Kenzo
Kenzo

Reputation: 1837

What is "Integer.valueOf().intValue()" supposed to do?

Here is a java line of code that i have failed to understand.

 String line = "Some data";//I understand this line
 int size;//I understand this line too

 size = Integer.valueOf(line,16).intValue();//Don't understand this one

What i know is Integer.ValueOf(line) is the same as Integer.parseInt(line) , is not so? Correct me if i am wrong; Thanks.

Upvotes: 5

Views: 15871

Answers (4)

Simeon
Simeon

Reputation: 1

" = Integer.valueOf().intValue()"

and Example:

String myNumber = "54";    
int c = Integer.valueOf(myNumber).intValue();  // convert strings to numbers

result:

54 // like int (and before was a String)

Upvotes: -1

Upul Bandara
Upul Bandara

Reputation: 5958

Integer.ValueOf(line,16) converts string value line into an Integer object. In this case radix is 16.

intValue() gets the int value from the Integer object created above.

Furthermore, above two steps are equivalent to Integer.parseInt(line,16).

In order to get more INFO please refer Java API Documentation of Integer class.

Upvotes: 8

wannik
wannik

Reputation: 12706

Please look at the data type of the variables on the left hand side.

public class Test {
    public static void main(String[] args) {
        String s = "CAFE";
        Integer m = Integer.valueOf(s, 16);
        int n = m.intValue();

        System.out.println(n);
    }
}

Integer is a reference type that wraps int, which is a primitive type.

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500275

Yes, this is equivalent to:

size = Integer.parseInt(line, 16);

Indeed, looking at the implementation, the existing code is actually implemented as effectively:

size = Integer.valueOf(Integer.parseInt(line, 16)).intValue();

which is clearly pointless.

The assignment to -1 in the previous line is pointless, by the way. It would only be relevant if you could still read the value if an exception were thrown by Integer.parseInt, but as the scope of size is the same block as the call to Integer.valueof, it won't be in scope after an exception anyway.

Upvotes: 4

Related Questions