0

I am trying to convert the Integer 0550 to a String, but using

Integer.toString(0550);

gives me the String "360" instead of "0550" which is what I want. I'm confused as to why it is giving me a completely unrelated (or so it seems) String.

5audade
  • 9
  • 1

2 Answers2

6

0550 is interpreted as octal (base 8) by Java.

Try removing the leading zero.

Further Reading
Literals in Java

Robert Harvey
  • 178,213
  • 47
  • 333
  • 501
0

The number 0550 is the octal representation for 360 decimal.

Pass in the radix (8) to get "550" literally.

Integer.toString(0550, 8);

Edit

The JVM does not have the ability to detect if you placed a 0 (octal) or an x (hexadecimal) in front of an integer value. So you will not be able to print that out. You need to tell the program that you are expecting input to be octal or hex.

public class DisplayInteger {
    public static void main(String[] args) {
        displayInteger(0550);
        displayInteger(550);
    }

    private static void displayInteger(int value) {
        System.out.println("Actual  : " + value);
        System.out.println("Base  8 : " + formatAxOctal(value));
        System.out.println("Base 10 : " + formatAsDecimal(value));
        System.out.println("Base 16 : " + formatAsHex(value) + System.lineSeparator());
    }

    private static String formatAxOctal(int value) {
        return formatInteger(value, 8, "0");
    }

    private static String formatAsDecimal(int value) {
        return formatInteger(value, 10, "");
    }

    private static String formatAsHex(int value) {
        return formatInteger(value, 16, "0x");
    }

    private static String formatInteger(int value, int radix, String prefix) {
        return String.format("%s%s", prefix, Integer.toString(value, radix));
    }
}

Output

Actual  : 360
Base  8 : 0550
Base 10 : 360
Base 16 : 0x168

Actual  : 550
Base  8 : 01046
Base 10 : 550
Base 16 : 0x226
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
  • @Thilo I corrected my mistake. I was thinking of parsing, not formatting... – Mr. Polywhirl Mar 24 '19 at 01:28
  • But this will be very confusing for other numbers now: `Integer.toString(1000, 8)` will not say "1000". – Thilo Mar 24 '19 at 01:29
  • @Thilo The precondition is that the number starts with a zero. But this may hard to detect, unless you to-string it and check for a leading zero. – Mr. Polywhirl Mar 24 '19 at 01:30
  • There is no need to detect anything at runtime. We are talking about compile-time integer literals. Included in your source code. Just don't start them with a `0`. – Thilo Mar 24 '19 at 01:34