Java comprises 5 conditional blocks namely – if, switch, while, for and try.
In all these blocks, if the specified condition is true, the code inside the block is executed and vice-versa. Also, Java compiler doesn’t let you leave a local variable uninitialized.
While initializing local variable inside a conditional block, one must bear the following 3 details in mind:
1. If the specified condition is true, and ‘values’ are provided in the condition, the program compiles fine.
2. If the specified condition is true, but ‘variables’ are provided in the condition, we get a compilation error.
3. If the specified condition is false, we get a compilation error.
The above-given points are true for both primitive and reference type local variables.
The code below will give a compilation error.
Output: prog.java:8: error: variable j might not have been initialized System.out.println("j :" + j); ^ 1 error
The condition in the if statement is false. Hence, local variable ‘j’ never gets initialized. Thus, trying to reference uninitialized variable ‘j’ in line8 gives a compilation error.
To avoid this, initialize your local variable to a default value outside the conditional block.
The code below works fine-
Output: j :0
Also, in Java, ‘values’ are read at compile time. But, ‘variables’ are read at run-time. Hence, when variables are a part of the condition, and another variable is initialized inside the conditional block, it gives an unexpected compile-time error.
Example: Have a look at the code below:
Output: prog.java:9: error: variable i might not have been initialized System.out.println("i :" + i); ^ 1 error
It gives a compilation error irrespective of the condition being true or false because Java didn’t read variables at compile time and thus ‘i’ isn’t initialized.
On the other hand, this doesn’t happen if values are specified instead of variables.
Output: i :95
- Instance Initialization Block (IIB) in Java
- Local Variable Type Inference or LVTI in Java 10
- Double Brace Initialization in Java
- Order of execution of Initialization blocks and Constructors in Java
- Local Inner Class in Java
- Final local variables in Java
- The Initializer Block in Java
- Are static local variables allowed in Java?
- Method and Block Synchronization in Java
- Static Block and main() method in Java
- Java Numeric Promotion in Conditional Expression
- Using _ (underscore) as variable name in Java
- Instance variable as final in Java
- Final static variable in Java
- Instance Variable Hiding in Java
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.