Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How about with java.util.Stack??

 
Hades Pan
Ranch Hand
Posts: 106
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The following Quession's ANS is A but why?
import java.util.Stack;
public class aClass
{
public static void main(String []agrs)
{
Stack st1 = new Stack();
Stack st2 = new Stack();
new aClass().Method(st1, st2);
System.out.println("st1 has: " + st1);
System.out.println("st2 has: " + st2);
}
private void Method(Stack st1,Stack st2)
{
st2.push(new Integer(100));
st1 = st2;
}
}
A. print
st1 has: []
st2 has: [100]
B. error in st1 = st2
C. error in ("st1 has: " + st1)
D. print
st1 has: [100]
st2 has: [100]
 
Fei Ng
Ranch Hand
Posts: 1245
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
becuase st1 = st2; in Method() is gone after the method.
remember, java pass by value?
main() pass st1 and st2 to method()
st2 get pushed a value "100"; since st2 pointing to the same stack object thats in main() so the value stay after the method.
st1 = st2; since it is a copy. It won't matter after the method.
remember, the references got copied and passed to method().
change the references doesn't matter but change what is in the object will stay.
 
Hades Pan
Ranch Hand
Posts: 106
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
"java pass by value"
I couldn't understand this
Can you explane it o lot? Think you ~~!
 
Fei Ng
Ranch Hand
Posts: 1245
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Try read this... it is very good.
http://www.javaranch.com/campfire/StoryPassBy.jsp
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic