×

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

Generics in Java

Generics in Java Parameterizedtypes mean generic. Generics allow types (Character, Integer, String, …, etc., as well as user-defined types) to act as parameters to interfaces, classes, and methods. Generics in Java...

9 minutes read.

Java Output Formatting

Sometimes we want a program's output to be displayed in a specific format. The printf () function in the C programming language can be used to achieve this. We will...

4 minutes read.

Interfaces and Classes in Strings in Java

CharBuffer: CharBuffer is utilized to implement the CharSequence interface. With the help of the mentioned class, we can allow character buffers to be utilized instead of CharSequences. We can consider the illustration...

4 minutes read.

Method Overriding in Java

Overriding  Overriding is also known as run time polymorphism, and it is about the same method with the same signatures in different classes. Overriding can be applied only methods. Method Overriding Method Overriding...

8 minutes read.

Morris Traversal for Preorder in Java

Without the use of recursion or stacks, we traverse a tree using the Morris algorithm. The linked binary tree is the foundation of the Morris traversal. Preorder Morris Traversal Algorithm The preorder...

3 minutes read.

Figurate Number in Java

There have been several uses for figurate or figural numerals throughout history. A number that may be expressed by regular, distinct geometric shapes with spaced evenly points is referred to...

4 minutes read.

Java Program to Create Set of Pairs Using HashSet

HashSet in Java: HashSet is an assortment in Java that has a place with java.util bundle. It inside utilises HashMap to store components. It is an execution of the Set connection...

11 minutes read.

How to check Date is Greater in Java?

In this article, you will be acknowledged about how to check if the given date is greater than the other date or not. We are simply comparing the dates and...

7 minutes read.

Java Password Generator

Generally, we must create a strong password for security reasons. In Java, there are numerous strategies for creating secure passwords. We will learn how to create a strong password in...

4 minutes read.

Convert IP to Binary in Java

Fundamental conversion, such as going from binary to decimal or vice versa, is a crucial activity in computers. Understanding IP addressing and subnetting is crucial for networking. The primary networking...

4 minutes read.

How Many Ways to Create an Object in Java?

As you know, a class is a blueprint for an object, and you can create objects from it. There are several ways to create objects of classes in Java. This...

6 minutes read.

Types of Sockets in Java

The fundamental idea behind Java's networking capability is the socket. Early in the 1980s, the Berkeley UNIX 4.2BSD version included the socket paradigm. Berkeley socket is the term employed as...

9 minutes read.

Java Numbers

We use primitive data types like byte, int, long, double, etc to work with the numbers, When we need objects, we use wrapper class like Integer, Double, Long, Byte, etc....

2 minutes read.

Prepared statement in Java

Prepared statement: A prepared statement is a statement that is pre-compiled SQL statement, and it is a sub-interface of a statement. Compared to other statement objects in java, Prepared Statement objects have...

3 minutes read.

Java Integer parseInt() method

The parseInt() method of Java Integer class parses the CharSequence argument as a signed decimal integer. The second parameter parses the string argument as a signed integer in the radix specified...

2 minutes read.

GCD of Different SubSequences in Java

The positive numbers are provided in an array called inArr. The aim is to determine the number of distinct GCDs (Greatest Common Divisors) in each subsequence present in the input...

4 minutes read.

Reserved Keywords in Java

In Java, a reserved term is used as a code key called a keyword. Because they are predefined, these terms cannot be used for anything else. They cannot serve as...

3 minutes read.

Java Integer signum() method

The signum() method of Java Integer class returns the signum function of the specified int value. Syntax public static int signum (int i)  Parameters The parameter ‘i’ represents the value whose signum is to...

1 minute read.

Nested Enum in Java

A class that can be defined within another class is called a nested class in Java. You can logically group classes that are used onlyin one place. This makes encapsulation...

3 minutes read.

Compile-time Error in Java

In java, the execution of a program is stopped due to the occurrence of some problem known as an error. Errors are illegal operations that are carried out by the...

4 minutes read.