×

How to Convert String to long in Java

How to Convert String to long in java

It is used when you want to perform the mathematical operation on the String which contains long number then the conversion from String to long is necessary. When you get the data from the text field, it received as a string. You can convert String to long in three ways:

  • Using Long.parseLong() method
  • Using Long.valueOf() method
  • Using the constructor of Long class

Using Long.parseLong() method

The Long.parseLong() is a built-in, static method of java.lang package. It parses the String argument as a signed decimal long and returns a long value. The Syntax of the method is-

public static long parseLong(String s)

The parameter s will be converted to a primitive long value. It throws a NumberFormatException if the parameter is not a valid long. It is the most common method to convert String to long.

Remember

  • The first character must be a digit or a minus sign (-).
  • The value it returns is not an instance of the Long class.

Valid Conversion

  • String number=”-10123”;
  • String number=”10123”;

Invalid Conversion

  • String number=”10123a”;
  • String number=”a10123”;
  • String number=”abcde”;

If you are declaring a String as above, Long.parseLong () throws “NumberFormatException,” because it is not a valid conversion. 

Example

In this example, we have taken a String num having value “10000”. val is a variable of type long having value 100001. rslt is a variable that stores the value of num after conversion. Long is a class under java.lang package. parseLong() is a static method parses a String num as an argument.  Now the string has been converted into long type, So we can perform mathematical operation. The first println statement concatenates two variables i.e. num and val.  In the second println statement we are performing addition operation between rslt and val variable.

public class StringToLongExample
{
public static void main(String[] args)
{
String num = "10000";
long val=100001;
long rslt = Long.parseLong(num); //Conversion using parseLong() method
System.out.println("Before Conversion: " +num+val); //concatenation of num and val
System.out.println("After Conversion:" +(rslt+val)); //performing addition
}
}

Output

Before Converion:10000100001
After Conversion: 110001

Using Long.valueOf() method

Its working is similar to Long.parseLong() method. Long.valueOf() is a built-in and static method in java.lang package. It returns a Long object holding the value of the specified String. The value it returns is an instance of the Long class. The signature of the method is-

public static Long.valueOf(String s)

Example

Consider the following example, here we have taken two variables of type String str1 and str2 having value “11111” and “22222” respectively. num1 and num2 are two variables of type long store the value of str1 and str2 after conversion. The first println statement concatenates the two strings str1 and str2. Now we have the converted value of String, so we can perform addition. The second println statement prints the addition of num1 and num2 variable.

public class StringToLongExample1
{
public static void main(String[] args)
{
String str1 = "11111";
String str2 = "22222";
long num1 = Long.valueOf(str1);             //Conversion using valueOf(String) method
long num2 = Long.valueOf(str2);
System.out.println("Before Conversion: " +str1+str2);       //concatenation of Str1 and str2
System.out.println("After Conversion: " +(num1+num2));    //performing addition
}
}

Output

Before Conversion:  1111122222
After Conversion:  33333

Using the constructor of Long class

Another method to convert String to long is; to create the constructor of Long class and then invoke its longValue() method. It has a constructor that allows String argument and creates a new Long object. We can create constructor in the following forms-

String avg = "11111";
Long longObject = new Long(avg);
long number = longObject.longValue();

We can also write as: 

String avg = "11111";
long number = new Long(avg).longValue();

or

long number = new Long("11111").longValue();

Example

Consider the following example; we have taken two variables val1 and val2 of type String having values “10000” and “22222” respectively. num1 and num2 are two variables of type long which stores the long value of val1 and val2. new is a keyword that creates the object of Long class and having arguments val1 and val2 passing to it. The first println statement prints the concatenation of two strings val1 and val2. The second println statement prints the addition of variable num1 and num2.

public class StringToLongExample2
{
public static void main(String[] args)
{
String val1 = "10000";
String val2 = "22222";
long num1 = new Long(val1);     //Conversion using Long(String s) constructor
long num2 = new Long(val2);
System.out.println("Before Conversion: " +val1+val2);    //concatenation of num1 and num2
System.out.println("After Conversion: " +(num1+num2)); //performing addition
}
}

Output

