Languages
[Edit]
EN

Java - convert int to long

5 points
Created by:
Evie-Grace-Noble
621

Short solutions

Edit

Below we have full examples of how to convert int to long.

1. Using explicit long casting

Edit

Output:

2. Using implicit long casting

Edit

Output:

3. Using multiplication by long number

Edit

Output:

4. Convert to int to Long using Long constructor

Edit

Output:

Note:
Syntax of Long constructor:
public Long(long value)

As we can see this constructor get long as parameter, so in our case we just made casting from int to long.

When we see the hint from intellij idea, we will see 'Remove boxing' and when we apply it, our code will convert
from:
Long longNumber = new Long(number);

to:
Long longNumber = (long) number;

When we use new Long constructor with int parameter we get hint from intellij idea:

Unnecessary boxing 'Long.valueOf(number)' less... (Ctrl+F1)
Inspection info: Reports explicit boxing, i.e. wrapping of primitive values in objects. Explicit manual boxing is unnecessary under Java 5 and newer, and can be safely removed.
This inspection only reports if the project or module is configured to use a language level of 5.0 or higher.

5. Convert to int to Long using Long.valueOf()

Edit

Output:

Note:
The same hint from intellij idea as for Long constructor.

Syntax of Long.valueOf() method:
public static Long valueOf(long l)

Intellij idea, hint 'Remove boxing' will convert
from:
Long longNumber = Long.valueOf(number);

to:
Long longNumber = (long) number;

When we use Long.valueOf() we get hint from intellij idea:
Unnecessary boxing 'Long.valueOf(number)' less... (Ctrl+F1)

6. Convert Integer to Long using Integer longValue() method

Edit

Output:

 

1
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

Java conversion

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join