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

Asked

Viewed 1,099 times

22

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

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

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

If step one int it changes the original value, now if step a String he keeps the value.

long teste1 = 0422;
Resultado: 274

int teste2 = 0422;
Resultado: 274
  • Related:http://answall.com/q/25031/7261

1 answer

19


When you do Integer.valueOf(0422), thanks to the prefix 0 at the beginning of the number, the conversion will be made based on the value in the octal basis, and not on the decimal basis. Which is different from you to do Integer.valueOf(422), that as it does not have the prefix 0 means that the number 422 is to the same decimal.

Possible prefixes to change basis 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 have print with the System.out.println(), the result is printed always 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);
    }
}

Upshot:

422 octal == 274 to the decimal place
422 to the decimal: 422
422 String for 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 basis of the number that will be read from the String is by using the method valueOf(String s, int radix), and indicating the basis in the second parameter of the method. Example:

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

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

View documentation: Integer - Java SE7

Browser other questions tagged

You are not signed in. Login or sign up in order to post.