Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Method calls

 
Alpana Singh
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is the question fron Khalid Mughals mock exam.

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();
}
}


I answered 001 as o/p

But the o/p is 101

How can this be possible.
 
premraj cheguri
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

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();
}
}


Values of variables which we are passing to method wont be changed and we do know that array references can be modified by passing them to a method. here we are passing only 'b' and 'c[]'.

so b value wont be changed. as 'c' is an array it will be changed. we are not passing the variable 'a' as a parameter to method. so it get modified.

i hope im correct
 
A Kumar
Ranch Hand
Posts: 980
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
HI,

here the a that you are modifying is the class instance variable...a ..

You dont have any local variable a declared in the method...


So a is 1....

b ...that becomes one is local to the method g..

Hope you got it..

 
Alpana Singh
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
yeah, i got it.variable b in method g() is shadowing the class variable and it's local to g().Am i right?
 
Raghu Raj Reddy
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
public void g(int b, int[] c) {
a=1;-->is from global variable.it is original value we r changing
b = 1;-->u r changing value of b is local to g();it is not effecting original b.
c[0] = 1;
}
 
Akhilesh Trivedi
Ranch Hand
Posts: 1608
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Alpana Singh:
yeah, i got it.variable b in method g() is shadowing the class variable and it's local to g().Am i right?



Yes you are.
[ October 19, 2005: Message edited by: Akhil Trivedi ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic