I have this code :
public static void main(String[] args){
    boolean greeting = true;        //or false
    if(greeting)
        hello();
}
public static void hello(){
    System.out.println("Hello")
}
I want to call hello method without using (if,switch) if the value of greeting is set to true
is it possible to re-write this program without using if statement or switch ? if so how?
You can use an enum
enum Greeting {
    GREETING(() -> System.out.println("hello")),
    NO_GREETING(() -> {});
    private final Runnable greeting;
    private Greeting(Runnable r) {
        greeting = r;
    }
    public void greet() {
        greeting.run();
    }
}
and then have
public static void main(String[] args) {
    Greeting gr = Greeting.GREETING;   // or Greeting.NO_GREETING
    // or if you insist on the boolean
    // Greeting gr = (greeting) ? Greeting.GREETING : Greeting.NO_GREETING;
    gr.greet();
}
That would also be extendable to have things like
CORDIAL_GREETING(() -> System.out.println("hi wow so nice to see you"))
in the enum.
The ternary operator in the comment is of course not really different from an if/else.
checkout this :
public static void main(String[] args)
{
    boolean b = true;
    Predicate<Boolean> p = s -> {hello();return true;};
    boolean notUsefulVariable = b && p.test(true);      //will be called
    b = false;
    notUsefulVariable = b && p.test(true);              //will not called
}
public static void hello(){
    System.out.println("Hello");
}
or you could use while
b = true;
while(b)
{
    hello();
    break;
}
                        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