java – How does Integer.valueOf() differ when using String or int parameters?

Question:

Why are the System.out results different in the lines below?

Integer teste = Integer.valueOf("0422");
Resultado: 422

Integer teste = Integer.valueOf(0422);
Resultado: 274

If I pass an int it changes the original value, now if I pass a String it keeps the value.

long teste1 = 0422;
Resultado: 274

int teste2 = 0422;
Resultado: 274

Answer:

When you do Integer.valueOf(0422) , thanks to the 0 prefix at the beginning of the number, the conversion will be done on the basis that the value is in the octal base, not the decimal base. Which is different from doing Integer.valueOf(422) , which as it doesn't have a 0 prefix means that the number 422 is in decimal.

Possible prefixes for changing bases are:

0b – indicates the number is a binary
0 – indicates the number is an octal
0x – indicates the number is a hexadecimal

When you print with System.out.println() , the result is always printed in decimal, and as 422 in octal is equal to 274 in decimal the printed value is 274.

Example:

public class BaseNumerica {
    public static void main(String[] args) {
        System.out.println("422 em octal == " + Integer.valueOf(0422) + " em decimal");
        System.out.println("422 em decimal: " + Integer.valueOf(422));
        System.out.println("422 de String para inteiro decimal: " + Integer.valueOf("0422"));
        //Comprovando que 274 em decimal vale 422 em octal 
        System.out.printf("Decimal: %d ; Octal: %o", 274, 274);
    }
}

Result:

422 in octal == 274 in decimal
422 in decimal: 422
422 from String to decimal integer: 422
Decimal: 274; Octal: 422

Unlike Integer.valueOf(int i) , the method Integer.valueOf(String s) does not take into account the prefix to change the base of the number read. The correct way to change the base of the number that will be read from the String is using the valueOf(String s, int radix) , and indicating the base in the second parameter of the method. Example:

System.out.println(Integer.valueOf("422", 8));

It understands that the value of 422 is in octal, and then prints the value of 274 in decimal.

See the documentation: Integer – Java SE7

Scroll to Top