Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 932
NimChimpsky Avatar asked Feb 23 '23 02:02

NimChimpsky


1 Answers

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

like image 98
Joachim Sauer Avatar answered Feb 25 '23 15:02

Joachim Sauer