static keyword

What is static keyword?
The static keyword denotes that a member variable or method, can be accessed without  instantiation of the class to which it belongs. In simple term, it means that you can call a method, even if you've never created the object of a class to which it belongs.

The static keywords can be variables or methods.
  1. Static variables
  2. Static methods
Static Keyword
The Static keyword can not be applied to following
  1. Class (Not Nested)
  2. Constructor
  3. Interfaces
  4. Instance Variables
  5. Local Variables
1) Static variables
  1. When a variable is declared with the keyword static, its called a class variable. All instances share the same copy of the variable.
  2. A class variable can be accessed directly with the class, without the need to create a instance.
  3. The static variable can be used to refer the common property of all objects (that is unique for each object) e.g. company name of employees,college name of students etc.
  4. The static variable gets memory only once in class area at the time of class loading.

1
2
3
4
5
class TestClass {
 int rollno;
 String name;
 static String college = "COEM"; // Static variable
}

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.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
//Program of static variable  

class Student {

 int rollno;
 String name;
 static String college = "COEM";

 Student(int r, String n) {
  rollno = r;
  name = n;
 }

 void display() {
  System.out.println(rollno + " " + name + " " + college);
 }

 public static void main(String args[]) {
  Student s1 = new Student(111, "John");
  Student s2 = new Student(222, "Jerry");
  s1.display();
  s2.display();
 }
}

Output:
111 John COEM
222 Jerry COEM

2) static method
  1. It is a method which belongs to the class and not to the object(instance).
  2. A static method can access only static data and can change the value of it. It can not access non-static data (instance variables).
  3. A static method can be accessed directly without creation of an object.
Example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Addition {
 static int add(int x, int y) {
  return x + y;
 }

 public static void main(String args[]) {
  int result = Addition.add(5, 5);
  System.out.println(result);
 }
}

The above add() method which is declared as static can be invoke without creating an object of class Addition.



<-- Previous || Next -->

2 comments:

  1. It was so nice article. Thank you for valuable information

    ReplyDelete
  2. This comment has been removed by a blog administrator.

    ReplyDelete