Friday, August 11, 2017

Final keyword


It is used to make a variable as a constant, Restrict method overriding, Restrict inheritance.

final keyword can be used in following way.

  1. Final at variable level
  2. Final at method level
  3. Final at class level



Final at variable level

Final keyword is used to make a variable as a constant.

A variable declared with the final keyword cannot be modified by the program after initialization.


Example

public class Circle

{

public static final double PI=3.14159;

public static void main(String[] args)

{

System.out.println(PI);

}
}



Final at method level

It makes a method final, meaning that sub classes cannot override this method.


Example

class Employee

{

 final void disp()

{ System.out.println("Hello Good Morning");

 }
}

class Developer extends Employee

{

void disp()

{

System.out.println("How are you ?");

} }

class FinalDemo

 {

 public static void main(String args[])

{

Developer obj=new Developer();

obj.disp();

}
}


Final at class level

It makes a class final, meaning that the class can not be inheriting by other classes.

example

final class Employee

 {

 int  salary=10000;

 }

class Developer extends Employee

{ void show()

 {

 System.out.println("Hello Good Morning");

} }

 class FinalDemo

{

 public static void main(String args[])

 {

Developer obj=new Developer();

 obj.show();

}
}

Recursion



The idea of calling one function from another immediately suggests the possibility of a function calling itself. The function-call mechanism in Java supports this possibility, which is known as recursion.

Syntax:

returntype methodname()

{  

//code to be executed  

methodname();//calling same method  

}  

Example

public class RecursionExample
{
   int factorial(int n)
 {
  if(n==1)
   return 1;
  else
 return(n * factorial(n-1));
}
public static void main(String[] args)
{
RecursionExample ob=new RecursionExample();
 System.out.println("Factorial of 5 is:"+ob.factorial(5));
}
}

Argument Passing


There is only call by value in java, not call by reference. If we call a method passing a value, it is known as call by value. The changes being done in the called method, is not affected in the calling method.

Example
Object as Argument
class CallByValue1
{
int data=50;
void change(CallByValue1 op)
{
op.data=op.data+100;//changes will be in the instance variable 
}
public static void main(String args[])
{
 CallByValue1 op=new CallByValue1();
 System.out.println("before change "+op.data);
 op.change(op);//passing object
 System.out.println("after change "+op.data);
 }
}

Example

Value As an Argument

class CallbyValue
{
int data=50;
void change(int data)
{
data=data+100;//changes will be in the local variable only
//System.out.println("local change change"+data);
}
public static void main(String args[])
{
CallbyValue op =new CallbyValue();
System.out.println("before change"+op.data);
op.change(500);
System.out.println("after change"+op.data);
}
}

Method Overloading


If two or more method in a class has same name but different parameters, it is known as method overloading.

Method overloading can be done by changing number of arguments or by changing the data type of arguments.

If two or more method have same name and same parameter list but differs in return type are not said to be overloaded method.



Different ways to overload the method

  1. By changing number of arguments or parameters.
  2. By changing the data type.
  3. Sequence of Data type of parameters.

When an overloaded method is called the compiler looks for exact match.

Sometime when exact match is not found, java automatic type conversion plays a vital role

Example for By changing number of arguments or parameters.
class ChangeArgumentList
{
 void find(int l, int b)
 {
  System.out.println("Area is"+(l*b)) ;
 }
 void find(int l, int b,int h)
 {
  System.out.println("Area is"+(l*b*h));
 }
 public static void main (String[] args)
 {
  ChangeArgumentList  ar = new ChangeArgumentList();
  ar.find(8,5);     //find(int l, int b) is method is called.
  ar.find(4,6,2);    //find(int l, int b,int h) is called.
 }
}


Example for By changing the data type.
class ChangeDataType
{
 void sum (int a, int b)
 {
  System.out.println("sum is"+(a+b)) ;
 }
 void sum (float a, float b)
 {
  System.out.println("sum is"+(a+b));
 }
 public static void main (String[] args)
 {
  ChangeDataType  cal = new ChangeDataType();
  cal.sum (8,5);      //sum(int a, int b) is method is called.
  cal.sum (4.6f, 3.8f); //sum(float a, float b) is called.
 }
}

Example for Sequence of Data type of parameters.

class SequnceOfDatatye
{
   public void disp(char c, int num)
   {
       System.out.println("I’m the first definition of method disp");
   }
   public void disp(int num, char c)
   {
       System.out.println("I’m the second definition of method disp" );
   }
}
class Sample3
{
   public static void main(String args[])
   {
       SequnceOfDatatye obj = new SequnceOfDatatye();
       obj.disp('x', 51 );
       obj.disp(52, 'y');
   }
}



Constructor Overloading



Whenever same constructor is existing multiple times in the same class with different number of parameters or order of parameters or type of parameters is known as Constructor overloading.

The compiler differentiates these constructors by taking into account the number of parameters in the list and their type.

Constructor overloading can be used to initialize same or different objects with different values.

Example
 // Constructor Overloading
class Box
{
 double width, height, depth;
 // constructor used when all dimensions
 // specified
 Box(double w, double h, double d)
 {
  width = w;
  height = h;
  depth = d;
 }
 // constructor used when no dimensions
 // specified
 Box()
 {
  width = height = depth = 0;
 }
 // constructor used when cube is created
 Box(double len)
 {
  width = height = depth = len;
 }
 // compute and return volume
 double volume()
 {
  return width * height * depth;
 }
}
// Driver code
public class Test
{
 public static void main(String args[])
 {
  // create boxes using the various
  // constructors
  Box mybox1 = new Box(10, 20, 15);
  Box mybox2 = new Box();
  Box mycube = new Box(7);
  double vol;
  // get volume of first box
  vol = mybox1.volume();
  System.out.println(" Volume of mybox1 is " + vol);
  // get volume of second box
  vol = mybox2.volume();
  System.out.println(" Volume of mybox2 is " + vol);
  // get volume of cube
  vol = mycube.volume();
  System.out.println(" Volume of mycube is " + vol);
 }
}

Garbage Collection


Garbage Collection is process of reclaiming the runtime unused memory automatically.

In other words, it is a way to destroy the unused objects.

Advantages of Garbage Collection

  1. Programmer doesn't need to worry about dereferencing an object.
  2. It is done automatically by JVM.
  3. Increases memory efficiency and decreases the chances for memory leak.



How can an object be unreferenced

There are many ways:

  1. By nulling the reference
  2. By assigning a reference to another
  3. By anonymous object

By nulling a reference

Employee e=new Employee();  

e=null; 

By assigning a reference to another

Employee e1=new Employee();  

Employee e2=new Employee();  

e1=e2;//now the first object referred by e1 is available for garbage collection  

By anonymous object

new Employee();  





finalize() method


The finalize() method is invoked each time before the object is garbage collected.

This method can be used to perform cleanup processing.

 protected void finalize()

{

 

Important Points to Remember

  1. finalize() method is defined in java.lang.Object class, therefore it is available to all the classes.
  2. finalize() method is declare as proctected inside Object class.
  3. finalize() method gets called only once by a Daemon thread named GC (Garbage Collector)thread



gc() method

The gc() method is used to invoke the garbage collector to perform cleanup processing.

 The gc() is found in System and Runtime classes.

Syntax

public static void gc(){} 



example

Constructors


Constructor is a special type of method that is used to initialize the state of object.

It provides the values to the data members at the time of object creation that is why it is known as constructor.

Characteristics of constructor

1. A constructor must have the same name as of its class.

2. It is invoked at the time of object creation and used to initialize the state of an object.

3. It does not have an explicit return type.



Types of constructor

1. Default or no-argument constructor.

2. Parameterized constructor.

Default or no-argument constructor

A constructor with no parameter is known as default or no-argument constructor.

If no constructor is defined in the class then compiler automatically creates a default constructor at the time of compilation.

Syntax

Class_name()

{
//optional block of code

}



Parameterized constructor

A constructor with one or more arguments is known as parameterized constructor.

Parameterized constructor is used to provide values to the object properties.

By use of parameterized constructor different objects can be initialize with different states.

 Syntax

class ClassName

{ .......

ClassName(list of parameters) //parameterized constructor

{ .......

 }

....... }



Important points Related to Parameterized Constructor

      Whenever we create an object using parameterized constructor, it must be define parameterized constructor otherwise we will get compile time error.

      Whenever we define the objects with respect to both parameterized constructor and default constructor, It must be define both the constructors.

      In any class maximum one default constructor but 'n' number of parameterized constructors.
Difference between Method and Constructor

Methods


A method is a collection of statements that are grouped together to perform an operation.

Method describes the behavior of an object

Creating Method

Syntax

modifier returnType nameOfMethod (Parameter List) {

// method body

}



Parameter Vs. Argument



Parameter is variable defined by a method that receives value when the method is called.

Parameter are always local to the method they dont have scope outside the method.

argument is a value that is passed to a method when it is called.



Example