In Java, variables and instances are assigned default values depending on their data types when they are declared but not explicitly initialized. Here’s a summary of the default values for each data type:
Primitive Data Types
- byte: 0
- short: 0
- int: 0
- long: 0L
- float: 0.0f
- double: 0.0
- char: '\u0000' (null character)
- boolean: false
Reference Data Types
- Objects (including arrays): null
Example in a Class
When you declare instance variables in a class, they receive these default values:
class Example {
byte b; // default 0
int i; // default 0
boolean flag; // default false
String str; // default null
}
Local Variables
Local variables, on the other hand, do not receive default values. They must be explicitly initialized before use:
void method() {
int localVar; // must be initialized before use
// System.out.println(localVar); // This will cause a compilation error
}
Summary
- Instance variables get default values based on their type.
- Local variables do not have default values and must be initialized before they can be accessed.