javareturn-valuemethod-call

How is the return value of a method ignored in Java?


I'm trying to understand how the return value of the HashSet.add() method is handled in Java when it's not used in a condition or assigned to a variable. Here's an example of what I mean:

Set<String> seen = new HashSet<>();
seen.add("apple");  // Return value is ignored
seen.add("banana"); // Return value is ignored
seen.add("apple");  // Return value is ignored

boolean add(E e) is a method in Set.java class. It basically adds the specified element to the given set (seen in this case). In this code, the add method is called three times, but the return values (true or false) are not used.

I also want to contrast this with an example where the return value is used in a condition. For instance:

Set<String> seen = new HashSet<>();
if (!seen.add("apple")) {
    System.out.println("Apple is already in the set!");
} else {
    System.out.println("Apple was added to the set.");
}

I understand that add returns true if the element was added to the set and false if it was already present. However, I'm confused about what happens to the return value when it's not explicitly used in the code.(Such as in the first example)

Could someone explain this behavior in detail?


Solution

  • See how the Java Language Specification defines Expression Statements:

    Certain kinds of expressions may be used as statements by following them with semicolons.

    ExpressionStatement: StatementExpression ;

    ...

    An expression statement is executed by evaluating the expression; if the expression has a value, the value is discarded.

    An expression can execute a method call that returns a value. It is up to the programmer to use or not the returned values.