Katerina Zamani

About Katerina Zamani

Katerina has graduated from the Department of Informatics and Telecommunications in National and Kapodistrian University of Athens (NKUA) and she attends MSc courses in Advanced Information Systems at the same department. Currently, her main academic interests focus on web applications, mobile development, software engineering, databases and telecommunications.

Java string to long Example

Long class forms the primitive type long, which can represent an integer number of 32 bits (2^32). A very common procedure in Java programming is the conversion of String to Long.

As you can expect, in this example we are going to show how to convert a string to long in every possible way.

 
 
 
 

1. Syntax of the convert operations

First of all, in order to convert a string to long, we can simply create a Long object by setting the specified string to its constructor. Otherwise you can use different operations, as you can see below:

It is worth to mention that if the string cannot be parsed, all the above operations throw a NumberFormatException.

2. Example of String to Long conversion

Create a new java file with the name StringToLongClass and paste the following code.

StringToLongClass.java:

package com.javacodegeeks.basics.stringtolong;

public class StringToLongClass {

	public static void main(String[] args) {
		
		String str = "1234567890123";
		
		Long longNum = new Long(str);
		System.out.println("Use of constructor: longNum = "+longNum.longValue());
		
		long long1 = Long.parseLong(str);
		System.out.println("Use of parseLong: long1 = "+long1);
		
		long l1 = Long.valueOf(str).longValue();
		System.out.println("Use of valueOf: l1 = "+l1);
		
		// with a specified radix
		long long2 = Long.parseLong("-AAAAAAAA", 16);
		System.out.println("Use of parseLong with 16 radix: long2 = "+long2);
		
		// returns a Long object. radix=36 for ISO basic Latin alphabet
		Long l2 = Long.valueOf("JCG", 36);
		System.out.println("Use of valueOf with 36 radix: l2 = "+l2);

		// for octal format use 0
		long decLong1 = Long.decode("0776");
		System.out.println("Use of decode with octal format: decLong1 = "+decLong1);
		
		// for hex format use 0x or 0X or #
		long decLong2 = Long.decode("0xFFFFFFFFE");
		System.out.println("Use of decode with hex format: decLong2 = "+decLong2);
		
		// exception conditions
		try {
			long long3 = Long.parseLong("FFC", 8);
		} catch (NumberFormatException e) {
			System.err.println("NumberFormatException in parseLong, "+ e.getMessage());
		}
				
		try {
			Long l3 = Long.valueOf("hi");
		} catch (NumberFormatException e) {
			System.err.println("NumberFormatException in valueOf, "+ e.getMessage());
		}
		
		try {
			Long decLong3 = Long.decode("#FFG");
		} catch (NumberFormatException e) {
			System.err.println("NumberFormatException in decode, "+ e.getMessage());
		}
				
	}

}

As you can see in the code above, we call parseLong() and valueOf() methods with the default decimal radix as well as with the use of a specified radix and a sign (+/-). For instance if the indicated radix is set to 16, a hexadecimal number is defined. Also notice that longValue() is used in the returned value of valueOf() operation, in order to transform the Long object to long data type. Now have a look to decode() operation. As we mentioned above, the leading zero indicates an octal number and 0x specifies a hexadecimal number.

Of course, we couldn’t disregard the exception conditions for the used methods. long3 throws an exception because the specified string can not be parsed as an octal number. In parallel l3 throws NumberFormatException too, because we just declare a string value without specifying the appropriate radix. Finally, decLong3 throws the same exception because "FFG" doesn’t represent a hexadecimal number.

Below, you can see the output of the execution.

Output:

Use of constructor: longNum = 1234567890123
Use of parseLong: long1 = 1234567890123
Use of valueOf: l1 = 1234567890123
Use of parseLong with 16 radix: long2 = -2863311530
Use of valueOf with 36 radix: l2 = 25072
Use of decode with octal format: decLong1 = 510
Use of decode with hex format: decLong2 = 68719476734
NumberFormatException in parseLong, For input string: "FFC"
NumberFormatException in valueOf, For input string: "hi"
NumberFormatException in decode, For input string: "FFG"

Download the source code

This was an example of string to long in Java. Download the source code of this example: StringToLongExample.zip

Related Whitepaper:

Java Essential Training

Author David Gassner explores Java SE (Standard Edition), the language used to build mobile apps for Android devices, enterprise server applications, and more!

The course demonstrates how to install both Java and the Eclipse IDE and dives into the particulars of programming. The course also explains the fundamentals of Java, from creating simple variables, assigning values, and declaring methods to working with strings, arrays, and subclasses; reading and writing to text files; and implementing object oriented programming concepts. Exercise files are included with the course.

Get it Now!  

Examples Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
All trademarks and registered trademarks appearing on Examples Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Examples Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.

Sign up for our Newsletter

20,709 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books