In this code there is a compile time error.
"Example.java:17: error: variable y might not have been initialized".
Can anyone explain what's the reason for this error and how to fix it?
import java.util.*;
class Example{
public static void main (String args[]){
Scanner input=new Scanner(System.in);
System.out.println("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);
}
}
Before accessing a variable it must be initialized.
Static and instance variables are initialed implicitly even if you are not providing a value while declaring them. But with local variables, it's not the case, they must be assigned explicitly before you can use them.
You are not using else statement and it's not obvious to the compile that you've covered all possible cases.
Try this instead, you'll see that now variable y changes accordingly to the user input:
int y;
if (num < 100) {
y=100;
}
else if (num > 100) {
y=200;
}
else {
y=300;
}