First we need to differentiate conversion, which consists in transforming one type of data into another, one cast, which consists in accessing an object as a type more specific than the current reference allows.
Conversion
Converting one type of value into another requires a routine to process bytes or characters.
This reply considers that the conversion between number and text is done on basis 10.
Convert Integer to String
A variable of the 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. Therefore, it is important at all times treat the exception NumberFormatException
, thus:
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 make a cast to access it again as the specific type.
Example:
Object objeto = Integer.valueOf(1);
Integer inteiro = (Integer) objeto;
In the above example:
- An object of the type
Integer
is created
- It is stored in a variable of type
Object
- The cast
(Integer)
causes the type variable Object
can be assigned to a variable of type Integer
Note that the cast 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 launched at runtime. So it is always good to check whether the cast will be possible. Example:
Object objeto = ...
if (objeto instanceof Integer) {
Integer inteiro = (Integer) objeto;
} else {
//log, erro, etc.
}
In that case, no need to treat ClassCastException
with try/catch
, because instanceof
guarantees that this will not occur.
Many Ides, like the Eclipse, will issue a warning (Warning) find a cast without a instanceof
before.
You want to know the conversion of what to what?
String
forint
? Focus on one thing in the question.– Maniero
It’s like @bigown said, be objective in your question.
– Weslley Tavares
Object conversion to primitive types and no conversion from primitive to primitive types.
– Igor Contini
I made the edit and now I’m waiting for answers @bigown.
– Igor Contini
@Igorcontini Do you know the type of the object? Or it can be of any type? If it can be of any type, because?
– Maniero
I was able to convert the tblPeople object which is the person table by placing a String on the left side in front of the tblPeople.
– Igor Contini
@Igorcontini The answer given below also works.
– DiegoAugusto