• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Tim Cooke
  • Campbell Ritchie
  • paul wheaton
  • Ron McLeod
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Piet Souris
Bartenders:

Doubt

 
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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[]) {
i[0] = 2;
i[0] *= 2;
}
}

IMO the answer should be 1, but the answer is . Is it because the method change_i is static and the changes happened in this method will be reflected in main(), but int i[]is not declared as static, how it can be 4 in main(). Please explain.
 
Ranch Hand
Posts: 289
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Shallender,
I think the reason that the result reflects change in the value of i is because i is an array, and consequently an object.Recall that when you pass an object reference to a method, all changes made to that reference will be effected in the original object, since a reference is only an address in memory and any alterations are happening to the same location.This is contrary to the behaviour of primitives, passing primitives to methods passes a copy of the value.So this has nothing to do with the method being static, but with the fact that an array is a java object.
I hope this helps..
Herbert
 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks Herbert,I understand the problem.
Shallender
 
reply
    Bookmark Topic Watch Topic
  • New Topic