Menu

How to Convert int to long in Java?

How to convert Java int to long

In Java, an int value can be converted into a long value by using the simple assignment operator. This is because this conversion is an Implicit type conversion in which a lower data type is automatically converted into a higher data type.

Example 1:

Here, the int value is converted into long value implicitly by using the assignment operator.

public class StudyTonight
{  
    public static void main(String args[])
    {  
        int i = 500;  
        long l = i;  
        System.out.println(" The long value is : " +l); 
    }
}

Output:

The long value is : 500

Also, we can convert an int value into a Long Object either by instantiating Long class or by using the Long.valueOf() method.

Example 2:

Here, the int value is converted into the Long Object by instantiating the class and using valueOf() method.

public class StudyTonight
{  
    public static void main(String args[])
    {  
        int i = 200;  
        long l = Long.valueOf(i); //conversion using the valueOf() method  
        System.out.println(i);  
        System.out.println(l);  
    }
}

Output:

200 200

Example 3:

Here, the int value is converted into long values implicitly by instantiating the long value.

public class StudyTonight
{  
    public static void main(String args[])throws Exception
    {  
        int n = 232;
        long l = new Long(n);
        System.out.println("long value is : " +l);
    }
}

Output:

long value is : 232