Core Java - SPLessons

Java Members

Chapter 12

SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

Java Members

Java Members

shape Description

Java Members, A Java class contains members. Anything declared inside the body of the class is known as members of the class. Members are classified into 2 types as follows. Before the user has to know the definition of static, static is the key word, if developer declares static keyword before the method name, then it becomes a static method otherwise it becomes non static method. Java members have categorized into two types as follows.


Static members or Variable

shape Description

Java Members, Memory for the static variables will be allocated only once when the class is loaded. This variable also called as class variable why because memory is allocated once while loading the class. To access the static variable following is the syntax.

class_name.variable_name

Non-Static members or Variable

shape Description

Java Members, Memory for non-static variables will be allocated while creating an object to the class. For every new object, it will create memory and to access the non-static variable following is the syntax.

obj_ref.variable_name

shape Example

Following is an example to understand the concept of Java Members.
staticvariable.java

//This program will help to understand the concept Java Members.
class staticvariable
{
   static int count=0;
   public void increment()
   {
       count++;
   }
   public static void main(String args[])
   {
	   staticvariable obj1=new staticvariable();
	   staticvariable obj2=new staticvariable();
       obj1.increment();
       obj2.increment();
       System.out.println("Obj1: count is="+obj1.count);
       System.out.println("Obj2: count is="+obj2.count);
   }
}

Where created a static variable by static keyword as follows.

static int count=0;

Output
When compile the code output will be as follows.

Obj1: count is=2
Obj2: count is=2

Here an interesting task is that user can execute the code without main method(only before JDK 1.7 versions) also as follows.

class Splessons{  
  static{  
  System.out.println("static block is invoked");  
  System.exit(0);  
  }  
}  

In the above scenario you will get the result as “static block is invoked”.

Summary

shape Key Points

  • The static variables will be called with classname.methodname.
  • Memory will be allocated for static variables only when the class is loaded.