How to convert int to long in Java?

Simple hint on very often question how to convert 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);
    }
}

The output will be:

    1000

How to convert int to Long in Java?

When we want to convert primitive int datatype to Long object, there are 2 different ways how 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);
    }
}

The output will be:

    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.