0

when I compile below code, say "variable y might not have been initialized". why this happen?

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);
    }
}
  • 1
    you should do this with ```if..else if..else``` – tmsbrndz Jan 07 '22 at 08:54
  • Does this answer your question? [Variable might not have been initialized error](https://stackoverflow.com/questions/2448843/variable-might-not-have-been-initialized-error) – Tom Jan 07 '22 at 08:55
  • 1
    because it is only initialized if one of those conditions returns true, otherwise, it isn't. just initialize a default value on declaration of the variable – Stultuske Jan 07 '22 at 08:55
  • `int y;` if no `if` is entered into - then what is the value of `y` ? – Scary Wombat Jan 07 '22 at 08:55

0 Answers0