Convert int to short in Java
Tags: int short Integer Convert
In this Java core tutorial, we learn how to convert int value into short value in Java program via different solutions.
Table of contents
How to cast int to short value in Java
In this first solution we try to cast an int value into short value as following Java example program.
ConvertIntToShortExample1.java
public class ConvertIntToShortExample1 {
public static void main(String[] args) {
int value1 = 99;
short value2 = (short)value1;
System.out.println("int value: " + value1);
System.out.println("short value: " + value2);
}
}
int value: 99
short value: 99
Using Integer.shortValue() method to get short value of an Integer object
The second solution below we use the shortValue() method from an Integer object to obtain the short value of Integer object.
ConvertIntToShortExample2.java
public class ConvertIntToShortExample2 {
public static void main(String[] args) {
Integer value1 = 27;
short value2 = value1.shortValue();
System.out.println("int value: " + value1);
System.out.println("short value: " + value2);
}
}
int value: 27
short value: 27
Happy Coding 😊