简体   繁体   中英

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.

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.

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.

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.

" = 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM