Why I'm getting the comlipe time error for the program?
---------- Compile ---------- Num_Pro.java:6: possible loss of precision found : int required: short a =a+2; ^ 1 error Normal Termination Output completed (2 sec consumed).
If 40 can be represented as short then why not 42?
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.
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 ]