Hurry! Try our new Interactive Courses for FREE. 🥳   🚀

Java Long valueOf(String s) Method

Java valueOf(String s) method is a part of the Long class of the java.lang package. This method is used to return the Long object of the string value passed as an argument.

It must be noted that the argument is treated as a signed decimal long and the value returned by this method can be interpreted as new Long(Long.parseLong(s)).

Syntax:

public static Long valueOf(String s) throws NumberFormatException  

Parameters:

The parameter passed is the string whose equivalent Long object is to be returned.

Exception:

NumberFormatException: This exception occurs when the input string is not parsable.

Returns:

Returns the Long object of the String value passed as parameter.

Example 1:

Here, the Long object representations are returned of the String value passed.

import java.lang.Long;

public class StudyTonight 
{  
	public static void main(String[] args)throws NumberFormatException
	{  
		String s1 = "909";
		String s2 = "-253";
		System.out.println("Equivalent Long object Value = " + Long.valueOf(s1));//returns a Long object representing the String specified 
		System.out.println("Equivalent Long object Value = " + Long.valueOf(s2));//returns a Long object representing the String specified    
	}  
}


Equivalent Long object Value = 909
Equivalent Long object Value = -253

Example 2:

Here is a user-defined example where anyone using this code can put a value of his choice and get the equivalent output.

import java.lang.Long;
import java.util.Scanner;

public class StudyTonight 
{  
	public static void main(String[] args)
	{    
		try
		{
			System.out.println("Enter the string value");
			Scanner sc=new Scanner(System.in);
			String x = sc.next();
			System.out.println("Equivalent Long object Value = " + Long.valueOf(x));//returns a Long object representing the string specified 
		}
		catch(NumberFormatException e)
		{
			System.out.println("Invalid input!!");
		}
	}  
} 


Enter the string value
787
Equivalent Long object Value = 787
******************************************
Enter the string value
-212
Equivalent Long object Value = -212
******************************************
Enter the string value
0x676
Invalid input!!

Live Example:

Here, you can test the live code example. You can execute the example for different values, even can edit and write your examples to test the Java code.