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 |
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[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.
- Initializer Program
The Initializer
program illustrates the use of automatic initialization.
It declares field variables of every primitive type, the String
type, and object types.
It also declares a local array and then displays the values of these variables.
class Initializer {
boolean bo;
byte by;
char c;
short s;
int i;
long l;
float f;
double d;
String str;
Object obj;
void run() {
short[] sh = new short[2];
System.out.println("boolean: "+bo);
System.out.println("byte: "+by);
System.out.println("char: "+c);
System.out.println("short: "+s);
System.out.println("int: "+i);
System.out.println("long: "+l);
System.out.println("float: "+f);
System.out.println("double: "+d);
System.out.println("String: "+str);
System.out.println("Object: "+obj);
System.out.println("sh[0]: "+sh[0]);
System.out.println("sh[1]: "+sh[1]);
}
public static void main(String[] args) {
Initializer app = new Initializer();
app.run();
}
}
Output of the above Java Program.
boolean: false
byte: 0
char:
short: 0
int: 0
long: 0
float: 0.0
double: 0.0
String: null
Object: null
sh[0]: 0
sh[1]: 0
"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.