How to convert String to long in Java

How to convert String to long in Java

Example:

Input:  num="1320"
Output: 1320

Approach: 1 : Using parseLong()

Java


public class StringToLong {
    public static void main(String[] args) {
        String num = "1320";
        long numLong = stringToLong(num);
        System.out.println("Long is " + numLong);
    }

    private static long stringToLong(String num) {
        return Long.parseLong(num);
    }

}

Approach : 2: Using valueOf()

Java


public class StringToLong {
    public static void main(String[] args) {
        String num = "1320";
        long numLong = stringToLong(num);
        System.out.println("Long is " + numLong);
    }

    private static long stringToLong(String num) {
        return Long.valueOf(num);
    }

}


No comments:

Post a Comment