Skip to content
Advertisement

How to execute the “if” and “else” at the same time?

Interesting problem:

Change if statement and print out “Hello World”

    public static void main(String[] args) {
        if(){
            System.out.println("Hello");
        }else{
            System.out.println("World");
        }
    }

My solution is to add “!System.out.println(“Hello”)” in the if statement,But it doesn’t work, any ideas?

    public static void main(String[] args) {
        if(!System.out.println("Hello")){
            System.out.println("Hello");
        }else{
            System.out.println("World");
        }
    }

UPDATE: I think this works:

    public static void main(String args[]) {    
        if(System.out.append("Hello ")==null){
            System.out.print("Hello ");
        }else{
            System.out.println("World");
        } 
    }

In C:

main()
{   if(printf("Hello"),0)
         printf("Hello");
    else
       printf(" world!n");
   getch();
}

Advertisement

Answer

Tadaaaa:

public static void main(String args[]) {    
    if(!new Object() {
        public boolean foo() {
            System.out.print("Hello ");
            return true;
        }
    }.foo()){
        System.out.println("Hello");
    }else{
        System.out.println("World");
    }
}
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement