Java toString () method

public String toString()
        {
        String str;
        str = "The test scores in descending order are \n";

        for(int i = 0; i < data.length; i++)
        {
            str = str + data[i] + " ";
        }
        str = str + "\nThe average is " + mean;
        return str;
        }

      

This java code returns scores in descending order for my code. But what turns me off is how "str" ​​is returned. As I understand it, this 'str' return value is (str + "\ nAverage" + mean "). Since this is my last updated" str "value, it will update" str "to" Tests in descending order: "First, second - loop, then the last "str +" \ nAverage value of "+ mean" So in the end, although we updated str several times, actually the printed "str" ​​will only be "str +" \ nAverage value "+ mean ". Please explain why the program actually finishes printing

Test results in descending order 70 80 .......... (element values)

(And then returns the mean of the mean)

+3


source to share


1 answer


Since the team was

str = str + "\nThe average is " + mean;

      

This means add everything already in str

and save the results in str

. If it was



str = "\nThe average is " + mean;

      

instead will replace everything already in str

.

+4


source







All Articles