Parse variable String to variable Int in Java [duplicated]

0

I am practicing variable changes in Java using Eclipse and a little doubt has arisen. If I want to change a variable of type String to another variable of integer type (int), which of the two forms is correct or adequate for do it?

int variable = Integer.parseInt(variableString);

or

int variable = Integer.valueOf(variableString);
    
asked by Sergio AG 20.04.2018 в 03:10
source

2 answers

2

You could say both methods can be used without considering one more "correct or adequate" than the other. But, since the variable where you are going to store the value is of a primitive type, I would prefer to use parseInt() since valueOf() will create an unnecessary object in memory.

Anyway, you can use any, since the mechanisms of autoboxing and auto-unboxing make sure to transform a primitive type to its corresponding wrapper, or vice versa, when necessary.

    
answered by 20.04.2018 / 03:18
source
0

If you are completely sure that the value you are going to transform is of int you should use:

Integer.parseInt(variableValor);

This is because the method returns a primitive data type int

Here the signatures of the methods:

public static Integer valueOf(String s) throws NumberFormatException { ... }
...
public static int parseInt(String s) throws NumberFormatException { ... }

The difference between the two methods is that Integer.parseInt(String s) returns a primitive data type int and Integer.valueOf(String s) returns an object of type Integer .

    
answered by 20.04.2018 в 03:21