I can not convert from int to string to java

0

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?

    
asked by Connor NG 18.04.2018 в 07:19
source

3 answers

4

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:

  • Inheritance: when you inherit a class, you are creating a type that is a "supertype" of a previous one, and therefore contains the same as the base class, which is why you can treat it as if it were the base type. For example, suppose a class B that inherits from A. An instance of class B can be stored in a variable type A, because basically, B is all that is A.
  • Casting: is to make a conversion from one type and store it in another. When doing this conversion, you are not saving the original value, but rather you are storing the equivalent of the value of the first type within the domain of the second type. This is what you want to do in your case.

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";
    
answered by 18.04.2018 / 09:09
source
1

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.

    
answered by 18.04.2018 в 12:46
0

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.

    
answered by 18.04.2018 в 07:38