Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Uninitialized Array

 
saloni jhanwar
Ranch Hand
Posts: 583
Firefox Browser Notepad Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


I thought it will fail to compile because array is uninitialized.
 
Manoj Kumar Jain
Ranch Hand
Posts: 198
Java Linux Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
saloni jhanwar
Ranch Hand
Posts: 583
Firefox Browser Notepad Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 198
Java Linux Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 4181
21
IntelliJ IDE Java Python
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Randall Twede
Ranch Hand
Posts: 4404
3
Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Campbell Ritchie
Sheriff
Pie
Posts: 48968
60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic