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

Categories

String myString = "this";
//string is immutable

myString.concat(" that");
//a new object is created but not assigned to anything

System.out.println(myString); //prints out "this"

I would prefer a compile time error - why is this not the case ? The same question can be applied to any method with a return type, when it is called without supplying return type.

public myObject doStuff(...whatever){
 //define my method
 return anObject;
}

can be called without providing a reference/variable to hold the return type:

MyObject newObject = doStuff(); //works
doStuff(); //works too without assigning return object
See Question&Answers more detail:os

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

1 Answer

The object will be created and eligible for garbage collection right away (i.e. it will probably be garbage collected pretty soon).

The reason this is not a compile time error is that not every method that returns a method requires you to use that return value. Some methods are only called for their side effects.

A good example is Collection.add(): it returns a boolean object, but more often than not, the calling code is not interested in that result and simply ignores it.

Similarly StringBuilder.append() returns the StringBuilder instance so that you can chain the calls. But it's also perfectly valid to ignore that return value and simply use myStringBuilder.append("foo");.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...