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 Jeanne Then how would you explain the behavior I get? I don't have to cast the same number to (short) right? Regards Maulin
Joined: Apr 13, 2003
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.
Maulin, I was trying to explain the general case. If you have: method(5); it looks for method(int), not method(short) I agree for assignment it shouldn't matter.
Joined: Sep 24, 2003
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 ]
Joined: Nov 24, 2001
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.