5

When I run this program, it outputs -43.

public class Main {
    public static void main(String[] args) {
        int a=053;
        System.out.println(a);
    }
}

Why is this? How did 053 turn into -43?

5 Answers 5

10

I've no idea how it's becoming negative, but starting an integer with 0 specifies it's octal (base eight). 53 in base eight is 43 in base ten.

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

1 Comment

BTW, in my machine it returns 43, not -43
3

The java tutorials http://download.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html

 int decVal = 26;      // The number 26, in decimal
 int octVal = 032;     // The number 26, in octal <<== LOOK FAMILIAR?
 int hexVal = 0x1a;    // The number 26, in hexadecimal
 int binVal = 0b11010; // The number 26, in binary

Yup... it's a gotcha!

Cheers. Keith.

Comments

1

It prints out 43, not -43. That is because if you write a number with a leading 0, it is an octal constant.

From here, http://download.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html

int octVal = 032; // The number 26, in octal

1 Comment

Nahhh... I'm just on the other side of the planet from the nearest SOF server... I have never supplied the first answer to any question, and I don't expect to... the question is (I suspect) a few minutes old before I even see it.
0

As http://docs.oracle.com/javase/specs/jls/se7/html/jls-3.html#jls-3.10.1 says:

An octal numeral consists of an ASCII digit 0 followed by one or more of the ASCII digits 0 through 7 interspersed with underscores, and can represent a positive, zero, or negative integer.

And its format is:

OctalNumeral:
    0 OctalDigits
    0 Underscores OctalDigits

So, if you use

int octVal = 053;

or,

int octVal = 0_53;

both of them, you will get 43.

Comments

0

This from googling 'how to convert octal to decimal'

Octal to Decimal

  1. Start the decimal result at 0.
  2. Remove the most significant octal digit (leftmost) and add it to the result.
  3. If all octal digits have been removed, you're done. Stop.
  4. Otherwise, multiply the result by 8.
  5. Go to step 2.

So 0 + 5 = 5, 5 * 8 = 40, 40 + 3 = 43

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.