Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading