Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Why array is printing '0' for all indexes,why wasn't it initilialized ?

 
Punya Pratap Singh
Ranch Hand
Posts: 81
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


Prints value "10" as assigned with value "10" in ChangeVal method.
but in below code same procedure is being done but it does not accepts the assignment in populateArray() function and
prints "0" for all indexes.
If we populate the array in Testing class's constructor then it prints all the values .why ?


 
N Sahni
Ranch Hand
Posts: 55
Java Spring
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

Try modifying line 14 as:

At line 14 by doing new Testing() you are againg creating new instance of Testing class and hence, a new array gets created.
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Pie
Posts: 15436
41
Android IntelliJ IDE Java Scala Spring
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That happens because you are creating different instances of class Testing.

You create one in line 36, in the main method. You call populateArray() on that one in line 37.

But in the printArray method, you are creating a new instance of class Testing, in line 14, and then you iterate over the array in that new instance. You didn't call populateArray() on the Testing object that you created in line 14, so you see that the array contains all zeroes.

Change line 14 to this:

 
Punya Pratap Singh
Ranch Hand
Posts: 81
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot Both of you.
Actually I was in impression that you can not create any inner class instance without using inclosing class instance.so I did not tried for that.



 
Rob Spoor
Sheriff
Pie
Posts: 20606
60
Chrome Eclipse IDE Java Windows
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You are right, but there is an instance of the enclosing class - this.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic