The code prompts the user to enter a string representing a number, then converts the string to a long data type using two different methods and prints out the results.
The Long.valueOf(str).longValue() method first converts the string str to a Long object using the valueOf() method and then retrieves the long value of the object using the longValue() method. This method can throw a NumberFormatException if the string cannot be parsed as a long.
The Long.parseLong(str) method directly converts the string str to a long primitive data type. This method can also throw a NumberFormatException if the string cannot be parsed as a long.
Note that if the input string represents a number that is outside the range of the long data type, an error may occur or the output may not be accurate.
import java.util.Scanner; public class StringToLong { public static void main(String args[]) { Scanner input = new Scanner(System.in); String str; System.out.print("Enter the Number : "); str = input.next(); System.out.println("String Value : " + str); long long_val = 0; //longValue() Method 1 long_val = Long.valueOf(str).longValue(); System.out.println("Long Value Using longValue() Method : " + long_val); //parseLong() Method 2 long_val = Long.parseLong(str); System.out.println("Long Value Using parseLong() Method : " + long_val); } }
Enter the Number : 123456 String Value : 123456 Long Value Using longValue() Method : 123456 Long Value Using parseLong() Method : 123456
Learn All in Tamil © Designed & Developed By Tutor Joes | Privacy Policy | Terms & Conditions