my dog learned polymorphism*
The moose likes Beginning Java and the fly likes array assignment Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "array assignment" Watch "array assignment" New topic
Author

array assignment

Rekha Anand
Ranch Hand

Joined: Feb 23, 2008
Posts: 36
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

Joined: Aug 31, 2004
Posts: 11343

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.


    "We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
    sscce.org
    Rekha Anand
    Ranch Hand

    Joined: Feb 23, 2008
    Posts: 36
    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

    Joined: Aug 31, 2004
    Posts: 11343

    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.
     
    jQuery in Action, 2nd edition
     
    subject: array assignment
     
    Similar Threads
    question about arrays
    Array - question
    Arrays
    doubt in arrays
    help!!