Types of variables java



In java There are 3 types of variables

1.local
2.instance variables
3.static variables


1. Local varaibles :#

Local variables are declared in methods, constructors, or blocks.

Local variables are created when the method, constructor or block is entered and the variable will be destroyed once it exits the method, constructor or block.

Access modifiers cannot be used for local variables.

Local variables are visible only within the declared method, constructor or block.

2.instance variables# :Instance variables are declared in a class, but outside a method, constructor or any block.

Access modifiers can be given for instance variables.

We can access them by using object of that class

3.Static variables and static methods:

  • # Class variables also known as static variables are declared with the static keyword in a class, but outside a method, constructor or a block.
  • #There would only be one copy of each class variable per class, regardless of how many objects are created from it.
  • #They are created when program starts they destroyed when program ends.
  • # We can access static variables using class name , no need to create an object.

like classname.variable name or classname.methodname

Example for all variables:

Class Employee{

      static String company_name="company name";
//static variable;
         
      int eemployeeNo; //instance variable;

          Employee(int eid){

             eemployeeNo=eid;
        }          


        void getSalary(){
     
         int sal=1000;//local variable

         s.o.p("salary of employee "+sal);


           }

         static  void getDetails(){
            s.o.p("details of company");

          }

        public static void main(String args[]){

           s.o.p(Employee.company_name);//accessing static variable

          Employee.getDetails();//static method call
    
          Employee e = new Employee(13);

 
         }

Comments