I am a Java beginner and pretty confused with this.
How is System.out.println(4*2147483647) equal to -4 in java?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
It is due to integer silent overflow.
2147483647 == Integer.MAX_VALUEis the maximum value for an integer.Silent overflow means that
2147483647 + 1 == Integer.MIN_VALUE = -2147483648You can then see that
2147483647 + 2147483647 == 2147483647 + (-2147483648 + - 1) == -2In other words,
2147483647 * 2 == -2, and you can now see why2147483647 * 4 == -4.More technically, the result is defined by the Java Language Specification #15.17.1: