To convert an int
to a long
in Java, you can simply assign the int
value to a long
variable, as a long
can hold larger values than an int
.
Here’s an example:
int myInt = 42; long myLong = myInt;
In this example, the int
value 42
is assigned to the myInt
variable. The next line assigns the value of myInt
to the myLong
variable, which automatically converts the int
value to a long
value.
Alternatively, you can use the long
constructor to explicitly convert the int
to a long
:
int myInt = 42; long myLong = (long) myInt;
In this example, the (long)
casts the myInt
value to a long
value before it is assigned to myLong
.
Java int to long Example:
Sure, here’s an example of how to convert an int
to a long
in Java:
int myInt = 42; long myLong = myInt; System.out.println("My int value: " + myInt); System.out.println("My long value: " + myLong);
In this example, we first declare an int
variable named myInt
with a value of 42
. We then declare a long
variable named myLong
and assign the value of myInt
to it. This causes the int
value to be automatically converted to a long
value.
Finally, we print out both variables using System.out.println()
to verify the conversion:
My int value: 42 My long value: 42
As you can see, the int
value of 42
was successfully converted to a long
value and assigned to the myLong
variable.