Reputation: 19
This is my Example
code
class Example{
public static void main(String args[]){
short s = 100;
byte b = s; // this is compile time error because of no casting
byte z = (short)25.12; // why this happens
System.out.println(z);
System.out.println(((Object)z).getClass());
}
}
please forgive for me as i just begin to learn java. can you please tell me this problem in technically.
Upvotes: 1
Views: 110
Reputation: 44335
The compiler doesn’t run your source code or analyze its logic. The compiler merely creates bytecode from each line of your source code.
When the compiler sees byte b = s;
, it just tries to generate code that assigns the value of b
. It doesn’t look back through your code to see what other instructions may have affected the value of s
.
It only knows that on that line of code, you are trying to set an 8-bit value (a byte) to an unknown 16-bit value (a short). When the compiler is looking at this line of code, it does not consider any previous lines, so it doesn’t care about the prior assignment; it treats s
as an unknown 16-bit value. That unknown value might or might not be something that fits in 8 bits.
On the other hand, byte z = (short)25.12;
is safe because the compiler doesn’t need to look at any other instructions to know that 25 can fit into 8 bits. It doesn’t matter that you have cast it to a short
. What matters is that implicitly casting it to byte
will not lose any information.
This would be true for (int) 25
as well. In all cases, 25 will fit in 8 bits without losing information.
Upvotes: 1
Reputation: 2165
byte b = s;
gives error because you can't assign bigger data type short(2 bytes) to smaller data type byte(1 byte). That is why it is giving you compile time error.byte z = (short)25.12;
lets break it down. 25.2
is by default double but when you typecast it using (short) it becomes 25
which is an integral literal. Now compiler will check whether 25 can be stored in byte or not. And since 5
is between -128 and 127 i.e. the range of byte it won't give any compile time error. But if you give any value out of the range of byte it will give error. Eg: byte z = (short)128.12;
Upvotes: 2
Reputation: 179
Take a look this article: https://www.javatpoint.com/java-data-types You getting errors, because:
short takes 16 bit(2 byte)
byte takes 8 bit (1 byte)
You can't put 16 bits, in to 8 bits.
Upvotes: -1
Reputation: 76
Typecasting a bigger datatype to a smaller one is not implicit because it can result in an incorrect conversion (loss of data).
byte b = s;
That's why the above line wont't compile because s is of type short (2 bytes) and b is of type byte (1 byte). Hence you need to typecast it explicitly
byte b = (byte)s;
Upvotes: 0