Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

string - what happens to an object in Java if you do not reference it, like here : myString.concat("that")

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

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

1 Reply

0 votes
by (71.8m points)

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");.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...