• 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
  • Tim Cooke
  • Ron McLeod
  • paul wheaton
  • Jeanne Boyarsky
Sheriffs:
  • Paul Clapham
  • Devaka Cooray
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
  • Himai Minh
Bartenders:

is this strange

 
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
(code/)
public class Qcb90 {
int a;
int b;
public void f() {
a = 0;
b = 0;
int[] c = { 0 };
g(b, c);
System.out.println(a + " " + b + " " + c[0] + " ");
}
public void g(int b, int[] c) {
a = 1;
b = 1;
c[0] = 1;
}
public static void main(String args[]) {
Qcb90 obj = new Qcb90();
obj.f();
}
}
(code/)
as i know primitive type are reference by copy so what wil be the result and why
any help
 
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Output: 1 0 1
Why:
in g()
a = 1; - set class member variable a to 1
b = 1; - set local variable b to 1, not the member var. b which stays 0 (this.b = 1 would set member var b)
c[0] = 1; - arrays are objects and passed by reference, so this sets first element of array created in f() to 1.
-VG
 
kashif sohail
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
actually what confusing me is a an b are primtives and a copy of primitives is given to each caller then how value is 101
as each method has its own copy
bit confused
plz help
kashif
 
"The Hood"
Posts: 8521
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
There is only one place in your example that you pass anything. That is in calling the method g.
You only passed b and c, and c is an object not a primitive. That is EXACTLY the reason that you get different results when printing a than when printing b.
When method g worked on a it worked on the object variable and set it equal to 1.
When it worked on b it worked on the local variable (copy) so the print statement prints the object variable which is still 0.
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic