This week's book giveaway is in the Design forum.
We're giving away four copies of Building Microservices and have Sam Newman on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Array Initialisation in Methods Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Building Microservices this week in the Design forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Array Initialisation in Methods" Watch "Array Initialisation in Methods" New topic

Array Initialisation in Methods

miceal oconnor

Joined: Nov 07, 2001
Posts: 29
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

Joined: Feb 09, 2002
Posts: 63
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

Valentin Crettaz
Gold Digger

Joined: Aug 26, 2001
Posts: 7610
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.

[Blog] [Blogroll] [My Reviews] My Linked In
I agree. Here's the link:
subject: Array Initialisation in Methods
It's not a secret anymore!