What is the difference of Integer.valueOf () when using String or int parameters?

19

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

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

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

If you pass a int it changes the original value, now if you pass a String it retains the value.

long teste1 = 0422;
Resultado: 274

int teste2 = 0422;
Resultado: 274
    
asked by anonymous 17.09.2014 / 16:15

1 answer

17

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

    
17.09.2014 / 16:36