Java convert long to short
In this Java core tutorial we learn how to convert a long value to short value with different solutions in Java programming language.
Table of contents
How to cast long to short in Java
In this first solution to convert a long value to short value we just simply cast the long variable to a short variable as the following Java code.
ConvertLongToShortExample1.java
public class ConvertLongToShortExample1 {
public static void main(String... args) {
long longValue = 999;
short shortValue = (short)longValue;
System.out.println("long value: " + longValue);
System.out.println("short value: " + shortValue);
}
}
long value: 999
short value: 999
Using Long.shortValue() method
In this second solution, with a given Long object we can use the Long.shortValue() method to return the short value as the example Java code below.
ConvertLongToShortExample2.java
public class ConvertLongToShortExample2 {
public static void main(String... args) {
Long longValue = 987L;
short shortValue = longValue.shortValue();
System.out.println("long value: " + longValue);
System.out.println("short value: " + shortValue);
}
}
long value: 987
short value: 987
Happy Coding 😊
Related Articles
Java convert short to BigInteger