Limitations of foreach loop statement in Java

Such as the following Java program:

public class test4 {
    public static void main(String args[]){
        int [] a=new int[3];
        for(int j:a){
            j=55;
        }
    }
}

As a result, the final output is not 55 55 55 as intuitively thought, but 0 0 0

The reason is that foreach can only get the value of the object each time it loops, but not the handle of the object, so any changes to the copy of the object cannot have any effect on the object itself, such as the following process:

int a = 1;
int b = a;
b = 2;
System.out.println(a);

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324689663&siteId=291194637