The Java compiler does not allow uninitialized local variables to be discarded. When a local variable is initialized inside a conditional block, the following three situations may happen:
If a value is provided in the conditional block and the given condition is true, the code compiles successfully.
If a variable (instead of a value) is provided in a conditional block and the condition is true, the code will give a compilation error.
If the condition that needs to be checked is false, the code will have a compilation error.
If local variables are initialized to default values outside the code's conditional block, no errors will occur and the code will compile successfully.
Demonstration
public class Demo{ public static void main(String args[]){ int i = 35; int j = 0; if (i > 32){ j = i + 11; } System.out.println("The value is: " + j); } }
The value is: 46
A class named Demo contains the main function. Here, two variables are defined, if one variable is greater than a specific number, the other value is added to it, and the ‘if’ block is closed. Then, print the results on the console.
The above is the detailed content of In Java, initialize local variables in conditional block. For more information, please follow other related articles on the PHP Chinese website!