String to long conversion in Java – 3 ways

In this article, we will discuss various ways to convert String to Long in Java

 

What is the need of converting String to primitive long or Long wrapper-type ?

  • Generally, whenever we receive any data from web application then it is passed in the form of String only
  • To perform any mathematical operations on such numbers which are received as String, we need to convert into respective type for further calculation
  • This article explains about String to primitive long or Long wrapper-type conversion only, but we can do conversion for other types like int, double, float, boolean, etc
  • Note: Likewise, sometime Long to String conversion is also required

 

Various ways to convert String to Long

  1. using Long.parseLong(“strValue”);
  2. using Long.valueOf(“strValue”);
  3. Create Long object and then invoke longValue() method {i.e.; new Long(“strValue”).longValue();}

 

Exception scenario:

  • handle exception properly in all 3 ways
  • otherwise NumberFormatException will be thrown for incorrect string values (or not correctly formatted string)
  • and terminates program abruptly
  • we will see 3 different examples for all cases with E.1, E.2 and E.3

 

Auto-boxing and un-boxing feature from Java 1.5 version:

  • parseLong() method returns primitive long data-type but it can be easily used as Long wrapper-type
  • as auto-boxing feature helps to convert primitive data-type to respective wrapper-types
  • similarly, Long.valueOf() method returns Long wrapper-type but it can also be used as primitive long data-type
  • let’s see one example on this auto-boxing feature at the very end

 

Read String class in detail with example

 

Let us move forward and discuss all possible ways to convert String to Long in Java

Way 1: Using Long.parseLong(“strValue”); method

  • This method can be used to convert String which constitutes of only numbers (or digits) into primitive long data-type
  • Only sign is allowed, like minus (-)
  • If passed string isn’t correctly formatted then NumberFormatException will be thrown as shown in the below E.1 example

Method signature:

public static long parseLong(String s) throws NumberFormatException;

 

ConvertStringIntoLongUsingParseLongMethod.java

package in.bench.resources.string.to.longg.conversion;

public class ConvertStringIntoLongUsingParseLongMethod {

	public static void main(String[] args) {

		// String with only digits
		String str1 = "123456789012345";

		// 1. converting String to long
		long longValue1 = Long.parseLong(str1);
		System.out.println("1. Converted long value is : " + longValue1);


		// String with only digits and a minus sign (-)
		String str2 = "-123456789012345";

		// 2. converting String to long
		long longValue2 = Long.parseLong(str2);
		System.out.println("\n2. Converted long value is : " + longValue2);
	}
}

Output:

1. Converted long value is : 123456789012345

2. Converted long value is : -123456789012345

 

Way 2: Using Long.valueOf(“strValue”); method

  • This method can be used to convert String which constitutes of only numbers (or digits) into Long wrapper-type
  • Only sign is allowed, like minus (-)
  • If passed string isn’t correctly formatted then NumberFormatException will be thrown as shown in the below E.2 example

Method signature:

public static Long valueOf(String s) throws NumberFormatException;

 

ConvertStringIntoLongUsingValueOfMethod.java

package in.bench.resources.string.to.longg.conversion;

public class ConvertStringIntoLongUsingValueOfMethod {

	public static void main(String[] args) {

		// String with only digits
		String str1 = "987651234567890";

		// 1. converting String to Long
		Long longValue1 = Long.valueOf(str1);
		System.out.println("1. Converted Long value is : " + longValue1);


		// String with only digits and a minus sign (-)
		String str2 = "-987651234567890";

		// 2. converting String to Long
		Long longValue2 = Long.valueOf(str2);
		System.out.println("\n2. Converted Long value is : " + longValue2);
	}
}

Output:

1. Converted Long value is : 987651234567890

2. Converted Long value is : -987651234567890

 

Way 3: Create Long object and then invoke longValue() method

  • Here, we will create new Long object with String as constructor-argument
  • After creating new Long object by passing string-value, then invoke longValue() method for converting String to primitive long data-type
  • Passed string to constructor-argument should constitutes of only numbers (or digits)
  • Only sign is allowed, like minus (-)
  • If passed string isn’t correctly formatted then NumberFormatException will be thrown as shown in the below E.3 example

Method signature:

public Long(String s) throws NumberFormatException;

public long longValue();

 

ConvertStringIntoLongUsingLongValueMethod.java

package in.bench.resources.string.to.longg.conversion;

public class ConvertStringIntoLongUsingLongValueMethod {

	public static void main(String[] args) {

		// String with only digits
		String str1 = "545451234567890";

		// 1. converting String to long by creating new Long Object
		Long long1 = new Long(str1);
		long longValue1 = long1.longValue();
		System.out.println("1. Converted long value is : " + longValue1);


		// String with only digits and a minus sign (-)
		String str2 = "-545451234567890";

		// 2. converting String to long by creating new Long Object
		Long long2 = new Long(str2);
		long longValue2 = long2.longValue();
		System.out.println("\n2. Converted long value is : " + longValue2);
	}
}

Output:

1. Converted long value is : 545451234567890

2. Converted long value is : -545451234567890

 

Exception scenarios:

  • In all above 3 cases, whenever string isn’t properly formatted to convert String to primitive long or Long wrapper-type, then NumberFormatException will be thrown
  • We will see, what happens if string isn’t correctly formatted for all 3 ways of conversion

 

Case E.1: Handle NumberFormatException while converting String to long using Long.parseLong() method

ParseLongMethodThrowsNFE.java

package in.bench.resources.string.to.longg.conversion;

public class ParseLongMethodThrowsNFE {

