2

Why iam getting java.enter code herelang.StackOverflowError exception in below program

public class Image {

  Image i=new Image();

  public Image() {
  }


  private byte[] image_array;
  private String image_name;
  private long id;
  public static void main(String[] args) {

        Image ii=new Image();
   }  
}
pvpkiran
  • 25,582
  • 8
  • 87
  • 134
Binu
  • 49
  • 5
  • And hint: learn about java naming conventions. A) dont use under_scores except for constants B) use names that *mean* something. `Image i` ... means nothing. `ii` is even worse. – GhostCat Aug 06 '18 at 07:33
  • And sorry, but who is upvoting a question that is a super obvious duplicate? – GhostCat Aug 06 '18 at 07:33
  • I think this question isn't quite as obvious because the constructor is actually empty and then there is an instance field with a call to that constructor. So the explanation would require referring to JLS and how instance fields are initialized. – Mick Mnemonic Aug 06 '18 at 07:35
  • that makes it quite obvious if you know the basic of a java class instanciation – jhamon Aug 06 '18 at 07:36
  • @jhamon, but the duplicate question doesn't really address that. – Mick Mnemonic Aug 06 '18 at 07:36

2 Answers2

4

Because when the line Image ii=new Image(); gets executed inside main it creates instance of Image and inside which you've written line Image i=new Image();

Which means you keep creating new Image instances repeatedly.

Just keep it like Image i; and initialize it on need basis.

Shubhendu Pramanik
  • 2,711
  • 2
  • 13
  • 23
  • What triggers the recursion when the constructor is empty? Shouldn't the call stack end there? – Mick Mnemonic Aug 06 '18 at 07:39
  • I am asking for a better explanation about what is happening; _why_ does it create instances repeatedly and what exactly causes the endless recursion? There isn't an explicit recursive call anywhere in the code. – Mick Mnemonic Aug 06 '18 at 08:23
  • @MickMnemonic It's because `Image i=new Image();` is inside class `Image` and its an instance variable. An instance variable is initialized(if not initialized explicitly it defaults to null(for objects)) when an instance of that class is created. Thought it's obvious to understand ;-) – Shubhendu Pramanik Aug 06 '18 at 10:38
  • I was looking for an explanation that referred to the [relevant part of the JLS](https://docs.oracle.com/javase/specs/jls/se8/html/jls-12.html#jls-12.5) where the execution order of instance variable initializers w.r.t. the constructor is specified. – Mick Mnemonic Aug 06 '18 at 12:03
0

As soon as you instantiate an object of class Image, it is started to be created. Along this process, it receives a field i of type Image, which is initialized with a new object of class Image. This one gets initialized again, and so on.

Just remove that line Image i=new Image();.

glglgl
  • 89,107
  • 13
  • 149
  • 217