Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

condition statement without if and switch

Tags:

java

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?

like image 424
Mrs.H Avatar asked Dec 19 '22 01:12

Mrs.H


2 Answers

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.

like image 81
daniu Avatar answered Jan 02 '23 01:01

daniu


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;
}
like image 25
Ali Faris Avatar answered Jan 02 '23 01:01

Ali Faris