Example 1:
SomeObject someObject = new SomeObject();
if (someObject.Method())
{
//do stuff
}
//someObject is never used again
vs
Example 2:
if (new SomeObject().Method())
{
//do stuff
}
Is there any benefit to using the first method over the second, or vice versa?
You MUST place an initial value into such a "constant" variable. If you do not place this initial value, Java will never let you assign a value at a later time because you cannot do anything to change the value of a final (constant) variable.
Calling a Method With a Return Value A return value by itself would not be very useful, given that it does not print to the console. Fortunately, we can store a method's return value into a variable.
Reference variable is used to point object/values. 2. Classes, interfaces, arrays, enumerations, and, annotations are reference types in Java. Reference variables hold the objects/values of reference types in Java.
Functions stored in variables do not need function names. They are always invoked (called) using the variable name. The function above ends with a semicolon because it is a part of an executable statement.
There are at least three potential benefits:
Readability: the first is more obvious in many cases than the syntax of the second example, especially to newer developers.
Better debugging experience: If the constructor for SomeObject
throws an exception, in the first case, the debugger will break on that line. In the second case, it's not obvious whether the exception is in the constructor or the method. The same issue arises for setting break points and inspecting values on the object - this will be difficult in the second case, and require setting the break point inside of the method.
In the first case, you can use the object outside of that single call. If you really only need a method for a single call, and don't need the object reference, then a static method may be more appropriate.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With