	public static void main(String[] args) {

		// String with only digits
		String str1 = "1234783557324423ben";

		// 1. converting String to long
		long longValue1 = Long.parseLong(str1);
		System.out.println("1. Converted long value is : " + longValue1);


		// String with only digits and a minus sign (-)
		String str2 = "-14345356767823ben";

		// 2. converting String to long
		long longValue2 = Long.parseLong(str2);
		System.out.println("\n2. Converted long value is : " + longValue2);
	}
}

Output:

Exception in thread "main" java.lang.NumberFormatException: 
For input string: "1234783557324423ben"
	at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
	at java.lang.Long.parseLong(Long.java:589)
	at java.lang.Long.parseLong(Long.java:631)
	at in.bench.resources.string.to.longg.conversion.ParseLongMethodThrowsNFE
.main(ParseLongMethodThrowsNFE.java:11)

 

Case E.2: Handle NumberFormatException while converting String to long using Long.valueOf() method

LongValueOfMethodThrowsNFE.java

package in.bench.resources.string.to.longg.conversion;

public class LongValueOfMethodThrowsNFE {

	public static void main(String[] args) {

		// String with only digits
		String str1 = "9876543210ben";

		// 1. converting String to Long
		Long longValue1 = Long.valueOf(str1);
		System.out.println("1. Converted Long value is : " + longValue1);


		// String with only digits and a minus sign (-)
		String str2 = "-9876543210ben";

		// 2. converting String to Long
		Long longValue2 = Long.valueOf(str2);
		System.out.println("\n2. Converted Long value is : " + longValue2);
	}
}

Output:

Exception in thread "main" java.lang.NumberFormatException: For input string: "9876543210ben"
	at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
	at java.lang.Long.parseLong(Long.java:589)
	at java.lang.Long.valueOf(Long.java:803)
	at in.bench.resources.string.to.longg.conversion.LongValueOfMethodThrowsNFE
.main(LongValueOfMethodThrowsNFE.java:11)

 

Case E.3: Handle NumberFormatException while converting String to long using longValue() method

LongValueMethodThrowsNFE.java

package in.bench.resources.string.to.longg.conversion;

public class LongValueMethodThrowsNFE {

	public static void main(String[] args) {

		// String with only digits
		String str1 = "54529813247848327ben";

		// 1. converting String to long by creating new Long Object
		Long long1 = new Long(str1);
		long longValue1 = long1.longValue();
		System.out.println("1. Converted long value is : " + longValue1);


		// String with only digits and a minus sign (-)
		String str2 = "-545229304832465ben";

		// 2. converting String to long by creating new Long Object
		Long long2 = new Long(str2);
		long longValue2 = long2.longValue();
		System.out.println("\n2. Converted long value is : " + longValue2);
	}
}

Output:

Exception in thread "main" java.lang.NumberFormatException: 
For input string: "54529813247848327ben"
	at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
	at java.lang.Long.parseLong(Long.java:589)
	at java.lang.Long.<init>(Long.java:965)
	at in.bench.resources.string.to.longg.conversion.LongValueMethodThrowsNFE
.main(LongValueMethodThrowsNFE.java:11)

 

What if we want to convert primitive long data-type to Long wrapper-type or vice-versa ?

  • Auto-boxing feature available from Java 1.5 version
  • So, converting primitive data-type to wrapper-type can easily be done, by directly assigning
  • Let’s see one example based on this auto-boxing feature

AutoBoxingFeatureForLongConversion.java

package in.bench.resources.string.to.longg.conversion;

public class AutoBoxingFeatureForLongConversion {

	public static void main(String[] args) {

		// String with only digits
		String str1 = "12345678901234567";

		// string to long conversion
		long longValue1 = Long.parseLong(str1);

		// 1. Auto-Boxing - converting long to Long
		long lAutoBoxing = longValue1;
		System.out.println("1. Auto-Boxing : " + lAutoBoxing);


		// String with only digits and a minus sign (-)
		String str2 = "-9876543210987654";

		// string to long conversion
		Long longValue2 = Long.parseLong(str2);

		// 1. Un-Boxing - converting long to Long
		long lUnBoxing = longValue2;
		System.out.println("\n2. Un-Boxing   : " + lUnBoxing);
	}
}

Output:

1. Auto-Boxing : 12345678901234567

2. Un-Boxing   : -9876543210987654

 

Hope, you found this article very helpful. If you have any suggestion or want to contribute any other way or tricky situation you faced during Interview hours, then share with us. We will include that code here.

 

References:

https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
https://docs.oracle.com/javase/tutorial/java/data/numberclasses.html
https://docs.oracle.com/javase/tutorial/java/data/autoboxing.html
https://docs.oracle.com/javase/tutorial/java/data/converting.html
https://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html
https://docs.oracle.com/javase/6/docs/api/java/lang/Long.html
https://docs.oracle.com/javase/7/docs/api/java/lang/Long.html
https://docs.oracle.com/javase/tutorial/java/data/strings.html
https://docs.oracle.com/javase/6/docs/api/java/lang/String.html
https://docs.oracle.com/javase/7/docs/api/java/lang/String.html
https://docs.oracle.com/javase/8/docs/api/java/lang/String.html
https://docs.oracle.com/javase/6/docs/api/java/lang/class-use/String.html
https://docs.oracle.com/javase/7/docs/api/java/lang/class-use/String.html
https://docs.oracle.com/javase/8/docs/api/java/lang/class-use/String.html
https://docs.oracle.com/javase/tutorial/essential/concurrency/immutable.html
https://docs.oracle.com/javase/tutorial/essential/concurrency/imstrat.html
http://docs.oracle.com/javase/7/docs/api/java/lang/NumberFormatException.html

 

Happy Coding !!
Happy Learning !!

Long to String conversion in Java - 6 ways
Double to String conversion in Java - 6 ways