search

Home  >  Q&A  >  body text

Java basics, please answer.

public class Demo {

             public static void main(String args[]) { 
                 boolean flag = 10%2 == 1 && 10 / 3 == 0 && 1 / 0 == 0 ; 
                 System.out.println(flag ? "mldn" : "yootk") ; 
             } 
         } 
         
         代码如上,我任务考察的是 && 符号 与 & 符号的区别,但是在最后一个  1 / 0 == 0 这个竟然能走通,而且打印出来了yootk,这个除数不是不能为零的吗?为什么能走通呢?很是费解,希望大神可以给解释下,谢谢。
世界只因有你世界只因有你2728 days ago784

reply all(3)I'll reply

  • 三叔

    三叔2017-06-30 09:55:33

    && and || have a short-circuit effect:
    The root cause of the short-circuit effect is to improve performance

    && operator checks whether the first expression returns false. If it is false, the result must be false and no other content is checked.
    || operator checks whether the first expression returns true. If it is true, the result Must be true, no other content will be checked

     public static void main(String args[]) { 
         boolean flag = 10%2 == 1 && 10 / 3 == 0 && 1 / 0 == 0 ; 
         System.out.println(flag ? "mldn" : "yootk") ; 
     } 

    10%2 == 1 is false, the following content will no longer be executed

    reply
    0
  • PHP中文网

    PHP中文网2017-06-30 09:55:33

    10%2 == 1 is false, the final result of the entire expression is false, and the following will not be executed, which is a short circuit.

    reply
    0
  • 迷茫

    迷茫2017-06-30 09:55:33

    && and || will short-circuit, but & and | will not. If you change && to &, something will definitely happen.

    reply
    0
  • Cancelreply