• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Bear Bibeault
  • Junilu Lacar
Sheriffs:
  • Jeanne Boyarsky
  • Tim Cooke
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • salvin francis
  • Frits Walraven
Bartenders:
  • Scott Selikoff
  • Piet Souris
  • Carey Brown

Local variable initialization - source: http://www.jchq.net/mockexams/exam1.htm

 
Ranch Hand
Posts: 120
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I was working on Q10 and I got a doubt:

public class Q {
public static void main(String argv[]){
int anar[]=new int[5]; //line 1
System.out.println(anar[0]); //line 2
}
}

It prints "0" without initialization of the array.
However, If I replace the line 1 and line 2 with the below code, its gives the compilation error.

int anInt; //line 1
System.out.println(anInt); //line 2

I understood the error message: "The local variable anInt may not have been initialized".

Can somebody explain the reason behind allowing to access uninitialized array but not uninitialized int?

Thanks for your time.

 
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
the Array Object will be initialized no matter where it is declared ( as method local or instance or class variable), and the default value is the default of the type
 
Ranch Hand
Posts: 58
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There is a rule for array elements you should remember:
Array elements are always, always, always given default values, regardless of where the array itself is declared or instantiated
Have fun and good luck
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic