Core Java

Java int to long conversion

Converting data types is an essential aspect of programming in any language. In Java, developers often find themselves needing to switch between int and Long or vice versa, as discussed in our article. Although this process might appear simple, Java provides multiple methods with distinct features and applications. This tutorial aims to explore these methods, offering a comprehensive insight into their functionality and guidance on when to apply each one. Let us delve into the practical example to explore and understand Java int to long.

1. The Basics: Understanding int and Long

In many programming languages, including Java, C, C++, and others, int and long are fundamental data types used to represent integer values.

1.1 int

Typically, an int is a 32-bit signed integer. It can represent values in the range of approximately -2 billion to +2 billion. It is declared in Java as

int myInteger = 42;

1.1.1 Usage

It is used for storing whole numbers without any decimal points. Commonly used for indexing arrays, counting, and general-purpose integer arithmetic.

1.2 long

A long is usually a 64-bit signed integer. It can represent a much larger range of values compared to int. It is declared in Java as

long myLong = 123456789012345L;

The L at the end is used to explicitly indicate that the value is a long literal.

1.2.1 Usage

It is used when int is not sufficient to represent the required range of values. Useful for calculations that involve very large numbers. Commonly used in scenarios where a larger range of integers is needed, such as timestamp representation, large counters, or dealing with very large numbers.

2. Autoboxing: the Implicit Conversion

Autoboxing is a feature in Java that allows the automatic conversion of primitive data types to their corresponding wrapper classes, and vice versa. This feature simplifies code and makes it more convenient by eliminating the need for manual conversion between primitives and their wrapper classes. Here’s a brief explanation:

2.1 Primitive to Wrapper

When you assign a primitive value to an object of its wrapper class, autoboxing automatically converts the primitive to its wrapper class.

// Autoboxing: int to Integer
int primitiveInt = 42;

Integer wrapperInt = primitiveInt; // Autoboxing

2.2 Wrapper to Primitive

When you assign an object of a wrapper class to a primitive variable, the compiler automatically extracts the primitive value from the wrapper (unboxing).

// Autoboxing: Integer to int
Integer wrapperInt = 42;

int primitiveInt = wrapperInt; // Unboxing

2.3 Example

In the example below, autoboxing and unboxing are demonstrated for int to Integer and double to Double. The process is seamless and improves code readability by simplifying the conversion between primitive types and their corresponding wrapper classes.

public class AutoboxingExample {
  public static void main(String[] args) {
    // Autoboxing: int to Integer
    int primitiveInt = 42;
    Integer wrapperInt = primitiveInt; // Autoboxing

    // Autoboxing: double to Double
    double primitiveDouble = 3.14;
    Double wrapperDouble = primitiveDouble; // Autoboxing

    // Unboxing: Integer to int
    Integer anotherWrapperInt = 100;
    int anotherPrimitiveInt = anotherWrapperInt; // Unboxing

    // Unboxing: Double to double
    Double anotherWrapperDouble = 2.718;
    double anotherPrimitiveDouble = anotherWrapperDouble; // Unboxing

    // Display values
    System.out.println("Autoboxing Example:");
    System.out.println("Primitive Int: " + primitiveInt);
    System.out.println("Wrapper Int: " + wrapperInt);
    System.out.println("Primitive Double: " + primitiveDouble);
    System.out.println("Wrapper Double: " + wrapperDouble);
    System.out.println("Unboxing Example:");
    System.out.println("Another Wrapper Int: " + anotherWrapperInt);
    System.out.println("Another Primitive Int: " + anotherPrimitiveInt);
    System.out.println("Another Wrapper Double: " + anotherWrapperDouble);
    System.out.println("Another Primitive Double: " + anotherPrimitiveDouble);
  }
}



/* 
Output:
Autoboxing Example:
Primitive Int: 42
Wrapper Int: 42
Primitive Double: 3.14
Wrapper Double: 3.14
Unboxing Example:
Another Wrapper Int: 100
Another Primitive Int: 100
Another Wrapper Double: 2.718
Another Primitive Double: 2.718
*/

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

In Java, the Long.valueOf() method is a static method provided by the Long wrapper class. It is used to create a Long object from a long primitive or a string representation of a long value. This method is useful when you need to convert a primitive long value to its corresponding Long wrapper object.

Here’s an example demonstrating the usage of Long.valueOf():

public class LongValueOfExample {
    public static void main(String[] args) {
        // Using Long.valueOf() to create Long objects

        // From a long primitive
        long primitiveLong = 123456789L;
        Long wrapperLongFromPrimitive = Long.valueOf(primitiveLong);

        // From a String representation of a long value
        String longString = "987654321";
        Long wrapperLongFromString = Long.valueOf(longString);

        // Display values
        System.out.println("Using Long.valueOf():");
        System.out.println("Wrapper Long from Primitive: " + wrapperLongFromPrimitive);
        System.out.println("Wrapper Long from String: " + wrapperLongFromString);
    }
}



/* 
Output:
Using Long.valueOf():
Wrapper Long from Primitive: 123456789
Wrapper Long from String: 987654321
*/

In this example:

  • Long.valueOf(primitiveLong) creates a Long object from the primitive long value 123456789L.
  • Long.valueOf(longString) creates a Long object from the string representation "987654321".

4. Using new Long() Constructor: the Object Creation Method

In Java, the Long class also provides a constructor that allows you to create a Long object using the new keyword. This constructor takes a long value as its argument.

Here’s an example demonstrating the usage of the new Long() constructor:

