This week's book giveaway is in the Mac OS forum. We're giving away four copies of a choice of "Take Control of Upgrading to Yosemite" or "Take Control of Automating Your Mac" and have Joe Kissell on-line! See this thread for details.
So my program uses a short and I originally attempted to assign it a value like so: static short zeroLeadsOne = 21845;//0101010101010101 However Java forces me to cast it using the following statement: static short zeroLeadsOne = (short) 21845;//0101010101010101 Can someone help me understand why I'm forced to cast this as I belive the value meets the primitive data type requirements. Thanks RJ. [ September 20, 2003: Message edited by: Rob Jones ]
Rob, If you write a number, it's default value is int. So the compiler thinks you are trying to store and int in a short. The (short) cast tells the compiler that you really want to do this and are ok with any lack of precision that may occur.
Hi all Well only for values which are greater than the short's range will have to be casted. As 21845 is well within there is no need for a cast. Had it been 221845 it would not had compiled. The short's range is from -32768 to 32767, both inclusive.
author & internet detective
Hi all, My java teacher told me when you declare a var like: short s = 2000; ==>just simply assigning a number to the var it should be ok; (Of course, the number can not be greater than the short's range ) but if you declare a var like this way: short a = 1;==>OK! short b = 2;==>OK! short c = a + b;==>complie error!! Because a and b will promote to be integers before operation, the sum of a+b will be an integer and you can not assign an int to a short var, so it should be modified: short c = (short)(a+b); This is my first reply, please tolerate my poor English! [ September 24, 2003: Message edited by: Chao Chihwai ] [ September 24, 2003: Message edited by: Chao Chihwai ]
Interesting! I found that if you chanage your a & b to final, then you don't have to typecase the sum of the addition to a short. I guess the compiler says "Hmmmm. The sm of a and b might sometimes be too large to put in a short." in the first case, but when you say they are final, then it knows that they will never be different from the values you assigned to them. Try the final!
Joined: Nov 04, 2001
Hi all well discussion point started by Chao seems to be different than what was originally posted. The compiler would throw compiler error if we try to use the way Chao mentions but thats a different issue I guess. So, Rob are you still get the error? Or did you find out the source of the error? Please let us know. Regards Maulin
Joined: Aug 14, 2003
OK it's working now without the cast. I'm not sure why though. I didn't change anything. Thanks for the info. -RJ.