Pin It

How local variables behaves inside a block of code in Java ?

Program to demonstrate initialization of local variables and usage in Java

public class LocalFields {

   public static void main(String[] args) {
  
      int local;  //uninitialized local variable 
                     
      int field = 10;
  
      if(field > 10){
 local = 10;
      }
  
      if(field < 10){
 local = 11;
      }
  
      if(field == 10){
 local = 12;
      }
  
     // below lines throws compile time error because
     //compiler doesn't computes that which if will execute
     //it sees that local is been used without being initialized
     System.out.println("The value of local is : " + local);

  }

}


The correct implementation of the program :
public class LocalFields {

   public static void main(String[] args) {
  
      int local= 0;  // always initialize local variables 
              // before use 
                     
      int field = 10;
  
      if(field > 10){
 local = 10;
      }
  
      if(field < 10){
 local = 11;
      }
  
      if(field == 10){
 local = 12;
      }
  
     System.out.println("The value of local is : " + local);

  }

}



Output of the program : 

 
Please Give Us Your 1 Minute In Sharing This Post!
SOCIALIZE IT →
FOLLOW US →
SHARE IT →
Related Posts Plugin for WordPress, Blogger...

Post your related queries below ...

comments powered by Disqus
Powered by Blogger.
 
© 2012 Learn Java by Examples Template by Hubber Spot