The Wayback Machine - https://web.archive.org/web/20241126183544/https://www.geeksforgeeks.org/java-program-to-convert-string-to-long/
Open In App

Java Program to Convert String to Long

Last Updated : 21 Nov, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

To convert a String to Long in Java, we can use built-in methods provided by the Long class. In this article, we will learn how to convert String to Long in Java with different methods.  

Example:

In the below example, we use the most common method i.e. Long.parseLong() method to convert a string to a primitive long.

Java
// Java Program to convert String to Long using parseLong() Method

public class GFG {

    public static void main(String args[]) {
        
        // Creating a custom string
        String s = "999999999999";
        System.out.println("String: " + s);

        // Converting into Long
        long l = Long.parseLong(s);

        // Printing String as Long
        System.out.println("Long: " + l);
    }
}

Output
String: 999999999999
Long: 999999999999

Note: Long.parseLong() method is a method in which all the characters in the String must be digits except the first character, which can be a digit or a minus ‘-‘. 

Syntax of Long.parseLong() method

Long varLong = Long.parseLong(s);

Parameter:

  • str: A string containing numeric characters. It can include a leading “-" for negatives.

Return Type:

  • A long primitive representing the numeric value of the string.

Other Methods to Convert String to Long in Java

There are many other ways to convert a String to a Long data type in Java which are as follows:

1. Using Long.valueOf() Method

The valueOf() method of the Long class is a method that converts the String to a long value. Similar to parseLong(String) method, this method also allows minus ‘-‘ as a first character in the String.

Syntax of Long.valueOf() Method

long varLong = Long.valueOf(str);

Example:

Java
// Java Program to Convert String to Longn using valueOf() Method

public class GFG {

    public static void main(String args[])
    {
        
        // Creating custom string
        String s = "999999999999";

        // Printing the above string
        System.out.println("String - " + s);

        // Converting into Long data type
        long l = Long.valueOf(s);

        // Printing String as Long
        System.out.println("Long - " + l);
    }
}

Output
String - 999999999999
Long - 999999999999


2. Using Constructor of Long Class

The Long class has a constructor which allows the String argument and creates a new Long object representing the specified string in the equivalent long value. 

Example:

Java
// Java Program to Convert String to Long using Constructor of Long class
import java.io.*;
import java.util.*;

class GFG {

    public static void main(String[] args)
    {
        
        // Custom input string
        String s = "999999999";
        System.out.println("String - " + s);

        // Converting above string to long
        // using Long(String s) constructor
        long n = new Long(s);

        // Printing the above long value
        System.out.println("Long - " + n);
    }
}

Output
String - 999999999
Long - 999999999

Note: The Long(String s) constructor is deprecated since Java 9. It is recommended to use Long.parseLong() or Long.valueOf() for converting a String to long.



Previous Article
Next Article

Similar Reads

Java Math addExact(long x, long y) method
The java.lang.Math.addExact() is a built-in math function in java which returns the sum of its arguments. It throws an exception if the result overflows a long.As addExact(long x, long y) is static, so object creation is not required. Syntax : public static long addExact(long x, long y) Parameter : a : the first value b : the second value Return :
1 min read
Java Math subtractExact(long x, long y) method
The java.lang.Math.subtractExact() is a built-in math function in java which returns the difference of the arguments.It throws an exception if the result overflows a long.As subtractExact(long x, long y) is static, so object creation is not required. Syntax : public static long subtractExact(long x, long y) Parameter : x : the first value y : the s
1 min read
Java Guava | Longs.checkedSubtract(long a, long b) method with Examples
The checkedSubtract(long a, long b) is a method of Guava's LongMath Class which accepts two parameters a and b, and returns their difference. Syntax: public static long checkedSubtract(long a, long b) Parameters: The method accepts two long values a and b and computes their difference. Return Value: The method returns the difference of long values
2 min read
Duration ofSeconds(long, long) method in Java with Examples
The ofSeconds(long, long) method of Duration Class in java.time package is used to get a duration in a 1 second format. In this method, the seconds are calculated as total seconds in 1 second format, i.e. 1 second per second. The second parameter nanoAdjustment is used to adjust the seconds in nanoSeconds unit. Syntax: public static Duration ofSeco
2 min read
Java Guava | gcd(long a, long b) of LongMath Class with Examples
The method gcd(long a, long b) of Guava's LongMath Class returns the greatest common divisor of two parameters a and b. Syntax: public static long gcd(long a, long b) Parameters: This method accepts two parameters a and b of the long type of whose GCD is to be found. Return Type: This method returns the largest positive long value that divides both
2 min read
Java Guava | mean(long x, long y) of LongMath Class with Examples
The mean(long x, long y) method of Guava's LongMath Class accepts two parameters x and y and calculates arithmetic mean of them rounded towards negative infinity. This method is overflow resilient. Syntax: public static long mean(long x, long y) Parameters: This method accepts two parameters x and y which are of long type. Return Value: The method
2 min read
Java Guava | mod(long x, long m) of LongMath Class with Examples
The mod(long x, long m) method of Guava's LongMath Class accepts two parameters x and m, and used to calculate the value of x modulus under m. Syntax: public static long mod(long x, long m) Parameters: This method accepts two parameters x and m which are of long type to calculate x modulo m. Return Value: The method returns x mod m that will be a n
2 min read
Java Guava | LongMath.checkedAdd(long a, long b) method with Examples
The checkedAdd(long a, long b) is a method of Guava's LongMath Class which accepts two parameters a and b, and returns their sum. Syntax: public static long checkedAdd(long a, long b) Parameters: The method accepts two long values a and b and computes their sum. Return Value: The method returns the sum of long values passed to it, provided it does
2 min read
Java Guava | Longs.indexOf(long[] array, long[] target) method with Examples
Longs.indexOf(long[] array, long[] target) method of Guava's Longs Class accepts two parameters array and target. If the target exists within the array, the method returns the start position of its first occurrence. If the target does not exist within the array, the method returns -1. Syntax: public static int indexOf(long[] array, long[] target) P
3 min read
Java Guava | LongMath.divide(long, long, RoundingMode) method with Examples
The divide(long p, long q, RoundingMode mode) method of Guava's LongMath Class accepts three parameters and calculates the result of dividing first parameter by second parameter, rounded according to the rounding mode specified by the third parameter. Syntax: public static long divide(long p, long q, RoundingMode mode) Parameters: The method takes
3 min read
Java Guava | Longs.indexOf(long[] array, long target) method with Examples
Longs.indexOf(long[] array, long target) method of Guava's Longs Class accepts two parameters array and target. If the target exists within the array, the method returns the position of its first occurrence. If the target does not exist within the array, the method returns -1. Syntax: public static int indexOf(long[] array, long target) Parameters:
3 min read
Java Program to Convert Long to String
The long to String conversion in Java generally comes in need when we have to display a long number in a GUI application because everything is displayed in string form. In this article, we will learn about Java Programs to convert long to String. Given a Long number, the task is to convert it into a String in Java. Examples of Long-to-String Conver
4 min read
How to Convert a String to an Long in Java ?
In Java, String to Integer Conversion is not always effective as the size of the String can overpass Integer. In this article, we will learn the method provided by the Long class or by using the constructor of the Long class. Example of String to Long ConversionInput: " 9876543210"Output: 9876543210Program Convert String to Long in JavaThe Most bas
2 min read
Java Program to Convert long to int
Long is a larger data type than int, we need to explicitly perform typecasting for the conversion. Typecasting is performed through the typecast operator. There are basically three methods to convert long to int: By type-castingUsing toIntExact() methodUsing intValue() method of the Long wrapper class. 1. Using Explicit Type Casting In typing casti
3 min read
Java Program to Convert int to long
Given a number of int datatype in Java, your task is to write a Java program to convert this given int datatype into a long datatype. Example: Input: intnum = 5 Output: longnum = 5 Input: intnum = 56 Output: longnum = 56 Int is a smaller data type than long. Int is a 32-bit integer while long is a 64-bit integer. They both are primitive data types
2 min read
Java Program to Convert Double to Long
Given a Double real number. Write a Java program to convert the given double number into a Long (long) in Java. Examples: Input: double = 2545.241 Output: 2545 Input: double = 21.54 Output: 21 Double data type: The double data type is a double-precision 64-bit IEEE 754 floating-point. Its value range is endless. It is commonly used for decimal valu
4 min read
Java Program to Convert Byte Array to Long
A Java Byte Array is an array used to store byte data types only. The default value of each element of the byte array is 0. Given an array of bytes, convert it to a long value. Example: Byte Array: 1 2 3 4 Long Value: 16909060 Equivalent Hexadecimal String: 0x1020304 There are numerous approaches for converting a Byte Array to Long, and a few of th
3 min read
Convert Long Values into Byte Using Explicit Casting in Java
In Java, a byte can contain only values from -128 to 127, if we try to cast a long value above or below the limits of the byte then there will be a precision loss. 1. byte: The byte data type is an 8-bit signed two’s complement integer. Syntax: byte varName; // Default value 0 Values: 1 byte (8 bits) : -128 to 127 2. long: The long data type is a 6
2 min read
Java lang.Long.lowestOneBit() method in Java with Examples
java.lang.Long.lowestOneBit() is a built-in method in Java which first convert the number to Binary, then it looks for first set bit present at the lowest position then it reset rest of the bits and then returns the value. In simple language, if the binary expression of a number contains a minimum of a single set bit, it returns 2^(first set bit po
3 min read
Java lang.Long.numberOfTrailingZeros() method in Java with Examples
java.lang.Long.numberOfTrailingZeros() is a built-in function in Java which returns the number of trailing zero bits to the right of the lowest order set bit. In simple terms, it returns the (position-1) where position refers to the first set bit from the right. If the number does not contain any set bit(in other words, if the number is zero), it r
3 min read
Java lang.Long.numberOfLeadingZeros() method in Java with Examples
java.lang.Long.numberOfLeadingZeros() is a built-in function in Java which returns the number of leading zero bits to the left of the highest order set bit. In simple terms, it returns the (64-position) where position refers to the highest order set bit from the right. If the number does not contain any set bit(in other words, if the number is zero
3 min read
Java lang.Long.highestOneBit() method in Java with Examples
java.lang.Long.highestOneBit() is a built-in method in Java which first convert the number to Binary, then it looks for the first set bit from the left, then it reset rest of the bits and then returns the value. In simple language, if the binary expression of a number contains a minimum of a single set bit, it returns 2^(last set bit position from
3 min read
Java lang.Long.byteValue() method in Java with Examples
java.lang.Long.byteValue() is a built-in function in Java that returns the value of this Long as a byte. Syntax: public byte byteValue() Parameters: The function does not accept any parameter. Return : This method returns the numeric value represented by this object after conversion to byte type. Examples: Input : 12 Output : 12 Input : 1023 Output
3 min read
Java lang.Long.reverse() method in Java with Examples
java.lang.Long.reverse() is a built-in function in Java which returns the value obtained by reversing the order of the bits in the two's complement binary representation of the specified long value. Syntax: public static long reverse(long num) Parameter : num - the number passed Returns : the value obtained by reversing the order of the bits in the
2 min read
Java.Lang.Long class in Java
Long class is a wrapper class for the primitive type long which contains several methods to effectively deal with a long value like converting it to a string representation, and vice-versa. An object of Long class can hold a single long value. There are mainly two constructors to initialize a Long object- Long(long b): Creates a Long object initial
12 min read
Java Program to Convert String to String Array Using Regular Expression
Regular Expressions or Regex (in short) is an API for defining String patterns that can be used for searching, manipulating, and editing a string in Java. Email validation and passwords are few areas of strings where Regex is widely used to define the constraints. Regular Expressions are provided under java. util.regex package. This consists of 3 c
3 min read
Java Program to Convert String to String Array
Given a String, the task is to convert the string into an Array of Strings in Java. It is illustrated in the below illustration which is as follows: Illustration: Input: String : "Geeks for Geeks" Output: String[]: [Geeks for Geeks]Input: String : "A computer science portal" Output: String[] : [A computer science portal] Methods: They are as follow
6 min read
Java.lang.Long.valueOf() method with examples
Java.lang.Long.valueOf() is a built-in method in Java of lang class that returns a Long object holding the value extracted from a specified String S when parsed with the radix that is given in the second argument. The first argument is interpreted as representing a signed long in the radix specified by the second argument, exactly as if the argumen
2 min read
Java Math toIntExact(long value) Method
The java.lang.Math.toIntExact() is a built-in math function in java which returns the value of the long argument.It throws an exception if the result overflows an int.As toIntExact(long value) is static, so object creation is not required. Syntax : public static int toIntExact(long value) Parameter : value : the long value Return : This method retu
1 min read
Java lang Long.toOctalString() Method with Examples
The Java.lang.Long.toOctalString() function is a built-in function in Java that returns a string representation of the long argument as an unsigned integer in base 8. Syntax: public static int toOctalString(long num) Parameters: The function accepts a single mandatory parameter num, which is to be converted to a string. The parameter is of long dat
2 min read
three90RightbarBannerImg