question on type promotion

Can somebody please explain to me why this will compile:byte b=0;b+=4;but this won't (possible loss of precision):byte b=0;b=b+4;thanks,Marko
[264 byte] By [m_draismaa] at [2007-11-27 9:37:21]
# 1
b+=4; // increments the byte by 4, so it still is a byteb=b+4; // == byte + int -> returns an int
prometheuzza at 2007-7-12 23:08:28 > top of Java-index,Java Essentials,Java Programming...
# 2
that's quick, thank you!
m_draismaa at 2007-7-12 23:08:28 > top of Java-index,Java Essentials,Java Programming...
# 3
i'm still confused: why doesn't this return an int?b=3+4;
m_draismaa at 2007-7-12 23:08:28 > top of Java-index,Java Essentials,Java Programming...
# 4

> i'm still confused: why doesn't this return an int?

> b=3+4;

The compiler is "smart". It can see thet 3+4 fits into a byte.

This will not work however:

byte b1 = 3;

byte b2 = 4;

byte b3 = b1+b2;

but this will:

final byte b1 = 3;

final byte b2 = 4;

byte b3 = b1+b2;

which is the same as

b=3+4;

prometheuzza at 2007-7-12 23:08:28 > top of Java-index,Java Essentials,Java Programming...
# 5
thanx again, you saved my day :-)
m_draismaa at 2007-7-12 23:08:28 > top of Java-index,Java Essentials,Java Programming...