Sunday, September 7, 2025
HomeLanguagesJavaJava.lang.Long.valueOf() method with examples

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 arguments were given to the parseLong(java.lang.String, int) method. It returns a result that is a Long object that represents the long value specified by the string.

Syntax:

public static Long valueOf(String s, int radix) throws NumberFormatException

Parameters: The method accepts two mandatory parameters:

  • S: This refers to the string which is to be parsed.
  • radix: This refers to the radix which is to be used in interpreting the string S.

Return type: The built-in method returns a Long object holding the value represented by the string argument in the specified radix.

Errors and Exception:

  • NumberFormatException: If the number does not contain a parsable long the program returns.

Below programs illustrate the Java.lang.Long.valueOf() method.

Program 1:




// Java program to demonstrate
// the java.lang.Long.valueOf() method
import java.lang.Math;
  
class Gfg1 {
  
    // driver code
    public static void main(String args[])
    {
        Long l = new Long(10);
        String str = "45325";
  
        // returns a Long instance representing 
        // the specified string with radix 10
        System.out.println("Long instance Value = " 
                               + l.valueOf(str, 10));
    }
}


Output:

Long instance Value = 45325

Program 2:




// Java program to demonstrate
// of java.lang.Long.valueOf() method
// NumberFormatException
import java.lang.Math;
  
class Gfg1 {
  
    // driver code
    public static void main(String args[])
    {
        Long l = new Long(10);
  
        // not a parsable long
        String str = "gopal";
  
        // returns a Long instance representing 
        // the specified string with radix 10
        System.out.println("Long instance Value = " 
                               + l.valueOf(str, 10));
    }
}


Output:

Exception in thread "main" java.lang.NumberFormatException: For input string: "gopal"
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
    at java.lang.Long.parseLong(Long.java:589)
    at java.lang.Long.valueOf(Long.java:776)
    at Gfg1.main(File.java:15)
RELATED ARTICLES

Most Popular

Dominic
32271 POSTS0 COMMENTS
Milvus
82 POSTS0 COMMENTS
Nango Kala
6641 POSTS0 COMMENTS
Nicole Veronica
11807 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11870 POSTS0 COMMENTS
Shaida Kate Naidoo
6755 POSTS0 COMMENTS
Ted Musemwa
7030 POSTS0 COMMENTS
Thapelo Manthata
6705 POSTS0 COMMENTS
Umr Jansen
6721 POSTS0 COMMENTS