Concept Flow - Default values
Declare variable
No explicit initialization?
Yes
Assign default value
Use variable in code
When a variable is declared but not given a value, Java assigns a default value based on its type before it is used.
int number; boolean flag; System.out.println(number); System.out.println(flag);
| Step | Action | Variable | Value | Output |
|---|---|---|---|---|
| 1 | Declare int number without initialization | number | 0 (default) | |
| 2 | Declare boolean flag without initialization | flag | false (default) | |
| 3 | Print number | number | 0 | 0 |
| 4 | Print flag | flag | false | false |
| 5 | End of program |
| Variable | Start | After Declaration | Final |
|---|---|---|---|
| number | undefined | 0 | 0 |
| flag | undefined | false | false |
Default values in Java: - Instance and class variables get default values automatically - int defaults to 0, boolean to false, object references to null - Local variables must be initialized before use - Helps avoid uninitialized variable errors - Default values depend on variable type
int variable inside a class?int default to 0 if not initialized.int variableint inside a class will have the default value 0.null or 0 to boolean is invalid and causes errors.class Test {
int x;
boolean b;
String s;
void printValues() {
System.out.println(x + "," + b + "," + s);
}
}
public class Main {
public static void main(String[] args) {
Test t = new Test();
t.printValues();
}
}public class Sample {
static int count;
public static void main(String[] args) {
int number;
System.out.println(count);
System.out.println(number);
}
}double values representing temperatures. You declare:double[] temps = new double[5];
temps immediately after this declaration?double, it's 0.0.new double[5], all 5 elements are initialized to 0.0 automatically.Pass the test and this pattern moves unknown