OpMt
OpMt

Reputation: 1742

System.out.println for Java

How is it that System.out.println(052) and System.out.println(0x2a) both print 42?

Does this have to do with binary at all?

Upvotes: 1

Views: 560

Answers (5)

pb2q
pb2q

Reputation: 59607

052, 0x2a and 42 are all different ways of writing the (decimal, base 10) number 42:

  • 052 is octal, or base 8
  • 0x2a is hexadecimal, or base 16
  • 42 is the familiar decimal, base 10

java allows you to use numbers literally in your code using any of these different formats: using a leading 0x to specify hexadecimal, or a leading zero, 0 to specify octal.

This has to do with binary inasmuch as anything that you'll do with java has to do with binary.

By the way, the binary, base 2 representation of 42 is: 101010. You can also use binary literals in java by preceding them with 0b, so 0b101010 == 0x2a.

Upvotes: 2

kosa
kosa

Reputation: 66637

System.out.println(0x2a) uses a hex literal (0x prefix indicates this), which has a decimal equivalent of 42.

System.out.println(052) uses an octal literal (leading 0 indicates this), which has a decimal equivalent is 42.

System.out.println will print the integers according to their decimal representation. If you want to keep hex, try System.out.printf("%x\n", 0x2a), or, for octal, "%o" in place of "%x".

Upvotes: 4

slavemaster
slavemaster

Reputation: 204

052 is an octal literal, and is equivalent to 0 * 8^2 + 5 * 8^1 + 2 * 8^0. 0x2a is a hexadecimal literal, equivalent to 2 * 16^1 + 10 * 16^0.

5 * 8 + 2 and 2 * 16 + 10 can be seen to be equivalent, as 5 * 8 is equivalent to 4 * 8 + 8, and 8 + 2 equals 10.

Upvotes: 1

Amresh
Amresh

Reputation: 478

052, starts with 0, so it's an octal number and hence 8*5+2=42 0x2a starts with 0x, so it's a hexadecimal number and hence 16*2+a = 32 + 10=42

Upvotes: 1

SLaks
SLaks

Reputation: 887275

052 is an octal (base 8) literal.
0x2a is a hexadecimal (base 16) literal.

Upvotes: 7

Related Questions