Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Casting inconsistency?

 
Dan Temple
Ranch Hand
Posts: 93
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Could anyone tell me why this is legal? It seems to break the casting rules:
long l = 104;
int i = 1;
int j = 0;
j = i << l;
System.out.println(j);
As I understand it, the int i should have been converted to a long when it was subject to the left shift by a long. But then the result would have been a long being converted to an int, which is illegal without an explicit cast. What am I missing?
Dan
[This message has been edited by Jim Yingst (edited July 23, 2001).]
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I edited your post to insert a space after the << - otherwise many browswers think you're trying to write an HTML tag, and try to interpret it rather than display it. Making it hard for others to figure out what you wrote. Anyway...
The rules for the shift operators are different from those for all other binary operators. The type of the right hand operand is basically ignored - only the 4 or 5 lease significant bits of it will be used anyway; it really doesn't matter how many more bits it might have had. The left hand operand is promoted to int if it wasn't already, but not further. The type of the result is the same as the type of the left hand operand - int in this case - regardless of what the right hand side was.
 
Dan Temple
Ranch Hand
Posts: 93
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Okay .. I understand. My Book misled me - *Dan whaps his book on the nose with a rolled up paper* Bad Java Book! Bad!!!
Dan
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic