Convert String into long in java

In this section, we are going to convert numeric type string data into long.

Convert String into long in java

In this section, we are going to convert numeric type string data into long.

Convert String into long in java

Convert String into long in java

In this section you will learn about conversion of numeric type String data into long in java. Converting string to long is similar to converting string to int in java, if you convert string to integer then you can convert string to long by the following same procedure. You need to know that long is a primitive type which is wrapped by Long wrapper class and String is an object that is  a sequence of character.

Converting  String to long using valueOf() method :

You can convert string to long  using valueOf() method of  java.lang.Long class which accept string as argument and return a equivalent Long primitive value. If you provide the wrong input , by wrong input  means that providing a non-numeric input to string or passing the value which is  beyond the range then, the NumberFormatException is thrown.

long value = Long.valueOf("1234");

Converting String into long using parseLong() :

The parseLong() is another method from java.lang.Long class which convert String in to Long value. parseLong() also throws NumberFormatException if the String provided is not converted into long. It also support a overloaded method to which accept octal, hexadecimal long value to String format. parseLong() is widely used for conversion from String to long in java. parseLong() also take negative value as input in the argument as the first character.

long value = Long.parseLong("1234");

A simple example using both these methods :

public class StringToLong {
	public static void main(String args[])
	{
		//Conversion using parseLong method
		long value=Long.parseLong("1234");
		System.out.println("Using parseLong() -> "+value);
		
		//conversion using valueOf method
		
		String str="1234";
		long val=Long.valueOf(str);
		System.out.println("Using Valueof() -> "+val);
	}
}

Output from the program :

Download SourceCode