Before Conversion: 1000022222
After Conversion: 32222

Related Topics

Difference between String and Char Array in Java

We are heading to examine some significant differences between String and Character arrays. Both char arrays and String hold the series of characters and are utilised as a cluster of...

3 minutes read.

Java Switch Keyword

In this article we are going to learn the concept of a java switch keyword. Generally, java case keyword is used with the switch statements or keyword.Switch keyword is implemented in...

3 minutes read.

Structure of Java Program

Java is well-known as an object-oriented, secure, and platform-independent programming language. The Java programming language allows us to construct a wide variety of programs. Therefore, it is essential to fully...

6 minutes read.

Java Solid Principles

Java implements the object-oriented SOLID principles for the design of software architecture. Solid Principles Java implements the object-oriented SOLID principles for the design of software architecture.   Five guiding principles transformed...

4 minutes read.

Static Array in Java

In this tutorial, we will study static arrays in Java. An array is a data structure that is of great importance in any programming language. It is classified into two...

3 minutes read.

Java String valueOf() method

Java String valueOf() method converts different types of values into String. Such as : int to String, long to String, boolean to String, character to String, float to String, double to...

2 minutes read.

Design of JDBC

Java applications may interface using database systems from many vendors using the Java Database Connectivity (JDBC) Application Software Interface (API) from Sun Microsystem. To connect spreadsheets, JDBC and database drivers...

3 minutes read.

Java Math sqrt() Method

The sqrt() method of Java Math class returns the accurately rounded positive square root of the specified double value. Syntax: public static double sqrt(double a) Parameters: The parameter ‘a’ represents the number whose square...

2 minutes read.

If Condition in Lambda Expression Java

The new and significant lambda expression feature of Java was added in Java SE 8. It provides a clear and concise mechanism for describing a single-method interface using an expression....

4 minutes read.

Java Anon Proxy

The Java Anon Proxy (JAP), also known as JonDonym, is a proxy system designed to enable Web browsing with revocable (the use of or publication under a pseudonym, a false...

4 minutes read.

Bounded buffer problem in Java

The Bounded buffer Problem can also be called a Producer consumer problem. The problem covers two processes—the producer and the consumer—that share a single, fixed-size buffer that serves as a...

4 minutes read.

Monsoon Umbrella Problem in Java

The Monsoon Umbrella problem is a classic Java programming problem used to test the skills of a programmer. The problem involves writing a program to determine the number of umbrellas...

3 minutes read.

Java String contains() method

contains() method returns true only if it contains the given sequence of characters otherwise it returns false. syntax: public boolean contains(CharSequence sequence) parameters: sequence : It is the sequence to be searched. Returns: It returns true...

1 minute read.

Method and Block Synchronization in Java

The Synchronization is performed in multi-threading concept. The multi-threading is a concept of parallel running of a program for the execution. In the multi-threading concept, the threads are run by...

3 minutes read.

Check the presence of Substring in a String in java

In java, the string can be treated as class and datatype. The string contains words and numbers but should be in double-quotes. Example: ” Omsairam” Substring The part of the string is called...

2 minutes read.

Moran Numbers in Java

In this article, we will be acknowledged about the moran numbers in Java, how they are formed, what are the approaches to achieve the moran numbers. Moran Number A moran numbers are...

3 minutes read.

Three Partition Problems in Java

In talks with leading IT organizations like Google, Amazon, TCS, Accenture, etc., this extremely intriguing subject is constantly brought up. The goal of the problem-solving exercise is to evaluate the...

8 minutes read.

Thread States in Java

An Item's Life Cycle (Thread States) A thread can be in any of the states mentioned above at any given time in Java. They are as follows: New Active I'm blocked or waiting Temporary...

3 minutes read.

Difference between = = and equals ( ) in java

Java : Java is a pure object oriented language. It was introduced by James Gosling in the year 1995. The first public implementation of java was done by sun micro systems...

6 minutes read.

Print Matrix Diagonally in Java

The aim is to print the elements of a matrix of size n*n in some kind of a diagonal pattern. Input : mat[3][3] = {{1, 2, 3},                      {4, 5, 6},                      {7,...

3 minutes read.