wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes what's wrong Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "what Watch "what New topic
Author

what's wrong

nmurar01
Greenhorn

Joined: May 28, 2002
Posts: 1
import java.awt.*;
public class Question2 {
public static void main(String[] args) {
int i=0;
StringBuffer a=new StringBuffer("A");
StringBuffer b=new StringBuffer("B");
modify(a,b);
System.out.println(a+","+b);
}
public static void modify(StringBuffer a, StringBuffer b)
{
b=a;
}
}

Why am I getting A,B in the output. I thought it would be A,A.
Thomas Paul
mister krabs
Ranch Hand

Joined: May 05, 2000
Posts: 13974
b is a local variable to the modify method. By changing b to point to a, you are doing nothing to the b in the main method. Try it by changing the variable names in the modify method to c and d to perhaps make it a bit clearer.
Look at this code:

When you understand this code, grasshopper, you will have reached a deeper understanding of pointers.


Associate Instructor - Hofstra University
Amazon Top 750 reviewer - Blog - Unresolved References - Book Review Blog
Jessica Sant
Sheriff

Joined: Oct 17, 2001
Posts: 4313

"nmurar01"-
Welcome to the JavaRanch! Please adjust your displayed name to match the JavaRanch Naming Policy.
You can change it here.
Thanks! and again welcome to the JavaRanch
Asif Mahmood
Greenhorn

Joined: Jun 11, 2001
Posts: 29
Nmurar01, the answer "A,B" is correct. In modify method, if you make changes to objects' values then the changes would be visible in main method, but if you make changes to objects' reference, these changes will not be visible in calling method.
Best regards,
-Asif
Arun Pai
Ranch Hand

Joined: Mar 11, 2002
Posts: 143
Now I understand the meaning of early birds catch the worm. Moderators
Arun Pai
Ranch Hand

Joined: Mar 11, 2002
Posts: 143
Hello Moderators,
I had this question on my exam only variable names were different and the modify method included additional append call between the variables. Early birds still managed to eat the worms???

-Arun
 
 
subject: what's wrong
 
Similar Threads
DAN's Qn doubt
The difference of String and StringBuffer?
String & String Buffer