Do i have to initialise a variable in every if else statement in Java?

    int outsideTem = 10;
    String output;
    if(outsideTem < 0){
        //output = "Grab a coat";// i get an error if i comment out this line but why?
        //System.out.println(output);
    }
    else if(outsideTem < 15){
        output = "Grab a cardigan";
        //System.out.println(output);
    }
    else{
        output = "HOT!!!";
        //System.out.println("HOT!!!");
    }
    System.out.println(output);

Getting an error if i comment out the variable from the if block. But I tried to intialise it before and it is working. But I am not sure why

    int outsideTem = 10;
    String output = "";// tried this and it is working but not sure why
    if(outsideTem < 0){
        //output = "Grab a coat";// i get an error if i comment out this line but why?
        //System.out.println(output);
    }
    else if(outsideTem < 15){
        output = "Grab a cardigan";
        //System.out.println(output);
    }
    else{
        output = "HOT!!!";
        //System.out.println("HOT!!!");
    }
    System.out.println(output);

>Solution :

Yes, variables need to be initialized before you can use them.
You are trying to use the variable in the print statement. In case outsideTemp is smaller than 0 and the line is commented out, what would you expect Java to print in that line?

You don’t need to initialize in the if however. You could already initialize it when you declare the variable.

So the following would work:

public class Application {

    public static void main(String[] args) {
        int outsideTem = 10;
        // initialize here
        String output = "";
        if(outsideTem < 0){ // unused if here, but compiling code
            //output = "Grab a coat";
            //System.out.println(output);
        }
        else if(outsideTem < 15){
            output = "Grab a cardigan";
            //System.out.println(output);
        }
        else{
            output = "HOT!!!";
            //System.out.println("HOT!!!");
        }
        System.out.println(output);
    }

}

Leave a Reply