Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

q on strings

 
JayaSiji Gopal
Ranch Hand
Posts: 303
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
Barry Gaunt
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Where did the question come from?

And please use tags!
 
Vipin Das
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi jayashri,
I executed this program. But no output was produced.
-vipin
 
PNS Subramanian
Ranch Hand
Posts: 150
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As expected, I get to see a StackOverflowError when executing this.
 
nethanjana indrakeela
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Would result in "StackOverflowError"
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic