Java Fundamentals  «Prev  Next»

Lesson 8Automatic initialization of Java Variables
ObjectiveField variable and array initialization

Automatic initialization in Java

This page describes how field variables and arrays are initialized.
Java automatically initializes field variables [1] and the elements of arrays to the default values shown in the following table:

Type Default value
boolean false
byte 0
short 0
int 0
long 0
float 0.0
double 0.0
object type null

public class StringConversion {
 public static void main(String[] args) {
  String s1 = "a" + 'b' + 63; // line 1
  System.out.println("s1= " + s1);	
  String s2 = "a" + 63; // line 2
  System.out.println("s2= " + s2);
  // String s3= 'b'+ new Integer(63); //line 3 - Compiler Error
  System.out.println('b' + new Integer(63)); // line 4
  String s4 = 'b' + 63 + "a";
  System.out.println("s4= " + s4);
  /* Compiler Error - Type mismatch: 
  cannot convert from int to String */
  //String s5 = 63 + new Integer(10); 
/* Output of Program 
s1= ab63
s2= a63
s4= 161a

Modern Java
Java does not initialize non-array local variables[2] (also referred to as automatic variables) .
The Java compiler generates error messages when it detects attempts to use uninitialized local variables. The Initializer program shows how automatic initialization works.

"Local variables are sometimes called stack, temporary, automatic, or method variables, but the rules for these variables are the same regardless of what you call them."
"Local variables" are called automatic.
Local variables automatically cease to exist when the execution of the block in which they are declared completes.
  int x;
// x automatically vanishes here.

In computer programming, an automatic variable is a lexically-scoped variable which is allocated and de-allocated automatically when program flow enters and leaves the variable's scope.
The term local variable is usually synonymous with automatic variable[3], since these are the same thing in many programming languages.

[1]Field variable: A variable that is a member of a class.
[2]Local variable: A variable whose scope is limited to a code block within a method. Local variables are also referred to as automatic variables.
[3] Automatic variable: A variable whose scope is limited to a code block within a method. Automatic variables are also referred to as local variables.