Convert object to String?
What is the best way to convert an object to a variable of type int
? Or is there no such conversion?
Example:
if (teste == JOptionPane.OK_OPTION) {
int linha = tblPessoa.getSelectedRow();
// Aqui o objeto não pode ser convertido em string.
int codigo = Integer.parseInt(tblPessoa.getModel().getValueAt(linha, 0));
pessoaController.excluir(Integer.valueOf(codigo));
}
3 answers
First you need to differentiate conversion, which consists of transforming one type of data into another, from a cast, which consists of accessing an object as a more specific type than the current reference allows.
Conversion
Converting one type of value to another requires a routine that does the processing of the bytes or characters.
This answer considers that the conversion between number and text is done in base 10.
Converter Integer for 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 some external source, it may not contain a valid number. So it's important always to treat the exception NumberFormatException
like this:
try {
int inteiro = Integer.parseInt(stringDuvidosa);
} catch (NumberFormatException e) {
//log, mensagem de erro, etc.
}
Cast
If you have a 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
- or cast
(Integer)
causes the variable of typeObject
to be assigned to a variable of typeInteger
Note that the cast it does not modify the object in any aspect, only the way it is referenced.
If the actual type of the object was not compatible with Integer
an exception ClassCastException
would be thrown at runtime. So it's always good to check if the cast will be possible. Example:
Object objeto = ...
if (objeto instanceof Integer) {
Integer inteiro = (Integer) objeto;
} else {
//log, erro, etc.
}
In this case, one does not need to treat ClassCastException
with try/catch
, because instanceof
guarantees that this will not occur.
Many IDEs, such as Eclipse, will issue a warning (warning ) if find a cast without a instanceof
before.
Hello,
You can do a casting passing to the expected type, but it's good to make sure the object is of the correct type.
int i = (Integer) object;
Font: stackoverflow
You can use String.valueOf(int)
For example:
int par = 2;
String dois = String.valueOf(par);