简体   繁体   中英

String concat() return type

while doing brush up my knowledge seems the below code & surprised how it works. If anybody know, explain it.

class test1 {
    public static void main(String[] ar) {
        String s1 = "abc";
        s1.concat("ef");
        System.out.println(s1);
    }
}

Actual Output:

abc 

Expected Output:

compile time error since concat() return type is string & it is not returned.

The String object type is immutable. For getting the concatenated value you must do this:

String s1 = "abc";
s1 = s1.concat("ef");

You don't get a compile time error because it is not necessary to store into a variable the returned value of the concatenation.

When you call a method, you don't specify any return type, you can specify the variable in which you want to store the returned value specified by the method declaration basicly like :

public String concat(String s){
     return this.value + s;
}

When you call a method :

"foo".concat("bar"); //return "foobar"

The String instance with the value "foobar" will be returned, but you are not attributing it to any variable, it is allowed even if in your case, it doesn't make sense since the result of that concatenation will be lost.

Now, if you are trying to explain that you can't not have a method like :

public String concat(String s){
     this.value + s;
}

You are correct, you can't implement a method declared with a return type but not returning anything. It will not compile.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM