Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

array assignment

 
Rekha Anand
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can someone please tell me what is happening in the line marked //** ?


public class example {
int i[] = {0};
public static void main(String args[]) {
int i[] = {1};
change_i(i);
System.out.println(i[0]);
}
public static void change_i(int i[]) {
int j[] = {2};
i = j; // **
}
}

Regards,
Rekha
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Keep in mind that this code contains 3 different variables called 'i'.
  • An instance variable i
  • A local variable i in the main method
  • A local variable i in the change_i method
  • The method change_i creates a new int array (referenced by j) and assigns this to the method-local variable i (i = j). The references stored by the other two 'i' variables are not affected.
     
    Rekha Anand
    Ranch Hand
    Posts: 36
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    O Ok..
    So that means the i referred in the //** line is same as the argument int i[] of the change method. And the output should be 1..??

    Regards,
    Rekha
     
    marc weber
    Sheriff
    Posts: 11343
    Java Mac Safari
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Originally posted by Rekha Anand:
    ... So that means the i referred in the //** line is same as the argument int i[] of the change method. And the output should be 1..??...

    Exactly.
     
    • Post Reply
    • Bookmark Topic Watch Topic
    • New Topic