+ 1
Can we upcast primitive datatypes
2 Réponses
+ 1
upcast is a term related to inheritance classes , but you can do some similar conversion with primitives. When larger type with higher max value converts to shorter, explicit (type) conversion is necessary, like
byte nbyte = (byte) nint;
rules for (explicit) conversion:
byte8 < short16 < char16 < int32 < long64 < float32 < double64
examples:
byte nbyte = 1;
int nint = nbyte;
long nlong = nint;
System.out.println(nlong); // 1
nint = (int) ++nlong;
nbyte = (byte) nint;
System.out.println(nbyte); // 2
nint = 99;
char cchar = (char) nint;
System.out.println(cchar ); // c
nint = ++cchar;
System.out.println(nint); // 100
short is signed max 32767 dec
char is unsigned max 65535 dec
so short16 < char16
int max 2147483647
long max 9223372036854775807
float max 3.4028235E38
so int32 < long64 < float32