Java convert byte to short
In this Java core tutorial we learn how to convert a byte value to a short value with different solutions in Java programming language.
Table of contents
- Assign byte variable to short variable in Java
- Using Byte.shortValue() method
- Using Short.valueOf() method
Assign byte variable to short variable in Java
In this first solution to convert a byte value to a short value we just simply assign the byte variable to the short variable as the following Java program.
ConvertByteToShortExample1.java
public class ConvertByteToShortExample1 {
public static void main(String... args) {
byte byteValue = 11;
short shortValue = byteValue;
System.out.println("byte value: " + byteValue);
System.out.println("short value: " + shortValue);
}
}
byte value: 11
short value: 11
Using Byte.shortValue() method
In this second solution, with a given Byte object we can convert it to short value using the Byte.shortValue() method as the following example Java code.
ConvertByteToShortExample2.java
public class ConvertByteToShortExample2 {
public static void main(String... args) {
Byte byteValue = 69;
short shortValue = byteValue.shortValue();
System.out.println("byte value: " + byteValue);
System.out.println("short value: " + shortValue);
}
}
byte value: 69
short value: 69
Using Short.valueOf() method
In this third solution, we can use the Short.valueOf(short s) static method to create a new Short object from a given byte value as the following Java code.
ConvertByteToShortExample3.java
public class ConvertByteToShortExample3 {
public static void main(String... args) {
byte byteValue = 67;
Short shortValue = Short.valueOf(byteValue);
System.out.println("byte value: " + byteValue);
System.out.println("short value: " + shortValue);
}
}
byte value: 67
short value: 67
Happy Coding 😊
Related Articles
Java convert short to BigInteger