Hi,
Contrary to some of the inputs given in this discussion the following program compiled and gave the following output:
This is my own code
public class Casting {
public static void main(
String[] args) {
byte b = 5;
byte c = 3;
//byte d = b+c;
byte d = (byte) (b + c);
System.out.println("Casting is necessary even when you add 2 bytes "+d);
int i = 127;
//byte e = i;
byte e = (byte)i;
System.out.println("Casting is necessary for Narrowing conversions of int to byte "+e);
int j = 128;
byte f = (byte) j;
System.out.println("byte capacity is smaller "+f);
int k = 32700;
short s = (short)k;
System.out.println("Narrowing conversion of int to short requires casting "+s);
final int m = 32700;
short sh = m;
System.out.println("Narrowing conversion of int to short requires NO casting because int is final and a " +
"compile time constant "+sh);
int a1 = Integer.MAX_VALUE;
float af = a1;
int a2 = (int) af;
System.out.println("int-float-int conversion a1 = " + a1 + " af = " + af + " a2 = " + a2);
long l1 = 32l;
// int n = l1;
int n = (int)l1;
System.out.println("long to int narrowing conversion "+n);
final long l2 = 1000L;
int p = (int)l2;
System.out.println("long to int narrowing conversion:" +
" long does not have to be final "+p);
long l3 = 130l;
byte g = (byte)l3;
System.out.println(" long to byte narrowing conversion. byte capacity is smaller "+g);
}
}
Casting is necessary even when you add 2 bytes 8
Casting is necessary for Narrowing conversions of int to byte 127
byte capacity is smaller -128
Narrowing conversion of int to short requires casting 32700
Narrowing conversion of int to short requires NO casting because int is final and a compile time constant 32700
int-float-int conversion a1 = 2147483647 af = 2.14748365E9 a2 = 2147483647
long to int narrowing conversion 32
long to int narrowing conversion: long does not have to be final 1000
long to byte narrowing conversion. byte capacity is smaller -126
Thanks,
Meera