How to convert string to long in java

public class StringToLongExample 
{
    public static void main(String args[]) 
    {
        String s = "9990449935";
        long l = Long.parseLong(s);

        System.out.println(l);
    }
}

Step-by-Step Explanation

1.  Class Declaration:

The declaration of class StringToLongExample.

This is the main class, with the conversion logic of the string to long.

2.  Main Method:

  • This is the beginning of the method. The type of this method is static as it doesn’t use any reference variable. This method contains arguments.
  • The point of entry to a Java program, a function named as ‘main()’, declaring where in the program, one would start his or her execution.

3. Declaring Strings:

String s = “9990449935”;

  • Declaring a variable, s of type as ‘String’, with a declared value that equals ‘\”9990449935″‘;.
  • This is a number represented as a string. A number cannot be used as such, since it needs to be coerced into a numerical type and long would be the most suitable here .

4. Converting String to Long:

long l = Long.parseLong(s);

  • The Long.parseLong(s) is being used to convert the string s, which is “9990449935”, to a long value.
  • The string  “9990449935”  is parsed into the long value  9990449935, that is stored into variable l.

5. Output the Long Value:

System.out.println(l);

The println() function is called to print the value of l on the console. As l is a long type, it prints the numeric value of the long, which is 9990449935.

Program Output:

The following output will be printed to the console when the program executes:

9990449935

Explanation of the Output:

The method Long.parseLong(s) converts the string  “9990449935” into the long value 9990449935, which is then printed in the console.

Key Points

  • Long.parseLong(s) : This method is used for the conversion of a string that consists of a numeric value to a long data type.
  • The string must represent a valid number. If the string cannot be parsed into a valid number (for example, if it contains letters or special characters), it will throw a NumberFormatException.

Example:

String s = “9990449935”;        // String containing a large numeric value

long l = Long.parseLong(s);     // Convert the string to long

System.out.println(l);          // Print the long value: 9990449935

Leave a Comment

Your email address will not be published. Required fields are marked *