Hi Philipe, Always remember that irrespective of the data type of a, the result of a + 2 will be an int. And since you can not assign an int value (even if it is in range of short or byte) to shorter data type without explicitly casting it, you can not assign the result of a+2 (which is an int) to a(which is short). You need to cast the result as following: a = (short)(a+2); This will run fine.
Joined: Oct 30, 2007
But in the below program why no explicit casting required.
Hi Phillip, Why do you think that an explicit cast is required here? You are declaring a variable of type short and incrementing it. When you increment a variable of type short then the number 1 which is added is of type short. But when you increment it using binary operator + by writing (a+1) then here 1 is an integer and consequently the result becomes an integer. Remember: a++ //compiler takes care of adding a value one of the same datatype as of a a+1 //You are telling the compiler to add the value 1 of type integer [ August 18, 2008: Message edited by: Shahnawaz Shakil ]