Training Java – part 3 – conversion byte, short, int and long types

It is topic given execises in Java about conversion integer.

In this example you can see work conversion of short datatype in Java. Write this code:

public class Proba {

	public static void main(String[] ar ) {
short smin = Short.MIN_VALUE ;
short smax = Short.MAX_VALUE ;
 
System.out.print(" short min = ");  System.out.print(smin);
    System.out.println(); 
System.out.print(" short max = ");  System.out.print(smax);           
    System.out.println();    
System.out.print(" short min-1 = ");  System.out.print(smin-1);
    System.out.println();
}
} 

It displays result:

Notice that minimum value for short type is -32768, but in print method you substract 1, so it will be value behind scope. You don’t give any warning. Why? Because this value is converted automatically for integer type with larger range.

What is matter when you assign this value to short variable?

...
short smin = Short.MIN_VALUE ;
short smax = Short.MAX_VALUE ;
 
System.out.print(" short min = ");  System.out.print(smin);
    System.out.println(); 
System.out.print(" short max = ");  System.out.print(smax);           
    System.out.println();    
System.out.print(" short min-1 = ");  System.out.print(smin-1);
    System.out.println();
short smin1 = smin - 1;  
...

You see message:

Exception in thread "main" java.lang.RuntimeException: 
Uncompilable source code - incompatible types: 
possible lossy conversion from int to short 
at dora.Test.main(Test.java:18)

It will be work without exception if you change type from short to integer for smin1 variable.

...
int smin1 = smin - 1;  
...

The same situation is for byte, int or long types.
What is matter for loss conversion? In example below the value of short type is assign to variable of byte type .

public class Test {
	public static void main(String[] ar )
{	
    short bmin = Byte.MIN_VALUE ;
    short bmax = Byte.MAX_VALUE ;
 
    System.out.print(" byte min = ");  System.out.print(bmin);
         System.out.println(); 
    System.out.print(" byte max = ");  System.out.print(bmax);           
         System.out.println();    
    short s = 134;    
    byte b = s;    
}
}

The result:

 byte min = -128
 byte max = 127
Exception in thread "main" java.lang.RuntimeException: 
Uncompilable source code - incompatible types: 
possible lossy conversion from short to byte
	at dora.Test.main(Test.java:16)

Resolve this problem you may make to project the short value into byte type.

...
short s = 134;    
byte b = (byte) s;    
System.out.println(b);
...

Effect:

This value is negative despite short value was positive out of range. In this situation after exceeded scope, the count is begin from -128 to 127 and this cycle is repeated, in this example it is go on to 7 units.
It is present in diagram below:

Leave a Reply

Your email address will not be published.

Time limit is exhausted. Please reload CAPTCHA.