Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
422 views
in Technique[技术] by (71.8m points)

java - Output for this test class is very confusing.Can anyone please explain the output?

public class Test { 
    public static void main(String[] args) {        
        String msg= "Hello";
        print(msg);
        msg += "world";
        print(msg);
    }

    static void print(String msg) {
        System.out.println(msg);
        msg += "tttt";
        System.out.println(msg);        
    }
}

OutPut:

Hello Hellotttt Helloworld Helloworldtttt

Why the out has Helloworld after Hellotttt and not Hellottttworld?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Because in method static void print(String msg) , the change in msg will only be available in this method. After the execution of print(msg) for the first time, value of msg will be "Hello" again.

If you want output like Hello Hellotttt Hellottttworld Hellottttworldtttt

you can do it like this :

static void main(String[] args) {   
    String msg= "Hello";
    msg = print(msg);
    msg += "world";
    print(msg);

}

static String print(String msg) {
    System.out.println(msg);
    msg += "tttt";
    System.out.println(msg);
    return msg;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...