• 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:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

one more array question..

 
Greenhorn
Posts: 23
  • 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);
}
public static void change_i(int i) {
i = 2;
i *= 2;
}
}

output :- program prints 1.

in next example :-

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;
}
}
output:- program prints 4;

in next case why the output is 4 instead of 1,which is same as the previous example.
 
Ranch Hand
Posts: 3244
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Archana
In your first example you are just pasing a primitive value which is passed by value. so any changes made to the value in the change_i method only effect the local copy that was passed in, not the orginal in the calling method.
In your second example the array you create in main is passed to the method. An array is a reference type in java so it is passed by value which is to say the value passed is a refence to the array itself. so any hange made in the method effects the original as well.
check out the pass by value campfire story for a good explaination of it.
hope that helps
 
Ranch Hand
Posts: 262
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The two example differ with respect to the fact that the first uses a primitive type and the latter uses an object (the array). When you invoke a method with a primitive as the argument, you pass a copy of the primitive value to the method. When you invoke a method with an object as the argument, you pass a copy of the reference to the object to that method.
These ideas are explained with much more care a depth in the article Pass-by-Value Please
Pass-by-Value Please
 
reply
    Bookmark Topic Watch Topic
  • New Topic