When you do Integer.valueOf(0422)
, thanks to the prefix 0
at the beginning of the number, the conversion will be done based on the value in the octal base, not the decimal base. Which is different from you doing Integer.valueOf(422)
, which since it does not have the 0
prefix, means that the number 422 is in the same decimal.
The possible prefixes to change base are:
0b - indicates that the number is a binary
0 - indicates that the number is an octal
0x - indicates that the number is a hexadecimal
When you print with System.out.println()
, the result is always printed in decimal, and because 422 in octal equals 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 String to Decimal Integer: 422
Decimal: 274; Octal: 422
Unlike Integer.valueOf(int i)
, the Integer.valueOf(String s)
method does not take into account the prefix to change the base of the read number. The correct way to change the base of the number that will be read from the String is by using the valueOf(String s, int radix)
method, and indicating the base in the second method parameter. Example:
System.out.println(Integer.valueOf("422", 8));
It understands that the value of 422 is in octal, and then prints the value 274 in decimal.
See the documentation: Integer - Java SE7