Java int to long

To convert an int to a long in Java, you can use one of the following methods. I’ll explain each approach and show how it works.

1. Implicit Conversion (Widening Conversion)

Java automatically converts a smaller data type (such as int) to a larger one (such as long) without any explicit casting. This is known as widening conversion. The conversion from int to long happens automatically because the long type can hold a larger range of values than int.

Example:


public class IntToLongExample {
    public static void main(String[] args) {
        int intValue = 456;  // 'int' type (32 bits)
        
        // Implicit conversion from int to long (no casting needed)
        long longValue = intValue;  // 'long' type (64 bits)
        
        System.out.println(longValue);  // Output: 456
    }
}

Explanation: In the above code, we declare an int value (intValue) and assign it to a long variable (longValue). Java automatically converts the int to a long because the long type can accommodate any int value, and there is no risk of data loss.

2. Explicit Casting

While implicit conversion works automatically for int to long, you can also use explicit casting. However, for this specific case (from int to long), explicit casting is unnecessary because it is safe and automatic. Still, I’ll show you how to do it:

Example:


public class IntToLongExample {
    public static void main(String[] args) {
        int intValue = 456;  // 'int' type
        
        // Explicit casting (not necessary, but works)
        long longValue = (long) intValue;  // Explicit type casting to long
        
        System.out.println(longValue);  // Output: 456
    }
}

Explanation: Here, (long) is used to explicitly convert the int to a long. While this works fine, it is not required in this case because of the widening conversion. Java would have done this automatically.

3. Using Long.valueOf() Method (Wrapper Class)

If you’re dealing with wrapper classes or need an Long object (instead of a primitive long), you can use the Long.valueOf() method. This is typically used when you need to work with objects or store values in collections like ArrayList.

Example:


public class IntToLongExample {
    public static void main(String[] args) {
        int intValue = 456;  // 'int' type
        
        // Convert to Long object using Long.valueOf()
        Long longObjectValue = Long.valueOf(intValue);  // Returns a Long object
        
        System.out.println(longObjectValue);  // Output: 456
    }
}

Explanation: Long.valueOf(intValue) converts the int to a Long object. This is useful when you need to work with Long objects (for example, if you’re working with collections like List). Unlike the previous two examples, this creates a Long object, not a primitive long.