How to convert int to long in Java?

This article is a simple hint on the often asked question of converting int to long or Long in Java.

How to convert int to long in Java?

When we want to convert primitive int datatype to primitive long data type, all we need to do is just assign primitive int to primitive long variable. Nothing else is necessary. Converting primitive data type from higher to lower data type is implicit.

Let’s look on the example how to convert int to long in Java:

public class Main {
    public static void main(String args[]) {
        int primitiveInt = 1000;
        long primitiveLong = primitiveInt;
        System.out.println(primitiveLong);
    }
}

Output

1000

How to convert int to Long in Java?

When we want to convert primitive int datatype to a Long object, there are two different ways to do it.

We can:

  • instantiate new Long class over int constructor.
  • use a static method to extract primitive int and create a new Long object (calling Long.valueOf() method).

Let’s look on the example how to convert int to long in Java:

public class Main {
    public static void main(String args[]) {
        int primitiveInt = 1000;

        // Option #1 - constructor initiation
        final Long objectLong = new Long(primitiveInt);
        // Option #2 - use static method
        final Long objectLongOther = Long.valueOf(primitiveInt);

        System.out.println(objectLong);
        System.out.println(objectLongOther);
    }
}

Output

1000
1000
This entry was posted in Tips & tricks and tagged , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

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