• 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
  • Paul Clapham
  • Tim Cooke
  • Jeanne Boyarsky
  • Liutauras Vilda
Sheriffs:
  • Frank Carver
  • Henry Wong
  • Ron McLeod
Saloon Keepers:
  • Tim Moores
  • Frits Walraven
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Piet Souris
  • Himai Minh

Doubt in calling the functions

 
Ranch Hand
Posts: 59
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
public class ClassTest{

public static void main (String[]args) {
int [] a = new int [1];
modify(a);
System.out.println(a[0]);
}

public static void modify (int[] a) {
a[0] ++;
}
}
and take another class


public class ClassTest1{

private static int a;

public static void main (String[] args) {
modify (a);
System.out.println(a);
}

public static void modify (int a) {
a++;
}
}
When comparing these two classes why the outputs of these two classes are different?
For the first class the output is 1 and for the second class the output is 0.Please explain why the answers differ though these two classes are similar?
 
Ranch Hand
Posts: 694
Mac OS X Eclipse IDE Firefox Browser
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
All parameters in Java are "passed by value". This means that a copy of the parameter is made.

In the first case, the parameter is an array and all arrays are objects so an object reference variable to the array is called. On the calling end is a copy of the object reference variable that refers to the array, so the array that is referenced by "a" on the calling side cannot be changed, but the *elements* of the array can be changed.

In the second case, the "a" refers to a primitive int. With all primitives, a copy of the whole primitive is made when they are passed into methods. With primitive parameters inside of a method, you can't change the value that was passed because everything that you do in the method is working on a copy of the primitive.

Kaydell
[ July 31, 2007: Message edited by: Kaydell Leavitt ]
 
sukhavasi vasavi
Ranch Hand
Posts: 59
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thank You Kaydell .I got it
 
Every snowflake is perfect and unique. And every snowflake contains a very tiny ad.
Garden Master Course kickstarter
https://coderanch.com/t/754577/Garden-Master-kickstarter
reply
    Bookmark Topic Watch Topic
  • New Topic