Thursday, June 22, 2017

Java-Analysis of a Java Program

Execution process of a java program
-----------------------------------
Execution of a java program always starts from main() method,it is starting point of execution to jvm.


main method must be declared as

public static void main(String args[]).

Program
------
class Sum
{
  //instance variables
  int a;
  int b;
  int c;

  public void init(int x,int y)
  {
    a=x;
    b=y;
  }
  public void add(){
   c=a+b;
  }
  public void show()
  {
    System.out.println("The sum is "+c);
  }
  public static void main(String args[])
  {
    Sum s=new Sum();//line1
    s.init(1,2);//line2
    s.add();//line3
    s.show();//line4
  }
}



In the above code when line1 is excuted an object is created for Sum class in a memory area called heap.

An object declaration consists of 2 parts

Sum s      =     new Sum();
---------        ----------
reference        Object  part
part

An object part consists

i)new operator
ii)constructor calling(Sum())

A new operator allocates memory for an object and invokes a constructor.

Construtor calling makes a call to a constructor of a class.

Whenever an object is created every object is provided with a unique address.

The address of object is initialized to a variable called as reference variable.


Methods are executed from a memory area called as stack as
shown in diagram.

An object consists of instance variables of a class

what is instance variable?
variable declared inside a class and outside a method and non static is known as instance variable.


what is local variable?
variable declared inside a method is known as local variable.

No comments: