Home > Mobile >  Variable initialization Error happen when compiling below java programme
Variable initialization Error happen when compiling below java programme

Time:01-29

Running this code I got the compiler error situation. why it happens?

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);
    }
}

CodePudding user response:

It's coming because the variable y is not initialized and the compiler thinks if none of the if statement is true then y would remain un-initialized and will not know what to print.

So you need to change

int y; 

to

int y=0;

Or some other initial value.

CodePudding user response:

Because We need to initialize every locale variables before using it, Lets say none of the condition matched then what should get printed in :

System.out.println(y);

Default Value of y , but compiler highlights that it may be an issue as you wanted some value of Y but its not assigned so check you code.

  •  Tags:  
  • Related