jQuery in Action, 2nd edition*
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
Author

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;
A()
{
b=new B();
System.out.println(b.toString());
}
public String toString()
{
return "I am A ";
}
}
class B
{
A a;
B()
{
a=new A();
System.out.println(a.toString());
}
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........."
endlessly.

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

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.
-vipin
PNS Subramanian
Ranch Hand

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

Joined: Nov 16, 2004
Posts: 2
hey,
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();
a.m();
}
}



bye ,(magicnetha@yahoo.com)
Pavan Kumat
Greenhorn

Joined: Dec 13, 2004
Posts: 10
Would result in "StackOverflowError"
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: q on strings
 
Similar Threads
NullPointerException
Printf
private inner class access
what should i need to do..
String problems