wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Method calls Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Method calls" Watch "Method calls" New topic
Author

Method calls

Alpana Singh
Ranch Hand

Joined: Sep 27, 2005
Posts: 36
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

Joined: Feb 20, 2005
Posts: 21
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

Joined: Jul 04, 2004
Posts: 979
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

Joined: Sep 27, 2005
Posts: 36
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

Joined: Oct 18, 2005
Posts: 2
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

Joined: Jun 22, 2005
Posts: 1526
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 ]

Keep Smiling Always — My life is smoother when running silent. -paul
[FAQs] [Certification Guides] [The Linux Documentation Project]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Method calls