wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes Uninitialized Array Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Uninitialized Array" Watch "Uninitialized Array" New topic
Author

Uninitialized Array

saloni jhanwar
Ranch Hand

Joined: Feb 09, 2012
Posts: 583



I thought it will fail to compile because array is uninitialized.


Tell the difficulties that i am difficult.
Manoj Kumar Jain
Ranch Hand

Joined: Aug 22, 2008
Posts: 191

This code will not compile, not because the array is uninitialized. Array elements are initialized with their default value that is 0 for integers.
This will fail because there is a local variable size that is not initialized before using and that is line no. 5


Do not wait to strike till the iron is hot; but make it hot by striking....
saloni jhanwar
Ranch Hand

Joined: Feb 09, 2012
Posts: 583

Manoj Kumar Jain wrote:This code will not compile, not because the array is uninitialized. Array elements are initialized with their default value that is 0 for integers.
This will fail because there is a local variable size that is not initialized before using and that is line no. 5


I know already that but i think elements arr[0]-[9] are also local variables.
Manoj Kumar Jain
Ranch Hand

Joined: Aug 22, 2008
Posts: 191

saloni jhanwar wrote:
I know already that but i think elements arr[0]-[9] are also local variables.

Array elements always initialized with the default value.
Steve Luke
Bartender

Joined: Jan 28, 2003
Posts: 4181
    
  21

That is part of how arrays work. According to the Java Language Specification (here) "An array initializer creates an array and provides initial values for all its components."

The next question might be: well what value does it use? And that answer is also in the JLS (here). That second specification page also point to why size doesn't get a value: "A local variable must be explicitly given a value before it is used, by either initialization or assignment, in a way that can be verified."

I bring up the JLS - which may not be normal practice in the 'Beginning' forum because it is a great resource to search through when you have these types of questions.


Steve
Randall Twede
Ranch Hand

Joined: Oct 21, 2000
Posts: 4347
    
    2

yeah for one thing arrays aren't covered in the API
the JLS was hard for me to read but it has info you need


SCJP
Visit my download page
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39409
    
  28
Randall Twede wrote: . . . the JLS was hard for me to read but it has info you need
Nobody else finds the JLS easy to read, but it is worth the effort.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Uninitialized Array