在下面的程序中,变量和数组中的值 5 是否分配了相同的内存位置?

Does the value 5 in both the variable and the Array is allocated with same memory location in the below program?

在下面的代码中 (x==val),我的意思是 val 的值(即 5)和数组的第 5 个元素(即 5)具有相同的内存位置。

class Search {  
    public static void main(String args[]) {
        int nums[] = { 6, 8, 3, 7, 5, 6, 1, 4 };     
        int val = 5;  
        boolean found = false;     
        for(int x : nums) {  
            if(x == val) {   
                found = true;  
                break;       
            }
        } 
        if (found)      
            System.out.println("Value found!");   
    } 
}

不,他们没有。在您的示例中,数组保留了连续的内存段,而变量 val 保留在不同的位置。即使两个元素(即数组的 valnth 元素)具有相同的值,它们也会存储在不同的位置。

要亲自查看效果,请尝试更改其中一个的值。您会发现另一个变量仍然保持其值。就像两个人有相同的名字,这并不能使他们成为同一个人。

不,它们不适用于您列出的示例。

如果这些是对象引用并且打印了 "Value found!" 消息那么是,因为对于引用类型,“==”操作检查引用是否相等,即它们是否指向同一个对象。然而,对于基本类型(例如 int),“==”操作只是检查值是否相等(而不是它们是否位于相同的内存位置)。