Convert from String to long in Java


To convert String to long, the following are the two methods.

Method 1

The following is an example wherein we use parseLong() method.

Example

 Live Demo

public class Demo {
   public static void main(String[] args) {
      String myStr = "5";
      Long myLong = Long.parseLong(myStr);
      System.out.println("Long: "+myLong);
   }
}

Output

Long: 5

Method 2

The following is an example wherein we have used valueOf() and longValue() method to convert String to long.

Example

 Live Demo

public class Demo {
   public static void main(String[] args) {
      String myStr = "20";
      long res = Long.valueOf(myStr).longValue();
      System.out.println("Long: "+res);
   }
}

Output

Long: 20

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 26-Jun-2020

183 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements