r/javahelp • u/gonnahike • Sep 01 '19
why does "int i = 1000; byte b = (byte) i; short s = (short) i; System.out.println(b + " " + s);" give me "-24 1000"
Hello,
I just started learning java a couple of weeks ago and I'm currently doing "data changes" (not sure what it's called in English, I'm learning through a Swedish book)
So the code looks like this:
public static void main(String[] args) {
int i = 1000;
byte b = (byte) i;
short s = (short) i;
System.out.println(b + " " + s);
The way I personally translate this code is that I put the number 1000 in i, then turn b into i and s into i as well. Since both s and b are now the number that I put in i, then I was 100% that I would print "1000 1000" but instead I get "-24 1000". Where did the number -24 come from?
Also in the same exercise I wrote the code:
double d1 = 2.5;
double d2 = 2.5E40;
double d3 = 1.23456789012;
float f1 = (float) d1;
float f2 = (float) d2;
float f3 = (float) d3;
System.out.println(f1 + " " + f2 + " " + f3);
Which apparently turns into 2.5 Infinity 1.2345679. Where the did the letters infinity come from? I didn't use char anywhere.. Should the code read "2.5 2.5E40 1.2345679"?
Thankful for any guidance