'My java code is not working because "the local variable has not been initialized" [duplicate]

    package fr.xeira.programme;

import java.util.Scanner; // import the Scanner class 

class Main {
  public static void main(String[] args) {
    Scanner myObj = new Scanner(System.in);
    String name;
    System.out.println("Enter First Number");

    String firstnumber = myObj.nextLine();
    System.out.println("Enter Symbol");
    String symbol = myObj.nextLine();
    System.out.println("Enter Second Number");
    String secondnumber = myObj.nextLine();

    int number = Integer.parseInt(firstnumber);

    int number2 = Integer.parseInt(secondnumber);

    int final1; //africa wakaka wakakakakakakakkakakakakakakwaaaa AFRIICAAAAAA WAWAKKAKAKWAKKAKKAK HEHEHEHE
    if (symbol == "+") {
        final1 = (number + number2);
    } else if(symbol == "-") {
        System.out.println(number - number2);
    } else if(symbol == "*") {
        System.out.println(number * number2);
    } else if(symbol == "/") {
        System.out.println(number / number2);
    }

    System.out.println(final1);
    }

}

It tells me (line 32) that "the local variable has not been initialized". Why is that? I initialize before the if statement, change it during the if statement, and now I'm simply trying to call it.

I'd apreciate some help ^^



Solution 1:[1]

When you declare int final1 on line 21, you have declared the variable, but not yet initialized because it has no value. You conditionally initialize it on line 23, but the compiler is detecting that the variable could not have a value by the time it reaches line 32 in runtime, so you get a compile error.

To fix, set final1 to a value for every possible condition, e.g.

int final1; //africa wakaka wakakakakakakakkakakakakakakwaaaa AFRIICAAAAAA WAWAKKAKAKWAKKAKKAK HEHEHEHE
if (symbol == "+") {
    final1 = (number + number2);
} else if(symbol == "-") {
    final1 = number - number2);
} else if(symbol == "*") {
    final1 = number * number2);
} else if(symbol == "/") {
    final1 = number / number2);
} else {
    final1 == //todo some value;
}

System.out.println(final1);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 MarkC