V
V
Vlad2016-04-30 00:24:33
Java
Vlad, 2016-04-30 00:24:33

Casting incompatible types in Java language (int to byte)?

I'm starting to learn Java and this question immediately arose. When casting from int to byte, the value of x is 145, which is within the range of valid byte values. As I understand it, it should display two identical numbers, but in practice -111, 145. I can't understand why.
class mainactivity {
public static void main(String[] args) {
byte b;
int x = 145;
System.out.println("convert int to byte" );
b = (byte)x;
System.out.println(b + " " + x);
}
}
convert int to byte
-111 145

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Espleth, 2016-04-30
@Vladikov

Byte takes values ​​from -128 to 127, not from 0 to 255. You have confused the range of valid values.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question