首页 > 解决方案 > Java order of operations clarification

问题描述

I am having trouble understanding order of operations in Java. Isn't arithmetic operator evaluated before relational. If so, why does this code run without error? Shouldn't y/z be evaluated first, causing an Arithmetic exception.

public static void main(String[] args) {
        // TODO Auto-generated method stub
    int x = 10;
    int y = 20;
    int z = 0;
    
    if(x>y && 10 < y/z) {
        System.out.print("Homer");
    }
    
    }

enter image description here

标签: javaoperator-precedence

解决方案


&& 运算符短路:即:如果第一次检查失败,它不会打扰进行第二次检查。现在,如果 X 实际上大于 Y,则在执行第二次检查时会出现除以 0 异常。

出于好奇,我尝试直接输入 10/0 ,它仍然按顺序评估条件。我想这是有道理的,因为您不希望进行任何已经预先确定为错误的实际计算。只会浪费时间。


推荐阅读