• Post Reply Bookmark Topic Watch Topic
  • New Topic

weird problem  RSS feed

 
rahul mehra
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
for the code below i'm getting following runtime error error

package project;

class B {

int a;
B d = new B();
}

class C {
public static void main(String args[])
{

C c = new C();
B b = new B();
System.out.println(b.d.a);

}

}



can anybody explain why???
--------------------------------------------------
compile:
run:
Exception in thread "main" java.lang.StackOverflowError
at project.B.<init>(C.java:6)
[.. removed 200+ repeated lines]
at project.B.<init>(C.java:6)
Java Result: 1
BUILD SUCCESSFUL (total time: 2 seconds)



[ October 19, 2007: Message edited by: Eric Pascarello ]
 
Rob Spoor
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by rahul mehra:
for the code below i'm getting following runtime error error

package project;

class B {

int a;
B d = new B();
}

class C {
public static void main(String args[])
{

C c = new C();
B b = new B();
System.out.println(b.d.a);

}

}

can anybody explain why???
--------------------------------------------------
compile:
run:
Exception in thread "main" java.lang.StackOverflowError
at project.B.<init>(C.java:6)
at project.B.<init>(C.java:6)
at project.B.<init>(C.java:6)
...
at project.B.<init>(C.java:6)
at project.B.<init>(C.java:6)
Java Result: 1
BUILD SUCCESSFUL (total time: 2 seconds)



In class B, you have a field of type B, with an immediate initialization. So when you create an instance of B, this field will be set.

However, this field is also of type B. So this is what will happen:
B in main initializing
- B in B in main initializing
- B in B in B in main initializing

etc.

After a while the stack space runs out and you get this error.
 
Burkhard Hassel
Ranch Hand
Posts: 1274
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You have exactly 1024 repeats of
at project.B.<init>(C.java:6)

in your posting.

Buy a better computer, maybe you get 2048.


Bu.
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!