First you need to differentiate conversion , which is to transform one data type into another, from a cast , which consists of accessing an object as a more specific type of which the current reference allows.
Conversion
Converting one value type to another requires a routine that processes bytes or characters.
This answer considers that the conversion between number and text is done in base 10.
Convert Integer to String
A variable of type Integer
String str = myInteger.toString();
Primitive integer:
String str = Integer.toString(123, 10); //base 10
Convert String to Integer
The command is simple:
Integer inteiro = Integer.valueOf("1");
Or if you want the primitive value:
int inteiro = Integer.parseInt("1");
The problem is that if the String is typed or read from an external source, it may not contain a valid number. So it is important always to handle the exception NumberFormatException
, like this:
try {
int inteiro = Integer.parseInt(stringDuvidosa);
} catch (NumberFormatException e) {
//log, mensagem de erro, etc.
}
Cast
If you have an object of a specific type referenced as a generic type, you can do a cast to access it again as the specific type.
Example:
Object objeto = Integer.valueOf(1);
Integer inteiro = (Integer) objeto;
In the example above:
An object of type Integer
is created
It is stored in a variable of type Object
The cast
(Integer)
causes the variable of type
Object
to be assigned to a variable of type
Integer
Note that cast does not modify the object in any way, just the way it is referenced.
If the actual object type was not compatible with Integer
a ClassCastException
exception would be thrown at runtime. So it's always good to check if cast is possible. Example:
Object objeto = ...
if (objeto instanceof Integer) {
Integer inteiro = (Integer) objeto;
} else {
//log, erro, etc.
}
In this case, you do not have to treat ClassCastException
with try/catch
, because instanceof
ensures that this will not happen.
Many IDEs, such as Eclipse, will issue a warning if they find a cast without a instanceof
before.