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"
Run Code Online (Sandbox Code Playgroud)
我更喜欢编译时错误 - 为什么不是这种情况?在没有提供返回类型的情况下调用它时,同样的问题可以应用于具有返回类型的任何方法.
public myObject doStuff(...whatever){
//define my method
return anObject;
}
Run Code Online (Sandbox Code Playgroud)
可以调用而不提供引用/变量来保存返回类型:
MyObject newObject = doStuff(); //works
doStuff(); //works too without assigning return object
Run Code Online (Sandbox Code Playgroud)