Shivakumar
Shivakumar

Reputation: 81

Java multiple variable Initialisation - How Does it work?

package com.mypackage;

import java.util.List;
import java.util.Map;

public class InitializationDemo {    

   public static void main(String[] args) {

       List<String> a, b = null;
       List<String> c = null, d = null;
       Map<String, String> e, f = null;
       Map<String, String> g = null, h = null;

       if(c == null){ //line $38: Works no compilation error
           // Do Something here
       }

       if(a == null) { //line #40: compilation error
           // Do Something here            
       } 

       if(e == null) { //line #44: compilation error
           // Do Something here            
       }

       if(g == null) { //line #46 Works no compilation error
           // Do Something here            
       } 
   }
}

Get the "The local variable a may not have been initialised." compilation error at line #40 and line #44:

I am trying to understand under the wood how does it work so that line #38 and #46 does not signal a compilation error however #40 and #44 signals compilation error.

Upvotes: 0

Views: 96

Answers (5)

Parker_Halo
Parker_Halo

Reputation: 505

Your code would become more readable and easier to handle with if you'd choose one notation. So either declare your variables as:

List<String> a = null, b = null, c = null, d = null;

or as

List<String> a = null;
List<String> b = null;
List<String> c = null;
List<String> d = null;

Another possiblitly to do this would be:

List<String> a, b, c, d;
a = b = c = d = null;

Upvotes: 1

subash
subash

Reputation: 3140

because you should initialize the local variable, local variables are not in the object level. it only having the local scope. so its not getting initialize on object creation. but in the code execution, jvm expect value for the each fields. so compiler tells you should initialize the local variable.

Upvotes: 0

Jean Jung
Jean Jung

Reputation: 1210

You should do a = null, b = null;. The initialization of the variables is like on the C language, each variable with your own value.

Upvotes: 1

akhil_mittal
akhil_mittal

Reputation: 24157

You are not initializing a and that is why it is complaining that it might not have been initialized. You should do:

List<String> a =null, b = null;

rather than:

List<String> a, b = null;

as the later one is equivalent to:

List<String> a;
List<String> b = null;

Upvotes: 4

ControlAltDel
ControlAltDel

Reputation: 35011

List<String> a, b = null;

this is equivalent to

List<String> a;
List<String> b = null;

Does that answer your question?

Upvotes: 4

Related Questions