Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class Variables Vs Method Variables

Tags:

java

While i am defining a class, i prefer to use following format.

public class ClassName{

   private String             var1 = null;
   private Map<String,String> map1 = null;

   public void process(){

      try{
           var1 = "Variable1";
           map1 = new HashMap<String,String>();

            // Do Some Stuffs Here with the varaibles.

      } catch(Exception e){
           e.printStackTrace();
      } finally{
           var1 = null;
           map1 = null;
      }

   }

}

But my friends suggest me to use following way,

public class ClassName{

   public void process(){

      String             var1 = null;
      Map<String,String> map1 = null;

      try{
           var1 = "Variable1";
           map1 = new HashMap<String,String>();

            // Do Some Stuffs Here with the varaibles.

      } catch(Exception e){
           e.printStackTrace();
      } finally{

      }

   }

}

My question is which is better and why?.

like image 718
Rakesh KR Avatar asked Mar 26 '26 19:03

Rakesh KR


1 Answers

This depends entirely on the situation. It is generally a good idea to define variables with the smallest scope possible. So unless you plan on using your variables outside of the method, just make them method variables.

like image 171
Dragondraikk Avatar answered Mar 29 '26 07:03

Dragondraikk