mriganka3
mriganka3

Reputation: 687

java integer handling

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?

Upvotes: 5

Views: 2672

Answers (5)

Bradley D
Bradley D

Reputation: 2825

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

Upvotes: 0

Heng
Heng

Reputation: 96

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.

Upvotes: 0

corlettk
corlettk

Reputation: 13574

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.

Upvotes: 3

sbridges
sbridges

Reputation: 25150

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

Upvotes: 1

icktoofay
icktoofay

Reputation: 129001

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.

Upvotes: 10

Related Questions