Signup/Sign In
LAST UPDATED: DECEMBER 1, 2020

How to convert Java String to long

In Java, a String can be converted into a long value by using the Long.parseLong() method and using the Long.valueOf() method.

Java Long.parseLong() Method

The parseLong() method is a part of the Long class. It is a static method and is used to convert the String into a long value.

Example 1:

Here, a string value is converted into the long value by using the parseLong() method.

public class StudyTonight
{  
	public static void main(String args[])
	{  
		String s = "454"; //String Decleration 
		long i = Long.parseLong(s);  // Long.parseLong() converts the string into long
		System.out.println(i);  
	}
} 


454

Java Long.valueOf() Method

The valueOf() method is a part of Long class. This method is used to convert a String into a Long Object.

Example 2:

Here, a String value is converted into a long value. See the example below.

public class StudyTonight
{  
	public static void main(String args[])
	{  
		try
		{
			String s1 = "500"; //String declaration 
			Long i1 = Long.valueOf(s1);  // Long.valueOf() method converts a String into Long
			System.out.println(i1);       
			String s2 = "mohit"; //NumberFormatException
			Long i2 = Long.valueOf(s2);
			System.out.println(i2);
		}
		catch(Exception e)
		{
			System.out.println("Invalid input");
		}
	}
}


500
Invalid input

Conversion By using longValue() method Example

Here, a String value is converted into a long value by using the longValue() method that returns a long value of Long object. See the example below.

public class StudyTonight
{  
	public static void main(String args[])
	{  
		String s="454"; //String Decleration 
		Long obj = new Long(s);
		long n = obj.longValue(); 
		System.out.println("Long value is : " +n );
	}
} 


Long value is : 454



About the author:
A Computer Science and Engineering Graduate(2016-2020) from JSSATE Noida. JAVA is Love. Sincerely Followed Sachin Tendulkar as a child, M S Dhoni as a teenager, and Virat Kohli as an adult.