public class NewLongConstructorExample {
    public static void main(String[] args) {
        // Using the new Long() constructor for object creation

        // Using a long primitive
        long primitiveLong = 123456789L;
        Long wrapperLongFromPrimitive = new Long(primitiveLong);

        // Display value
        System.out.println("Using new Long() Constructor:");
        System.out.println("Wrapper Long from Primitive: " + wrapperLongFromPrimitive);
    }
}



/*
Output:
Using new Long() Constructor:
Wrapper Long from Primitive: 123456789
*/

In this example, new Long(primitiveLong) creates a Long object from the primitive long value 123456789L.

It’s important to note that starting from Java 9, using the new Long() constructor for creating Long objects is discouraged, and the use of Long.valueOf() is recommended. This is because Long.valueOf() may cache and reuse instances for values within certain ranges, providing better performance and memory efficiency.

Here’s an updated version of the example using Long.valueOf():

Updated Version of Example

public class LongValueOfExample {
    public static void main(String[] args) {
        // Using Long.valueOf() to create Long objects

        // From a long primitive
        long primitiveLong = 123456789L;
        Long wrapperLongFromPrimitive = Long.valueOf(primitiveLong);

        // Display value
        System.out.println("Using Long.valueOf():");
        System.out.println("Wrapper Long from Primitive: " + wrapperLongFromPrimitive);
    }
}



/*
Output:
Using Long.valueOf():
Wrapper Long from Primitive: 123456789
*/

In practice, using Long.valueOf() is generally preferred over the new Long() constructor for creating Long objects.

5. Using Long.parseLong(): the String Conversion Method

In Java, the Long.parseLong() method is used to parse a String and convert it into a long primitive. This method is part of the Long class and is particularly useful when you need to convert a numeric representation in the form of a string to its corresponding long value.

Here’s an example demonstrating the usage of Long.parseLong():

public class LongParseLongExample {
    public static void main(String[] args) {
        // Using Long.parseLong() for string conversion

        // From a String representation of a long value
        String longString = "987654321";
        long primitiveLongFromString = Long.parseLong(longString);

        // Display value
        System.out.println("Using Long.parseLong():");
        System.out.println("Primitive Long from String: " + primitiveLongFromString);
    }
}



/* 
Output:
Using Long.parseLong():
Primitive Long from String: 987654321
*/

In this example, Long.parseLong(longString) converts the string "987654321" to a primitive long.

It’s important to note that Long.parseLong() can throw a NumberFormatException if the input string is not a valid representation of a long. Therefore, it’s a good practice to handle or catch this exception when using this method, especially if the input string may come from external sources or user input.

6. Convert int to Long

Here is a Java program that demonstrates the conversion of an int to a Long using various approaches:

public class IntToLongConversion {

    public static void main(String[] args) {
        int intValue = 42;

        // Autoboxing (Implicit Conversion)
        Long autoboxingResult = convertUsingAutoboxing(intValue);
        displayResult("Autoboxing", intValue, autoboxingResult);

        // Using Long.valueOf()
        Long valueOfResult = convertUsingValueOf(intValue);
        displayResult("Long.valueOf()", intValue, valueOfResult);

        // Using new Long() Constructor
        Long constructorResult = convertUsingConstructor(intValue);
        displayResult("new Long()", intValue, constructorResult);

        // Using Long.parseLong()
        Long parseLongResult = convertUsingParseLong(intValue);
        displayResult("Long.parseLong()", intValue, parseLongResult);
    }

    private static Long convertUsingAutoboxing(int intValue) {
        return (long) intValue;
    }

    private static Long convertUsingValueOf(int intValue) {
        return Long.valueOf(intValue);
    }

    private static Long convertUsingConstructor(int intValue) {
        return new Long(intValue);
    }

    private static Long convertUsingParseLong(int intValue) {
        String stringValue = Integer.toString(intValue);
        return Long.parseLong(stringValue);
    }

    private static void displayResult(String methodName, int originalValue, Long convertedValue) {
        System.out.println("Method: " + methodName);
        System.out.println("Original int value: " + originalValue);
        System.out.println("Converted Long value: " + convertedValue);
        System.out.println("------------------------------");
    }
}



/* 
Output:
Method: Autoboxing
Original int value: 42
Converted Long value: 42
------------------------------
Method: Long.valueOf()
Original int value: 42
Converted Long value: 42
------------------------------
Method: new Long()
Original int value: 42
Converted Long value: 42
------------------------------
Method: Long.parseLong()
Original int value: 42
Converted Long value: 42
------------------------------
*/

7. Conclusion

In conclusion, a fundamental understanding of data types is crucial in programming, and the distinction between int and Long serves a key role in managing integer values of varying ranges. The int data type is a 32-bit signed integer suitable for a wide range of everyday integer calculations, while the Long data type, a 64-bit signed integer, extends the range for scenarios requiring larger values. Transitioning between primitive types and their corresponding wrapper classes is facilitated by autoboxing, an implicit conversion mechanism that streamlines code and enhances readability. The Long.valueOf() method emerges as a powerful tool for creating Long objects, offering versatility by accepting both primitive values and string representations. Conversely, while the new Long() constructor provides an alternative approach for object creation, it is advised against modern Java development for reasons of efficiency and performance. Finally, the Long.parseLong() method shines as a reliable means for converting string representations of long values into their primitive counterparts, contributing to the flexibility and adaptability of Java programs. In summary, a nuanced comprehension of these concepts equips developers with the tools needed to handle integers effectively and interchangeably in various programming scenarios.

Yatin

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button