tags:

views:

514

answers:

6

when i write

System.out.println(0123);

i get

83

however

System.out.println((int)0123F);

returns

123

why it works that way?

+3  A: 

Because integer literals starting with 0 are treated as octal numbers.

See section 3.10.1 of the JLS

toolkit
+15  A: 

0123 means octal 123, that is 1*8*8 + 2*8 + 3, which equals 83. For some reason, octal floats are not available.

Creating 0123 means the integer 83. Creating 0123F means the floating 123. When converted back to integer, it remains 123.

Just don't use the leading 0 if you don't mean octal. After all, they are not exactly useful(and programmers who do know about octal numbers will get confused when they see 09F).

luiscubal
And if you want a hex number, it needs to start with 0x, not 0. So 0123F is a float, 0x123F is hex.
James Socol
@James Socol - Good add.
Tall Jeff
+1  A: 

Try this:

public static String leftPad(int n, int padding) {
    return String.format("%0" + padding + "d", n);
}
leftPad(5, 3); // return "005"
leftPad(15, 5); // return "00015"
leftPad(224, 3); // return "224"
leftPad(0, 4); // return "0000"
ryeguy
+2  A: 

first one printed as 83 because java takes 0123 as octal number and it prints decimal equivalent of that number.

A: 

printf will do it: http://java.sun.com/developer/technicalArticles/Programming/sprintf/

public class X { public static void main(final String[] argv) { System.out.printf("%04d", 123); System.out.println(); } }

You could also make it "%0" + size + "%d" if you wanted to vary the length... though if the lengths were common I'd probably make constants like: "%04d" "%012d" etc...

TofuBeer
A: 

The octal (leading 0) and hexadecimal (leading 0x) were inherited from C. For comparison, try

System.out.println(0x123);
Peter Lawrey