vibhor sharma wrote:We tried to assign the sum of two bytes to a byte variable, the result of which
is small enough to fit into a byte, How ever , we are adding something here , which means we are involving expressions .
But the compiler knows taht anything int -or -smaller expressions are always result an int (implicitly)..
it wont get complied unless explicit cast.
Hope this helps ...
mrkamal joshi wrote:byte a=100;// works fine
byte b=a+a;//don't why??
Rameshwar Soni wrote:There are 2 types of initialization you can do to a variable
(1) when you are doing then you are storing 100 which is by default of type integer into an variable of type byte.........Now
here Java will do an automatic conversion(implicit conversion) from int to byte i.e. changing 100 of type int to 100 of type byte................Now the question arises why this conversion happened? It happened because 100 was within the range of byte (range of byte is -127 to 128)............ So when you store Here 200 is again of integer but here an conversion will not happen since 200 is out-of-range from that of byte.............
(2) DYNAMIC INITIALIZATION : Now see when you will write So what you are doing here is adding to 2 numbers again by default of type integer to a variable of type byte.....This is Dynamic Initialization(i.e storing an expression into a variable........expression can include addition, subtraction, multiplication, division etc....... ) Here the compiler will not do the automatic conversion because the compiler has no idea what 5+4 will return as an answer....The compiler thinks that adding 2 numbers of type integer may return a value which cannot be stored in an byte variable(But in above example it can v=be stored in byte since the answer of 5+4 is 9......but the compiler doesn't know this and that's why the name is dynamic initialization i.i run-time).......So to be on safe side it thinks the answer is int..........And that is why we have to explicitly cast it and therefore to avoid error we write
You also asked about error................ See by default floating point numbers are of type double.....The way 5 is an int the same way 3.4 is double ......And above you are storing a double value i.e 3.4 into a float and that is why it is an error.......So you have to append an F or f at the end of the value .So to avoid an error we write