This week's book giveaway is in the OCPJP forum.
We're giving away four copies of OCA/OCP Java SE 7 Programmer I & II Study Guide and have Kathy Sierra & Bert Bates on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Shift operators on short data type Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCA/OCP Java SE 7 Programmer I & II Study Guide this week in the OCPJP forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Shift operators on short data type" Watch "Shift operators on short data type" New topic
Author

Shift operators on short data type

Jag Sharma
Greenhorn

Joined: Nov 09, 2001
Posts: 10
Why does java not support << and >> operators on a 'short'?
Nain Hwu
Ranch Hand

Joined: Sep 16, 2001
Posts: 139
Jagdeep,
It does. Why do you think it doesn't?
Maybe I don't quite understand your question.
Sadaf Zaidi
Greenhorn

Joined: Oct 09, 2001
Posts: 29
It does. Here is a simple program try out this.
public class Short
{
public static void main(String[]args)
{
short s;
s=2>>1;
System.out.println(s);
}
}

[This message has been edited by Sadaf Zaidi (edited November 09, 2001).]
[This message has been edited by Sadaf Zaidi (edited November 09, 2001).]
Jag Sharma
Greenhorn

Joined: Nov 09, 2001
Posts: 10
It works with your example, but when I try to compile with this:
----------------
short s=20;
s=s>>1;
----------------
It gives "Incompatible type for =. Explicit cast needed to convert int to short.s=s>>1;" error.
Why does it need a cast, is the compiler trying to safeguard against over/underflow?
Michael Bruesch
Ranch Hand

Joined: Sep 23, 2001
Posts: 158
When you perform the following code:
short s;
s = s >> 1;
what the compiler is doing is casting the short variable s to an int so it can perform the bitshift. Then when you try to assign it back to the short variable s, the compiler complains that it needs an explicit cast just to make sure that you meant to do that. Just change it to:
s = (short) (s >> 1);
and it should work exactly the way you expect it to.
------------------
Michael J Bruesch
Codito, ergo sum...
I code, therefore I am.
My Java Games, I'm quite proud


Michael J Bruesch<br /><i>I code, therefore I am.</i>
Argm Mastoi
Ranch Hand

Joined: Oct 16, 2001
Posts: 35
hi,
All arithmatic operations in Java returns either int value i.e 4 bytes value or long value(only if long is involved) i.e 8 bytes. so int this case
'short s' is not able to handle the 4 byte value so it gives error.
For this purpose we have op= operators in java.
so try out this statement:
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Shift operators on short data type