-5
public class LocalVariables {

    static public void main(String args[]){

        int var;

        if(args.length > 0){
            var = 10;

        }

        else{
            var = 20;
        }
        System.out.println(var);
    }

}

Here if I remove else part it's showing compilation error as:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
The local variable var may not have been initialized

Explain how the local variable value is initialized if I use else part.

Eugene S
  • 6,709
  • 8
  • 57
  • 91
vny uppara
  • 119
  • 6

3 Answers3

2

Look at it like this what happens when the if condition in your code is not met? The reason you would be getting an error saying :

The local variable var may not have been initialized

is because if the condition is false you really don't have var initialised, do you?

On the other hand else was serving the purpose of ensuring the initialization in the existing code for you.

Naman
  • 27,789
  • 26
  • 218
  • 353
  • When the condition of IF is not met the output is 20 . Tell me how else part is ensuring initialization why not if part? – vny uppara Dec 02 '16 at 09:53
  • once you remove `else` part and your args.length `< =0`. Could you tell me what would be the value of `var` in your code? – Naman Dec 02 '16 at 11:20
1

if you remove else block, what would be the value of var if(args.length<0) ? The compiler doesn't know that. So it shows you error. Either you have to initialize the var during declaration or you need to initialize in both if and else block.

Habin
  • 792
  • 1
  • 11
  • 21
-1

When executing main method, surely you do not provide args argument. So args.length > 0 returns false.

sk001
  • 561
  • 6
  • 27