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
865 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 Answer

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


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

2.1m questions

2.1m answers

60 comments

56.6k users

...