How to Convert String to Long in Java

Open the IDE., Copy and paste the following code: class Convert { public static void main(String[] args) { try { String str = "124863"; long num = (Long.parseLong(str))+36; System.out.println(num); } catch(NumberFormatException e) {...

4 Steps 1 min read Easy

Step-by-Step Guide

  1. Step 1: Open the IDE.

    Open your IDE of choice, or use a text editor and the command line to write and run the code. ,, The output will be
    124899., Once you know what each line means, you can adapt it for other purposes.

    You declare a String variable str with the value "124863".

    Next, you use the wrapper class for Long to parse the String value, assign it to a new Long variable num, and add 36 to the assigned value.

    Then you print the new Long value of variable num as
    124899.

    You use the try-catch block to counter a NumberFormatException and print a corresponding error message.
  2. Step 2: Copy and paste the following code: class Convert { public static void main(String[] args) { try { String str = "124863"; long num = (Long.parseLong(str))+36; System.out.println(num); } catch(NumberFormatException e) { System.out.println("Invalid String for conversion to long"); } } }

  3. Step 3: Run the program.

  4. Step 4: Understand what the program does.

Detailed Guide

Open your IDE of choice, or use a text editor and the command line to write and run the code. ,, The output will be
124899., Once you know what each line means, you can adapt it for other purposes.

You declare a String variable str with the value "124863".

Next, you use the wrapper class for Long to parse the String value, assign it to a new Long variable num, and add 36 to the assigned value.

Then you print the new Long value of variable num as
124899.

You use the try-catch block to counter a NumberFormatException and print a corresponding error message.

About the Author

L

Laura Ferguson

Writer and educator with a focus on practical practical skills knowledge.

35 articles
View all articles

Rate This Guide

--
Loading...
5
0
4
0
3
0
2
0
1
0

How helpful was this guide? Click to rate: