Java Integer shortValue() method
The shortValue() method of Java Integer class returns a short value for this Integer after a narrowing primitive conversion. Syntax public short shortValue () Parameters NA Overrrides: The shortValue () overrides : shortValue in class Number Return Value This method returns the numeric value represented by this object after conversion to type short. Example 1
public class JavaIntegerShortValueExample1 { public static void main(String[] args) { Integer val1=56; System.out.println(val1.shortValue()); //passing value greater than short's range Integer val2=18765459; //it will automatically the interger value into short after a narrowing primitive conversion. System.out.println(val2.shortValue()); } }Output
56 22163Example 2
public class JavaIntegerShortValueExample2 { public static void main(String[] args) { Integer val1=56; short x=val1.shortValue(); //converting int values to short Integer val2=98; short y=val2.shortValue(); //calling methods of Short class int sh=Short.compare(x,y); if(sh==0){ System.out.println(x+" and "+y+" are equal."); } else if (sh>0){ System.out.println(x+" is greater than "+y); } else{ System.out.println(y+" is greater than "+x); } } }Output
98 is greater than 56Example 3
public class JavaIntegerShortValueExample3 { public static void main(String[] args) { int val1=56; //int is a primitive type, its object can not be used to call Integer class methods else it will give an error short x=val1.shortValue(); System.out.println(x); } }Output
Error:(7, 21) java: int cannot be dereferenced