How to convert String to long in Java

In this post, we will be looking at different ways of converting String to long in Java. We will first convert the String object into the Long wrapper class object in Java and but because of the unboxing feature of Java, that Long object will automatically be converted into the long primitive data type value.

Let’s look at all of the above-mentioned ways

Using Long.parseLong() method

Long wrapper class has a static method parseLong() in which we can pass the string and will return a Long in return.

Method declaration – public static long parseLong(String s).
What does it do? We pass a string into the function’s arguments and in turn, it will convert it into Long and return it back to the calling function. But if the string is invalid, then it will throw NumberFormatException.

public class Codekru {

	public static void main(String[] args) {
		String str = "12345678";
		long l = Long.parseLong(str);
		System.out.println(l);
		
	}
}

Output –

12345678

What if we pass an invalid String into the argument

public class Codekru {

	public static void main(String[] args) {
		String str = "1234codekru5678";
		long l = Long.parseLong(str);
		System.out.println(l);
		
	}
}

Output –

Exception in thread "main" java.lang.NumberFormatException: For input string: "1234codekru5678"

Using Long.valueOf() method

The Long class has one more static method which can also convert String into long.

Method declaration – public static Long valueOf(String s).
What does it do? – It also converts the String into long and throws NumberFormatException if the String passed is invalid.

public class Codekru {

	public static void main(String[] args) {
		String str = "123478";
		long l = Long.valueOf(str);
		System.out.println(l);
		
	}
}

Output –

123478

What if there is a negative number? Will our methods able to process it?

public class Codekru {

	public static void main(String[] args) {
		String str = "-123478";
		long l1 = Long.parseLong(str);
		long l2 = Long.valueOf(str);
		System.out.println(l1);
		System.out.println(l2);
	}
}

Output –

-123478
-123478

So, there will be no issues if we want to process negative numbers. 🙂

Using Long() constructor

We can convert String into long by directly using the Long() constructor but it is deprecated and we don’t recommend using it.

According to the documentation

Deprecated. It is rarely appropriate to use this constructor. Use parseLong(String) to convert a string to a long primitive, or use valueOf(String) to convert a string to a Long object.

public class Codekru {

	public static void main(String[] args) {
		String str = "12345678";
		long l = new Long(str);
		System.out.println(l);
	}
}

Output –

12345678

Hope you have liked the article. Please feel free to write us in comments or mail us at [email protected]

Liked the article? Share this on

Leave a Comment

Your email address will not be published.