import java.util.*;
class Example {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
System.out.print("Input an integer : ");
int num = input.nextInt();
int y;
if (num > 100) {
y = 200;
}
if (num < 100) {
y = 200;
}
if (num == 100) {
y = 200;
}
System.out.println(y);
}
}
ERROR:
Example.java:19: error: variable y might not have been initialized
System.out.println(y);
^
CodePudding user response:
If none of the if-branches is entered, y is never initialized. Since accessing an uninitialized local variable is illegal, the compiler generates an error (as defined in JLS, §16). The compiler is not able to infer that one of the three cases must be entered.
I recommend to use else if in the 2nd case and else in the 3rd case:
import java.util.Scanner;
class Example {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
System.out.print("Input an integer : ");
int num = input.nextInt();
int y;
if (num > 100) {
y = 200;
}
else if (num < 100) {
y = 200;
}
else /* if (num == 100) */ {
y = 200;
}
System.out.println(y);
}
}
CodePudding user response:
Javac does NOT flow-analysis. In other word, you know that either num > 100, num < 100, or num == 100 is true but javac doesn't know.
In this case, you can combine those if by else if and else like that:
if (num > 100) {
y = 200;
} else if (num < 100) {
y = 200;
} else { // num == 100 must be true
y = 200;
}
You may also assign some value (eg. 0) to y, but above solution is more clear.
