This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Java in General and the fly likes Why array is printing '0' for all indexes,why wasn't it initilialized ? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Why array is printing Watch "Why array is printing New topic
Author

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

Punya Pratap Singh
Ranch Hand

Joined: Nov 23, 2010
Posts: 80


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

Joined: Jul 07, 2011
Posts: 55

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.


Thanks and Regards,
Nilesh Sahni | nsahni@infocepts.com | www.infocepts.com
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14074
    
  16

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:


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
Punya Pratap Singh
Ranch Hand

Joined: Nov 23, 2010
Posts: 80
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

Joined: Oct 27, 2005
Posts: 19649
    
  18

You are right, but there is an instance of the enclosing class - this.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
 
 
subject: Why array is printing '0' for all indexes,why wasn't it initilialized ?
 
Similar Threads
Local Array can get default values but local variable will not get default value
Arrays
Private modifier problem
Mock Exam Q
Why will I get this output?