Convert int to long java – Java Program to Convert int to long

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 :

  1. Take an int value  and store it in an int variable input1
  2. Typecast the variable with Long and store it in a variable output .
  3. 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 :

  1. Take an int type value and store it in an int variable input1.
  2. Then pass that input1 variable as parameter to valueof() method which will convert the int to long value and return it .
  3. Store that long value  in a variable output .
  4. 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: