JAVA 和 C 中的 AND 运算符的工作方式有区别吗?

Is there a difference in the working of AND operator in JAVA and C?

import java.util.Arrays;
import java.util.Scanner;
    
public class InsertionSort {
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        int[] arr = new int[s.nextInt()];
        for (int i = 0; i < arr.length; i++) {
            arr[i] = s.nextInt();
        }
        s.close();
        new RunInsertionSort().insertionSort(arr);
        System.out.println(Arrays.toString(arr));
    }
}

class RunInsertionSort {
    public void insertionSort(int[] arr) {
        int i, j, temp;
        for (i = 1; i < arr.length; i++) {
            temp = arr[i];
            j = i - 1;
            while ((j >= 0) && (temp < arr[j])) {
                arr[j + 1] = arr[j];
                j--;
            }
            arr[j + 1] = temp;
        }
    }
}

如果 j>=0 放在条件 temp< arr[j] 之后,我得到的错误是

5

5 4 3 2 1

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index -1 out of bounds for length 5

    at RunInsertionSort.insertionSort(InsertionSort.java:22)

    at InsertionSort.main(InsertionSort.java:12)

但在 C 语言中,这不会发生,无论我写 j>=0 && temp < arr[i] 还是 temp<arr[i] && j>=0

第一张图片 Image of Error when j>=0 is placed after temp<arr[j]

第二张图片Image when j>=0 is placed before temp<arr[j]

没有。它被称为短路。

顺序会影响您的条件,因为如果从左到右的任何条件失败,它将把完整条件标记为 false 并且不再评估任何条件。

while ((j >= 0) && (temp < arr[j]))

所以如果j >= 0为假,它不会评估temp < arr[j]

但是如果你先交换它会评估 temp < arr[j] 其中 arr[j] 可以在 Java.

中产生 ArrayIndexOutOfBoundsException

您可以阅读有关 shortCircuit 的更多信息。

在C中,可能不给异常;相反,它可能会给你一个垃圾值。