How to return nothing in Java

309 Views Asked by At
public String nameToPhone(String inputName) {
        /* (c) Allow the user to search a contact’s phone number using his/her name. */
        Pattern p;
        Matcher m;

        // Store name as pattern
        p = Pattern.compile(inputName);
        // Match pattern with array name
        m = p.matcher(this.name);
        if (m.matches())
            return this.phoneNum;
        else
            return null;

    }

The function will be called with System.out.print(phonebookArray[i].nameToPhone)

Expected output:
display only phone number if searched name exist

Actual output:

  1. else return null will display phone number and also "null" if name exist
  2. else return "" will display phone number and a blank line if name exist

The issue is return null will display null and return "" will display a blank line. How can I return absolutely nothing?

1

There are 1 best solutions below

0
Fathul Fahmy On

You cant. The caller has to have the fallback logic, not this method. The caller has to do if (result == null) dont do anything or similar. By the way, you should prefer to use Optional as return type to indicate absence of a result, not null or "". – Zabuzard