• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Array Initialisation in Methods

 
miceal oconnor
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello Guys,
When you declare variables in a class ( member variables ) they are automatically assigned default values. However when you declare variables in a method they are not assigned default values. Is this also true of arrays? I read somewhere that array elements are always given default values are declaration & construction?
Thanks - Miceal
 
chafule razgul
Ranch Hand
Posts: 63
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Arrays are treated like objects. As class variables they are given a default value. As with the rest of the variables declared in methods however, they are not initialized. If you attempt to access an array declared, not not initialized in a method, you'll be warned by the compiler

HTH
 
Valentin Crettaz
Gold Digger
Sheriff
Posts: 7610
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
From JLS 4.5.5 Initial Values of Variables

Each class variable, instance variable, or array component is initialized with a default value when it is created (�15.9, �15.10):
For type byte, the default value is zero, that is, the value of (byte)0.
For type short, the default value is zero, that is, the value of (short)0.
For type int, the default value is zero, that is, 0.
For type long, the default value is zero, that is, 0L.
For type float, the default value is positive zero, that is, 0.0f.
For type double, the default value is positive zero, that is, 0.0d.
For type char, the default value is the null character, that is, '\u0000'.
For type boolean, the default value is false.
For all reference types (�4.3), the default value is null.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic