How to convert String to long in Java?

To convert a string to a long in Java, you can use the parseLong() method of the java.lang.Long class. This method parses the string as a signed decimal long, and returns the resulting long value.

Here is an example of how you can use parseLong() to convert a string to a long:

import java.util.Scanner;

public class StringToLongExample {
  public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    System.out.print("Enter a long: ");
    String input = in.nextLine();
    long value = Long.parseLong(input);
    System.out.println("The long value is: " + value);
  }
}

If the string is not a valid representation of a long, parseLong() will throw a NumberFormatException. You can catch this exception and handle it appropriately, like this:

import java.util.Scanner;

public class StringToLongExample {
  public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    System.out.print("Enter a long: ");
    String input = in.nextLine();
    try {
      long value = Long.parseLong(input);
      System.out.println("The long value is: " + value);
    } catch (NumberFormatException e) {
      System.out.println("Invalid long: " + input);
    }
  }
}

Note that parseLong() only works for strings that represent decimal longs. If the string represents a long in another number system (such as hexadecimal or binary), you can use the valueOf() method of the java.lang.Long class, which takes an additional parameter specifying the number system, to parse the string.

For example, to parse a hexadecimal string as a long, you can do the following:

import java.util.Scanner;

public class StringToLongExample {
  public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    System.out.print("Enter a hexadecimal long: ");
    String input = in.nextLine();
    try {
      long value = Long.valueOf(input, 16);
      System.out.println("The long value is: " + value);
    } catch (NumberFormatException e) {
      System.out.println("Invalid long: " + input);
    }
  }
}

This example parses a hexadecimal string as a long, and prints the resulting long value.