Convert int to long java: In the previous article we have discussed Java Program to Convert int to String
In this article we will see how to convert an integer type to long type.
Program To Convert integer to long
Java convert int to long: Before going into the actual program, let’s see some example of both the types.
Example-: int type int a = 69; int b =126;
Example-: long type long a = 2322331L long b = 1234567890123456L
Let’s see different ways to do it.
Are you new to the java programming language? We recommend you to ace up your practice session with these Basic Java Programs Examples
Method 1 : Java Program to Convert int to long Using typecasting
int
type variable can be converted to long
by using typecasting. Let’s see how it actually works.
Here this method is also called widening typecasting because in this the lower data type int
is converted into the higher data type long
.
Approach :
- Take an int value and store it in an
int
variableinput1
- Typecast the variable with Long and store it 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 an int value through scanner class System.out.print("Enter an int value : "); int input1=sc.nextInt(); // converting to Long long output= input1; System.out.println("Converted Long value is : " + output); } }
Output : Enter a Int value : 666666 Converted Long value is : 666666
Method 2 : Java Program to Convert int to long Using valueof() method
int
type variable can be converted to Long by using valueof()
, let’s see how it actually works.
Here, the valueof()
method will convert the int
type variable into long variable & returns it.
Approach :
- Take an int type value and store it in an
int
variableinput1
. - Then pass that
input1
variable as parameter tovalueof()
method which will convert theint
tolong
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 an integer value through scanner class System.out.print("Enter an Int value : "); int input1=sc.nextInt(); // converting to Long long output= Long.valueOf(input1); System.out.println("Converted Long value is : " + output); } }
Output : Enter an Int value : 666666 Converted Long value is : 666666
Are you new to the java programming language? We recommend you to ace up your practice session with these Basic Java Programs Examples
Related Java Program: