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

Thursday, 10 January 2013

Methods in Java


Method: method is a block of a class that contains logic of that class. Logic must be placed only inside a method, not directly at class level. If we place logic at class level compiler throws error.

Method Prototype: the head portion of the method is called method prototype.

Method body and logic: the “{}” region is called method body, and the statements placed inside method body is called logic.

Method parameters and arguments: the variables declared in method parenthesis “( )” are called parameters. We can define method with ZERO to ‘n’ number of parameters.
The values passing to those parameters are called arguments. In method invocation we must pass arguments according to method parameters order and type.

Ex: void add (int a, float b) {  }     //here int a, float b are method parameters
Add (50, 60.5);   // here 50, 60.5 are arguments.

Method Signature: the combination of [Method name+parameters list] is called method signature.
Ex: void add (int a, int b) { }   // here add (int a, int b) is the method signature.

Method Return type: the keyword that is placed before method name is called method return type.
It tells to compiler and JVM about the type of the value is returned from this method after its execution.

Void return type keyword: if we do not want to return any value a method, we must use “void” as return type. It tells that the method does not return any value.
If we want to return any value a method, we must place data type keyword as return type.
Main method terminology with all above parts:

Public static void main (String[] args)
Public --     Accessibility modifier
Static --     Modifier
Void --      Return Type
Main --     Method Name
String [] -- Parameter Type
Args --      Parameter Name

The process of creating method with body is called method definition. This method is called Concrete Method.

Ex: public static void add(int a, int b){
System.out.println(a+b);
}

The process of creating method without body is called declaring a method/ method declaration. This method is called also abstract method. In method declaration the modifier “abstract” is mandatory and also should be terminated with “;”.
Ex: public native abstract void add(int a, int b);
1.   
  •     When we call a method control send to that method
  • .    If we pass argument that value is stored in parameter variable.
  • .    After method execution that parameter variable is destroyed and control is sent back to calling method.
  • .   Control is sent back to calling method with value if method has return type is not void.

Types of Methods: Basically concrete methods are divided into 3 types: 

  Based on static modifier we have two types of methods
  • Static methods
  • Non-static methods

We can call static methods directly from main method, but we cannot call non-static methods directly from main method. It leads CE:”non-static method cannot be referenced from static context”, because class level members will not get memory directly. JVM provides memory only if we use either “static or new” keywords. Main method has static keyword in its prototype since it is the initial point of class login execution; it must be identified and gets memory directly by JVM. Hence it has static keyword in its definition. Of course it must be called without object creation.
class MethodStatic
{          static void m1(){
                                System.out.println("in M1()");
                }
                void m2(){
                                System.out.println("M2() method");
                }
                public static void main(String[] args)
                {
                                System.out.println("Hello World! this is main Method");
                                m1();
                                MethodStatic ms=new MethodStatic();
                                ms.m2(); //it gets memory with reference to “ms” variable.
                }  }

2 Based on return type we have two types of methods
  •  Void methods
  •  Non-void methods

In void methods statements are optional, but in non-void methods return statement is mandatory with value range less than or equals to method return type range.
If we do not place return statement in non-void methods compiler throws CE: “missing return statement”

Types of return statements:  
return is only allowed in void method and constructor, and it is optional.
return value is only allowed in non-void methods, and it is mandatory.
Basically return statement is used to terminate method execution and for sending control back to calling method. In general, void methods are called in three ways 1. Directly—m1(); 2. As variable initialization statement—int x=m1();; 3.As SOPLN() argument—Sopln(m1());
The non-void methods can be called in all three ways.  In the first way the return value is lost. In the second way the returned value is stored in the destination variable. In the third way the returned value is printed on console.

3Based on parameter we have two types of methods
  •       Parameterized methods
  •       Non-parameterized methods


Wednesday, 9 January 2013

Access Modifiers in Java

The keywords which define accessibility permissions are called accessibility modifiers. Java supports four accessibility modifiers to define accessibility permissions at different levels.  In java, we have below 4 accessibility levels
1. Only within the class
2. Only within the package
3. Outside the package but only in subclass
4. From all places

Accessibility modifier keywords: To define the above four levels we have 3 key words.

  1.  Private: the class members which have private keyword in its creation statement are called private members. Those members are only accessible with in that class. 
  2. Protected: the class members which have protected keyword in its creation statements are called protected members. Those members can be accessible with in package from all classes, but from outside package only in subclass that too only by using subclass name or its object. 
  3. Public: the class and its member which have public keyword in its creation statement are called public members. Those members can be accessible from all places of java application. 
In class or its member’s declaration if we do not use any of the above 3 accessibility modifiers, the default accessibility level is package.
  • Default and public are the accessibility modifiers allowed for a class. 
  •  4 accessibility modifiers are allowed for class members. 
  • The default accessibility modifier of interface is package level and its member’s default accessibility is public.
Example:
class AccessModifierEx 
{
private static int a=10;
static int b=20;
protected static int c=30;
public static int d=40;

public static void main(String[] args) 
{
System.out.println("a="+a);
System.out.println("b="+b);
System.out.println("c="+c);
System.out.println("d="+d);
}
}