stackko state
stackko state

Reputation: 15

variable result might not have been initialized

error showing in the last line as

:::: variable result might not have been initialized

this is my code:

public static void main(String args[]){
    int n1, n2, result;
    char oper;
    n1=1000;
    n2=200;
    oper= '+';

    if(oper == '+')
        result=n1+n2;
    else if(oper == '-')
        result= n1-n2;
    else if(oper == '*')
        result= n1*n2;
    else if(oper == '/')
        result= n1/n2;
    else if(oper == '%')
        result= n1%n2;

    System.out.println("Answer: "+result);
}

Upvotes: 1

Views: 714

Answers (2)

Shanu Gupta
Shanu Gupta

Reputation: 3817

Your first line should be:

int n1, n2, result=0;

result variable was not initialized nor it could be calculated from the code, hence the compiler thinks it won't find the value of the variable. Thus its giving compilation error.

Upvotes: 1

Saurav Sahu
Saurav Sahu

Reputation: 13964

You need to understand why you got this error:

  1. In case of method's local variable, Java guarantees that the variable is properly initialized before it's used.

  2. Variable result may miss getting initialized in case none of the if-else if clause gets satisfied. Note that you have not put any else clause at end to update variable result before it get used in this statement System.out.println("Answer: "+result);

Upvotes: 1

Related Questions