Search code examples
javamemoryallocation

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


In the below code how (x==val), I mean does the value of val(i.e. 5) and the 5th element of the array (i.e. 5 )has same memory location.

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!");   
    } 
}

Solution

  • No they are not for the example you listed.

    If these were object references and the "Value found!" message was printed then yes because for reference types the "==" operation checks whether the references are equal, i.e. whether they point to the same object. However for primitive types (such as an int) the "==" operation simply checks whether the values are equal (and not whether or not they are the same memory location).