In the previous article we have discussed Java Program to Convert String to int
In this article we will see how to convert string to long.
Program To Convert String to long
Before going into the program, let’s see some examples of both String and long type.
Example-1: String types String a = "b"; String b = "5643646442";
Examples-2: Long types long a = 56666L; long b = 5643646442;
Let’s see different ways to convert String to long.
Want to excel in java coding? Practice with these Java Programs examples with output and write any kind of easy or difficult programs in the java language
Method 1 : Java Program to Convert String to long Using parseLong() method
String
type variable can be converted to long by using parseLong()
method, let’s see how it actually works.
Here this method is a wrapper class in Java. This method of the Long class converts the String
variables into long
.
Approach :
- Take a string value and store it in a string variable
input1
. - Then pass that
input1
variable as parameter toparseLong()
method which will convert theString
intolong
value and return it . - Store that long value in a variable
output
. - Display the result .
Program:
import java.util.Scanner; public class Main { public static void main(String[] args) { // creating scanner object Scanner sc = new Scanner(System.in); // input a string value through scanner class System.out.print("Enter a string : "); String input1=sc.next(); // converting to long long output =Long.parseLong(input1) ; System.out.println("Converted long value is : " + output); } }
Output : Enter a string : 96666666 Converted long value is : 96666666
Method 2 : Java Program to Convert String to long Using valueOf() method
String
type variable can be converted to long by using valueOf()
method, let’s see how it actually works.
This method returns an object of the Long class. However, the object will be automatically converted into the primitive type.
Approach :
- Take a string value and store it in a string variable
input1
. - Then pass that
input1
variable as parameter toLong.valueOf()
method which will convert theString
intolong
value and return it . - Store that long value in a variable
output
. - Display the result .
Program:
import java.util.Scanner; public class Main { public static void main(String[] args) { // creating scanner object Scanner sc = new Scanner(System.in); // input a character through scanner class System.out.print("Enter a string : "); String input1=sc.next(); // converting to Long long output =Long.valueOf(input1) ; System.out.println("Converted Long value is : " + output); } }
Output : Enter a string : 96666666 Converted long value is : 96666666
Want to excel in java coding? Practice with these Java Programs examples with output and write any
kind of easy or difficult programs in the java language
Related Java Program: