0

I have situation which I dont undestand. When I do

 System.out.println(1<<30);

I got very big positive number 1073741824. But when I do

 System.out.println(1<<31);

I got very low number -2147483648. As I read long type is signed 64 bit long. Max number is 2^63 -1. So here I dont undestand why my shift goes negative(((( Doing

System.out.println((long)(1<<31));

also gives the same result(((

5
  • 1
    Why did you think the numbers here would be long ? Commented Dec 10, 2014 at 14:36
  • Yep, you are right. But why System.out.println((long)(1<<31)); does not work either??? Commented Dec 10, 2014 at 14:39
  • because you're casting too late, when it's already MIN_VALUE. See the answer, it's right. Commented Dec 10, 2014 at 14:39
  • Because you cast the result (an int) not the operands. The expression (1<<31) is already an integer. Commented Dec 10, 2014 at 14:40
  • Thank you, very much. Very interesting situation for me. I created 100 tests for my little program and 1 of 100 didnt pass. Now I see why. Spent a day to catch it))) Commented Dec 10, 2014 at 14:43

2 Answers 2

6

1 << 31 is an int, not a long. And what you have is not really an overflow, but Integer.MIN_VALUE (sign bit set, all the rest zeroes).

Unless you suffix them appropriately, any numeric constant in Java is an int by default. If you want a long, you have to tell the compiler that you want a long: 1L << 31 (note the L).

And note that even (long) (1 << 31) wouldn't work; even in this scenario, 1 << 31 remains an int. Casting "after the fact" doesn't help ;)

Sign up to request clarification or add additional context in comments.

Comments

0

When we shift 1 by 31 to the left we get 0x80000000, this is Integer.MIN_VALUE = -2147483648. See Integer class.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.