MY mENU


Sunday 13 January 2013

Static and Non Static content in Java

Class level members which have static key word in their definition are called static members.
  1. Static variables
  2. Static Blocks
  3. Static Method
  4. Main Method
All static members are identified and get memory location at the time of class loading by default by JVM in method area. Only variables get memory location, methods will not have separate memory location like variables. They are just identified and can be accessed directly without object creation.

Can we declare local variable or parameter as static?
No, it is not possible. It leads to CE: “illegal start of expression” Because as being static variable it must get memory at the time of class loading, which is not possible  to provide memory to local variable the time of class loading. JVM provides individual memory location to each static variable in method area only once in a class life time.

Static variable get life as soon as class is loaded into JVM and is available till class is removed from JVM (or) JVM Shutdown. And it is class scope means it is accessible throughout the class.

Basically JVM will not execute class members directly. It executes class members in two phases. They are:
1.       Identification phase
2.       Execution phase
First JVM identifies complete class static members at the time of class loading from top to bottom. After identification them it starts the static member’s execution according to their priority. 

  • Identifying a variable means, creating its memory with default value based on its data type.
  • Identifying a method means, remembering its prototype.
  • Executing a variable means, storing its assigned value if any.
  • Executing a method means, executing its logic if it is called.
JVM will not execute static methods by itself. They are executed only if they are called explicitly by developer either from main method, or from static variable as its assignment statement or from static block. We can initialize variable with same variable name, this assignment is valid. In this case the variable value is replaced with same value.
            Int a=10;
            a=a;

Static block is always executed before main method.

Main method is public always because it must be called by JVM from outside of our package.

Why main method has static keyword in its definition?
Main () is the initial point of class logic execution. Hence it should be identified at the time of class loading. Due to this reason it contains static keyword in its prototype. Of course it must be executed without object creation.
Main() method is the mediator method between java Developer and JVM to inform methods execution order.

Why main() method return type is void?
Because if we return a value, it will be given to JVM which is useless. Hence main() method return type is void.

Why main () method parameter type is string [] array?
To pass command line arguments into java application.

Note: main () method should not be called from its own block or from a method that is calling from main(), it leads to exception java.lang.StackOverflowError.

Can we declare local variables as static?
No, local variables can’t be declared as static it leads to compile time error illegal start of expression. Because local variable should get memory location only if method is called. But if we declared as static contract is violating and it leads to compile time error.

Conclusion:
  • Using static keyword we can provide memory location directly for variables and methods.
  • If any variable or method is defined as static then we can access them using class name from outside class where they are defined.
  • In same class if the local variable and the static variable has the same name we can differ them using class name.
  • In method block static variable can’t be defined, it should be proved in class scope only.
  • Using static block a class can be executed without main () method.
NON-Static members:
The class level variable that does not have static keyword in its definition is called non-static variable. These members get memory location only if object is created with new keyword and constructor of that class in heap area by JVM in continuous memory locations. JVM will not provide memory location for these members by default by itself.

Object is a continuous memory location of non-static variables and non-static methods of  a class. Every object will have its own hash code. If it does not have its own hash code we should not call it as object.

Ex: Example e=new Example ().  Here is “e” is an object and new Example() is object creation statement.

How many objects can be created for a class?
Multiple objects. We can create multiple objects for a class, but their referenced variable name must be different. When we create multiple objects, non-static variables get separate copy of memory for each object. So to access non-static variables from a particular object we use that object’s referenced variable. If we modify one object data will not be affected to another object, because we change object data using its referenced variable.

If we print object referenced variable, print() or println() methods prints => classname@hashcode

toString() method is a predefined method available in java.lang.Object class to return object information in string format. Its default implementation is returning objects hashcode in hexa decimal string format. It is also called internally for print() and println() methods to print object.

So to print objects state when we print() object we have to override toString() method shown below code:

class ToStringOverride
{
        int id;
        String name,company;
        public String toString(){
                        return "id::"+id+"\n"+"Name::"+name+"\n"+"Company::"+company;
        }
        public static void main(String[] args)
        {
        ToStringOverride t=new ToStringOverride();
                        t.id=994;
                        t.name="mahanti";
                        t.company="FutureImpact";
                        System.out.println(t);
        }}

If non-static variables are accessed directly by their name (or) using class name it leads to compile-time error “Non-static variable cannot be referenced from static context”.

If non-static variables are accessed using null referenced variable it leads to run time error “java.lang.NullPointerException