dimanche 18 juillet 2021

Why does java run the entire if statement condition block? [duplicate]

I am curious about the output of this jshell session:

|  Welcome to JShell -- Version 13.0.2
|  For an introduction type: /help intro

jshell> boolean foo() {
   ...> System.out.println("foo");
   ...> return true;
   ...> }
|  created method foo()

jshell> boolean foo1() {
   ...> System.out.println("foo1");
   ...> return false;
   ...> }
|  created method foo1()

jshell> if (foo() | foo1()) {
   ...> System.out.println("if statement ran.");
   ...> }
foo
foo1
if statement ran.

Once foo() returned true, the output of foo2() had no effect. So why did the compiler still run it?

Aucun commentaire:

Enregistrer un commentaire