Good day, the next question. Here is the code:

public String toString() { String text ="sss"; text.concat("dss"); return text; } 

and the concat will not be executed, IDE’s informs about this as follows:

Call it ignored. Both methods are checked. It is almost certainly an error. An example of where you’d like to read the java.io.inputStream.read (), is to read the java.lang.String or java.math. If you’re ignoring.

So, someone can explain in connection with which everything is so and how not to catch this?

  • one
    I think everything is simple, the whole problem is that there should be text=text.concat("dss"); ? (concat does not change the variable?) - Batanichek Nov.

3 answers 3

The class String is an immutable class (why it's done here ), i.e. after creating an instance, you can only recreate it, but not change the values ​​inside. Accordingly, the concat method does not change the values ​​in text , but creates a new instance of the String class, which is not assigned to you anywhere and disappears in the depths of the GC. You need to do either:

 public String toString() { String text ="sss"; text = text.concat("dss"); return text; } 

or in general so:

 public String toString() { return "sss".concat("dss"); } 

    Fairly warns. This line does not make sense. In the production code, it is definitely not the place, and for any test or toy purposes you can ignore the warning.

    If you think that after

     text.concat("dss"); 

    the text string takes the form of sssdss , then you are mistaken, the strings are immutable and concat will return such a string to you, but it will not make the text string itself. That is, if you want to return the string sssdss from the toString method, you should do so:

     public String toString() { String text ="sss"; return text.concat("dss"); } 

      The concat method does not change the string, but only creates a new one as a result of the merging of the current and the passed as a parameter. The method returns a new String object, just the result of the concatenation. This result must now be somewhere to add.

      Therefore it is correct to write either

       String text ="sss"; return text.concat("dss"); 

      or if you want like you,

       String text ="sss"; text = text.concat("dss"); return text;