I convert the int variable into integer but when I try to replace its value with a string it does not work for me, what can the solution be?
Remember that Java is a strongly "typed" language, that is, the types of data stored in variables or classes defined with a certain type can not store another type of data. That is, you can not save String in int, nor an int in String. To save a value of a certain type in a variable of another type, it is necessary to "force" the type, or do a casting .
Clarifying without going too deep, to see why it is possible to save a data type value in another type of data, you have to see the inheritance and the casting:
Notice that in your code, the variable tipo
is of type int, and therefore you can not store anything other than an int in it. This is the reason why your line
tipo = " nkn";is wrong: you can not put a String in an int (unless doing a casting - > changing the domain's value).
Leaving aside some parts, you can do one of the following two options:
//Opción 1: int tipo; String tipoEnCadena; tipoEnCadena= tipo+"" tipoEnCadena=" nkn"; //Opción 2: int tipo; String tipoEnCadena; tipoEnCadena=Integer.toString(tipo); tipoEnCadena=" nkn";
There are three main ways to do this:
String.valueOf(int)
"" + int
Integer.toString(int)
Remember that you must assign the result to a variable or return it in some way, if it is not as if you were not doing anything.
The static method toString()
of the Integer class returns a String with the conversion done. On the line where you have Integer.toString(tipo)
you are not assigning the result of the conversion to any variable of type String.
It should be something like String nueva = Integer.toString(tipo);
and with the new chain created you can do what you want.