How to create a function with an optional parameter in Java

2 Answers

0 votes
// You can’t declare a truly optional parameter in Java 
// But Java gives you a way to simulate optional parameters

// Default Values Using Method Overloading 

public class Example {

    public void greet(String name) {
        System.out.println("Hello, " + name);
    }

    public void greet() {
        greet("Guest"); // default value
    }

    public static void main(String[] args) {
        Example e = new Example();
        e.greet("AAOO"); 
        e.greet();       
    }
}



/*
run:

Hello, AAOO
Hello, Guest

*/

 



answered 1 hour ago by avibootz
0 votes
// You can’t declare a truly optional parameter in Java 
// But Java gives you a way to simulate optional parameters

// Optional Parameters Using Varargs 

public class Example {

    public void greet(String... names) {
        if (names.length > 0) {
            System.out.println("Hello, " + names[0]);
        } else {
            System.out.println("Hello, Guest");
        }
    }

    public static void main(String[] args) {
        Example ex = new Example();

        ex.greet();          
        ex.greet("Bella");   
    }
}



/*
run:

Hello, Guest
Hello, Bella

*/

 



answered 1 hour ago by avibootz
...