File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

what's wrong

 
nmurar01
Greenhorn
Posts: 1
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 13974
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Jessica Sant
Sheriff
Posts: 4313
Android IntelliJ IDE Java
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
"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
Posts: 29
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 143
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Now I understand the meaning of early birds catch the worm. Moderators
 
Arun Pai
Ranch Hand
Posts: 143
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic