Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Kai Notes - http://www.jdiscuss.com/

 
Arun Pai
Ranch Hand
Posts: 143
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A class was given in the main() method:
Stack s1=new Stack();
Stack s2=new Stack();
method(s1,s2);
System.out.println("s1" + s1+" "+ "s2" + s2);
the method is so defined:
public static void method(Stack s1,Stack s2){
s1.push(new Integer(100));
s2=s1
}
what is the output ? I choose E
A. Compile error, because ...
B. Runtime error, because ...
C. s1[100]s2[100]
D. s1[ ]s2[ ]
E. s1[100]s2[ ]
F. s1[ ]s2[100]
Need to know the methods of Stack: push(), pop() and peek().
Stack is part of the java.util package - it is a subclass of Vector so I guess it is part of the objectives.
Kai: Many thought this is a Collection question, but I believe
it is more about argument passing.
-Arun
 
luco zhao
Ranch Hand
Posts: 50
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Arun Pai:

Kai: Many thought this is a Collection question, but I believe
it is more about argument passing.
-Arun

Yes, it is a question on argument passing, but why the correct output is E, not C. Thanks for yer kind explanation.
 
Robert Ziel
Greenhorn
Posts: 28
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Luco,
it's because you only
refer the local s1 to s2
so the original stays the same..

so answer would be E
Robert
[ May 12, 2002: Message edited by: Robert Ziel ]
 
chiru mega
Greenhorn
Posts: 1
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is not correct.
------------
Hi Luco,
it's because you only
refer the local s1 to s2
so the original stays the same..

so answer would be E
Robert
-------
since both will be passed by reference,changes made to s2 will also appear in main.
correct me if iam wrong
 
Robert Ziel
Greenhorn
Posts: 28
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi Chiru,
youre wrong because you in fact you have 4 references to 2 objects
when you say s1.push(100) you
change the object1
when you say
s1 = s2
then only the local copy of s1 refers to s2
when the method ends
s1 still refers to the first object
if find it poor programming
you should use differnt var names.
robert
 
John Bateman
Ranch Hand
Posts: 320
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Some code and some commentsa to further explain this 'phenomenon'.


[ May 13, 2002: Message edited by: John Bateman ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic