J2EEOnline  Tweet
GofPatterns OOPortal


Automatic initialization of Java Variables Field variable and array initialization
Lesson 8Automatic initialization of Java Variables
ObjectiveField variable and array initialization
Automatic initialization
Describe how field variables and arrays are initialized.
Java automatically initializes field variables and the elements of arrays to the default values shown in the following table:

Type Default value
boolean false
byte 0
char
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
161
s4= 161a
 */
Java does not initialize non-array local variables (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.
  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.