Wednesday 27 January 2016

JAVA STATIC KEYWORD

The static keyword in java is used for memory management mainly. We can apply java static keyword with variables, methods, blocks and nested class. The static keyword belongs to the class than instance of the class.
The static can be:
  1. variable (also known as class variable)
  2. method (also known as class method)
  3. block
  4. nested class
1) Java static variable
If you declare any variable as static, it is known static variable
  • The static variable can be used to refer the common property of all objects (that is not unique for each object) e.g. company name of employees,college name of students etc.
  • The static variable gets memory only once in class area at the time of class loading.
Advantage of static variable
It makes your program memory efficient (i.e it saves memory).

Understanding problem without static variable
class Student{  
     int rollno;  
     String name;  
     String college="ITS"
Suppose there are 500 students in my college, now all instance data members will get memory each time when object is created.All student have its unique rollno and name so instance data member is good.Here, college refers to the common property of all objects.If we make it static,this field will get memory only once.

this keyword in java

Usage of java this keyword
Here is given the 6 usage of java this keyword.
  1. this keyword can be used to refer current class instance variable.
  2. this() can be used to invoke current class constructor.
  3. this keyword can be used to invoke current class method(implicitly)
  4. this can be passed as an argument in the method call.
  5. this can be passed as argument in the constructor call.
  6. this keyword can also be used to return the current class instance.
1) The this keyword can be used to refer current class instance variable.
If there is ambiguity between the instance variable and parameter, this keyword resolves the problem of ambiguity.

Understanding the problem without this keyword

class Student10{      int id;      String name;  
    Student10(int id,String name){      id = id;  
     name = name;  
    }  
    void display(){System.out.println(id+" "+name);}    
    public static void main(String args[]){      Student10 s1 = new Student10(111,"Karan");      Student10 s2 = new Student10(321,"Aryan");      s1.display();  
    s2.display();  
    }  
}  
Final Keyword In Java
The final keyword in java is used to restrict the user. The java final keyword can be used in many context. Final can be:
variable
method
class
The final keyword can be applied with the variables, a final variable that have no value it is called blank final variable or uninitialized final variable. It can be initialized in the constructor only. The blank final variable can be static also which will be initialized in the static block only. We will have detailed learning of these. Let's first learn the basics of final keyword.




No comments:

Post a Comment