• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Shift operators on short data type

 
Jag Sharma
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why does java not support << and >> operators on a 'short'?
 
Nain Hwu
Ranch Hand
Posts: 139
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jagdeep,
It does. Why do you think it doesn't?
Maybe I don't quite understand your question.
 
Sadaf Zaidi
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 158
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Argm Mastoi
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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:
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic