File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes q on strings 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 "q on strings" Watch "q on strings" New topic

q on strings

JayaSiji Gopal
Ranch Hand

Joined: Sep 27, 2004
Posts: 303
What would be the output of the following code?
class A
B b;
b=new B();
public String toString()
return "I am A ";
class B
A a;
a=new A();
public String toString()
return "I am B ";
public class Test
public static void main(String[] ar)
A a=new A();
B b=new B();

Compile error.

Prints "I am A I am B........."

Prints "I am B I am A........."

Goes into an endless loop.

I answered 4, but the correct ans is b. Can somebody tell me y?

SCJP 1.4, SCWCD 1.4<br /> <br />Thanks in advance!<br />Jayashree.
Barry Gaunt
Ranch Hand

Joined: Aug 03, 2002
Posts: 7729
Where did the question come from?

And please use tags!

Ask a Meaningful Question and HowToAskQuestionsOnJavaRanch
Getting someone to think and try something out is much more useful than just telling them the answer.
Vipin Das
Ranch Hand

Joined: Jul 05, 2004
Posts: 47
Hi jayashri,
I executed this program. But no output was produced.
PNS Subramanian
Ranch Hand

Joined: Jul 13, 2004
Posts: 150
As expected, I get to see a StackOverflowError when executing this.
nethanjana indrakeela

Joined: Nov 16, 2004
Posts: 2
see u'r code, frist you make counstructor A and make new object B, then that moment, invoke B constructor, but in the B constructer make object A,agian B counstructor invoke A constructor, you maked infinity loop!

if you wont, you can do it whithin one class,

class A{

void m(){System.out.println("m"); m2();}
void m2(){System.out.println("m2"); m();}

public static void main(String arg[]){

A a=new A();

bye ,(
Pavan Kumat

Joined: Dec 13, 2004
Posts: 10
Would result in "StackOverflowError"
I agree. Here's the link:
subject: q on strings
It's not a secret anymore!