dineshonjava

Compile Time Polymorphism in Java

Compile time polymorphism or static method dispatch is a process in which a call to an overloading method is resolved at compile time rather than at run time. In this process, we done overloading of methods is called through the reference variable of a class here no need to superclass. 

Method Overloading in Java:
If a class have multiple methods by same name but different parameters, it is known as Method Overloading.

If we have to perform only one operation, having the same name of the methods increases the readability of the program. Suppose you have to perform addition of the given numbers but there can be any number of arguments, if you write the method such as sum(int,int) for two parameters, and sum2(int,int,int) for three parameters then it may be difficult for you as well as other programmers to understand the behavior of the method because its name differs. So, we perform method overloading to figure out the program quickly.
Advantage of method overloading?

Method overloading increases the readability of the program.

Different ways to overload the method:
There are two ways to overload the method in java


  • By changing number of arguments
  • By changing the data type

1. Example of By changing number of arguments:
class Calculation{
  void sum(int a,int b)
  {
     System.out.println(a+b);
  }
  void sum(int a,int b,int c){
     System.out.println(a+b+c);
   }

  public static void main(String args[]){
  Calculation obj=new Calculation();
  obj.sum(10,10,10);
  obj.sum(20,20);

  }
}
output:
30
40

2. Example of By changing the data type:
In this example, we have created two overloaded methods that differs in data type. The first sum method receives two integer arguments and second sum method receives two double arguments.

class Calculation{
  void sum(int a,int b){
    System.out.println(a+b);
   }
  void sum(double a,double b){
    System.out.println(a+b);
  }

  public static void main(String args[]){
  Calculation obj=new Calculation();
  obj.sum(11.5,11.5);
  obj.sum(30,20);

  }
}

output:
23.0
50


Why Method Overloaing is not possible by changing the return type of method?


In java, method overloading is not possible by changing the return type of the method because there may occur ambiguity. Let's see how ambiguity may occur:
class Calculation{
  int sum(int a,int b)
  {
    System.out.println(a+b);
  }
  double sum(int a,int b){
    System.out.println(a+b);
   }

  public static void main(String args[]){
  Calculation obj=new Calculation();
  int result=obj.sum(30,20); //Compile Time Error
  }
}

Method Overloading and TypePromotion:

One type is promoted to another implicitly if no matching datatype is found. Let's understand the concept by the figure given below:

Compile Time Polymorphism in Java

As displayed in the above diagram, byte can be promoted to short, int, long, float or double. The short datatype can be promoted to int,long,float or double. The char datatype can be promoted to int,long,float or double and so on.


Example of Method Overloading with TypePromotion:
class Calculation{
  void sum(int a,long b){System.out.println(a+b);}
  void sum(int a,int b,int c){System.out.println(a+b+c);}

  public static void main(String args[]){
  Calculation obj=new Calculation();
  obj.sum(20,20);//now second int literal will be promoted to long
  obj.sum(20,20,20);

  }
}

Output:
40
60

Example of Method Overloading with TypePromotion if matching found:
If there are matching type arguments in the method, type promotion is not performed.

class Calculation{
  void sum(int a,int b){System.out.println("int arg method invoked");}
  void sum(long a,long b){System.out.println("long arg method invoked");}

  public static void main(String args[]){
  Calculation obj=new Calculation();
  obj.sum(20,20);//now int arg sum() method gets invoked
  }
}

Example of Method Overloading with TypePromotion in case ambiguity:
If there are no matching type arguments in the method, and each method promotes similar number of arguments, there will be ambiguity.
class Calculation{
  void sum(int a,long b){System.out.println("a method invoked");}
  void sum(long a,int b){System.out.println("b method invoked");}

  public static void main(String args[]){
  Calculation obj=new Calculation();
  obj.sum(20,20);//now ambiguity
  }
}

Output:

Compile Time Error

Using null to overload methods in Java [duplicate]:
The following code compiles and goes fine.
public class Main
{
    public void temp(Object o)
    {
        System.out.println("The method with the receiving parameter of type Object has been invoked.");
    }

    public void temp(String s)
    {
        System.out.println("The method with the receiving parameter of type String has been invoked.");
    }

    public void temp(int i)
    {
        System.out.println("The method with the receiving parameter of type int has been invoked.");
    }

    public static void main(String[] args)
    {
        Main main=new Main();
        main.temp(null);
    }
}
In this code, the method to be invoked is the one that accepts the parameter of type String
Output:

The method with the receiving parameter of type String has been invoked.

If more than one member method is both accessible and applicable to a method invocation, it is necessary to choose one to provide the descriptor for the run-time method dispatch. The Java programming language uses the rule that the most specific method is chosen.
Where you pass null as argument for an overloaded method, the method chosen is the method with the most specialized type, so in this case: String is chosen rather than the most tolerant: Object.

Among Object/String/int the choice is clear for the compiler: you will get the String's one cause an int cannot be null and so its corresponding method is not eligible to be called in this case.

But if you change int for Integer, compiler will be confuse because both methods taking String is as accurate as Integer's one (orthogonal in hierarchy).



<<Previous <<   || Index ||   >>Next >>


Runtime Polymorphism in Java

Runtime polymorphism or dynamic method dispatch is a process in which a call to an overridden method is resolved at runtime rather than at compile-time. In this process, an overridden method is called through the reference variable of a superclass. The determination of the method to be called is based on the object being referred to by the reference variable.

Upcasting:

When reference variable of Parent class refers to the object of Child class, it is known as upcasting.
For example:
Runtime Polymorphism in Java
class A{}
class B extends A{}
class Test{
   public static void main(String args[]){
   A a=new B();//upcasting
  }
}
Example of Runtime Polymorphism:

In this example, we are creating two classes Bicycle and HondaShine. HondaShine class extends Bicycle class and overrides its run() method. We are calling the run method by the reference variable of Parent class. Since it refers to the subclass object and subclass method overrides the Parent class method, subclass method is invoked at runtime. Since it is determined by the compiler, which method will be invoked at runtime, so it is known as runtime polymorphism.

class Bicycle{
   void run(){
   System.out.println("bicycle is running");
   }
 }
 class HondaShine extends Bicycle{
   void run(){
     System.out.println("shine is running safely with 70km");
    }
 
   public static void main(String args[]){
     Bicycle b = new HondaShine();//upcasting
     b.run();
   }
 }

Output:
shine is running safely with 70km

Runtime Polymorphism with data member:

Method is overriden not the datamembers, so runtime polymorphism can't be achieved by data members.
In the example given below, both the classes have a datamember speedlimit, we are accessing the datamember by the reference variable of Parent class which refers to the subclass object. Since we are accessing the datamember which is not overridden, hence it will access the datamember of Parent class always.

class Bicycle{
  int speedlimit=100;
 }
 class HondaShine extends Bicycle{
  int speedlimit=160;
 
  public static void main(String args[]){
   Bicycle obj=new HondaShine();
   System.out.println(obj.speedlimit);
 }
}

Output:
100

Note: Runtime polymorphism can't be achieved by data members.



<<Previous <<   || Index ||   >>Next >>


Polymorphism in Java

The dictionary definition of polymorphism refers to a principle in biology in which an organism or species can have many different forms or stages. This principle can also be applied to object-oriented programming and languages like the Java language. Subclasses of a class can define their own unique behaviors and yet share some of the same functionality of the parent class.

Polymorphism can be demonstrated with a minor modification to the Bicycle class. For example, a printDescription method could be added to the class that displays all the data currently stored in an instance.

public void printDescription(){
    System.out.println("\nBike is " + "in gear " + this.gear
        + " with a cadence of " + this.cadence +
        " and travelling at a speed of " + this.speed + ". ");
}
To demonstrate polymorphic features in the Java language, extend the Bicycle class with a MountainBike and a RoadBike class. For MountainBike, add a field for suspension, which is a String value that indicates if the bike has a front shock absorber, Front. Or, the bike has a front and back shock absorber, Dual.

Here is the updated class:
public class MountainBike extends Bicycle {
    private String suspension;

    public MountainBike(
               int startCadence,
               int startSpeed,
               int startGear,
               String suspensionType){
        super(startCadence,
              startSpeed,
              startGear);
        this.setSuspension(suspensionType);
    }

    public String getSuspension(){
      return this.suspension;
    }

    public void setSuspension(String suspensionType) {
        this.suspension = suspensionType;
    }

    public void printDescription() {
        super.printDescription();
        System.out.println("The " + "MountainBike has a" +
            getSuspension() + " suspension.");
    }
} 

Note the overridden printDescription method. In addition to the information provided before, additional data about the suspension is included to the output.

Next, create the RoadBike class. Because road or racing bikes have skinny tires, add an attribute to track the tire width. Here is the RoadBike class:
public class RoadBike extends Bicycle{
    // In millimeters (mm)
    private int tireWidth;

    public RoadBike(int startCadence,
                    int startSpeed,
                    int startGear,
                    int newTireWidth){
        super(startCadence,
              startSpeed,
              startGear);
        this.setTireWidth(newTireWidth);
    }

    public int getTireWidth(){
      return this.tireWidth;
    }

    public void setTireWidth(int newTireWidth){
        this.tireWidth = newTireWidth;
    }

    public void printDescription(){
        super.printDescription();
        System.out.println("The RoadBike" + " has " + getTireWidth() +
            " MM tires.");
    }
}

Note that once again, the printDescription method has been overridden. This time, information about the tire width is displayed.

To summarize, there are three classes: Bicycle, MountainBike, and RoadBike. The two subclasses override the printDescription method and print unique information.

Here is a test program that creates three Bicycle variables. Each variable is assigned to one of the three bicycle classes. Each variable is then printed.
public class TestBikes {
  public static void main(String[] args){
    Bicycle bike01, bike02, bike03;

    bike01 = new Bicycle(20, 10, 1);
    bike02 = new MountainBike(20, 10, 5, "Dual");
    bike03 = new RoadBike(40, 20, 8, 23);

    bike01.printDescription();
    bike02.printDescription();
    bike03.printDescription();
  }
}

The following is the output from the test program:

output:
Bike is in gear 1 with a cadence of 20 and travelling at a speed of 10.

Bike is in gear 5 with a cadence of 20 and travelling at a speed of 10.
The MountainBike has a Dual suspension.

Bike is in gear 8 with a cadence of 40 and travelling at a speed of 20.
The RoadBike has 23 MM tires.

Types of Polymorphism in Java:
There are following two type polymorphism in java.

1. Run Time Polymorphism(Method overriding)
2. Compile Time Polymorphism(Method overloading)



<<Previous <<   || Index ||   >>Next >>



Overriding and Hiding Methods in Java

Instance Methods

An instance method in a subclass with the same signature (name, plus the number and the type of its parameters) and return type as an instance method in the superclass overrides the superclass's method.

The ability of a subclass to override a method allows a class to inherit from a superclass whose behavior is "close enough" and then to modify behavior as needed. The overriding method has the same name, number and type of parameters, and return type as the method it overrides. An overriding method can also return a subtype of the type returned by the overridden method. This is called a covariant return type.

When overriding a method, you might want to use the @Override annotation that instructs the compiler that you intend to override a method in the superclass. If, for some reason, the compiler detects that the method does not exist in one of the superclasses, it will generate an error. For more information on @Override, see Annotations.

Class Methods


If a subclass defines a class method with the same signature as a class method in the superclass, the method in the subclass hides the one in the superclass.

The distinction between hiding and overriding has important implications. The version of the overridden method that gets invoked is the one in the subclass. The version of the hidden method that gets invoked depends on whether it is invoked from the superclass or the subclass. Let's look at an example that contains two classes. The first is Animal, which contains one instance method and one class method:

public class Animal {
    public static void testClassMethod() {
        System.out.println("The class" + " method in Animal.");
    }
    public void testInstanceMethod() {
        System.out.println("The instance " + " method in Animal.");
    }
}

The second class, a subclass of Animal, is called Cat:
public class Cat extends Animal {
    public static void testClassMethod() {
        System.out.println("The class method" + " in Cat.");
    }
    public void testInstanceMethod() {
        System.out.println("The instance method" + " in Cat.");
    }

    public static void main(String[] args) {
        Cat myCat = new Cat();
        Animal myAnimal = myCat;
        Animal.testClassMethod();
        myAnimal.testInstanceMethod();
    }
}

The Cat class overrides the instance method in Animal and hides the class method in Animal. The main method in this class creates an instance of Cat and calls testClassMethod() on the class and testInstanceMethod() on the instance.

The output from this program is as follows:

output:
The class method in Animal.
The instance method in Cat.

As promised, the version of the hidden method that gets invoked is the one in the superclass, and the version of the overridden method that gets invoked is the one in the subclass.

Advantages method overriding:
  • Method Overriding is used to provide specific implementation of a method that is already provided by its super class.
  • Method Overriding is used for Runtime Polymorphism

Rules for method overriding:

  • The argument list should be exactly the same as that of the overridden method.
  • The return type should be the same or a subtype of the return type declared in the original overridden method in the super class.
  • The access level cannot be more restrictive than the overridden method's access level. For example: if the super class method is declared public then the overridding method in the sub class cannot be either private or public. However the access level can be less restrictive than the overridden method's access level.
  • Instance methods can be overridden only if they are inherited by the subclass.
  • A method declared final cannot be overridden.
  • A method declared static cannot be overridden but can be re-declared.
  • If a method cannot be inherited then it cannot be overridden.
  • A subclass within the same package as the instance's superclass can override any superclass method that is not declared private or final.
  • A subclass in a different package can only override the non-final methods declared public or protected.
  • An overriding method can throw any uncheck exceptions, regardless of whether the overridden method throws exceptions or not. However the overriding method should not throw checked exceptions that are new or broader than the ones declared by the overridden method. The overriding method can throw narrower or fewer exceptions than the overridden method.
  • Constructors cannot be overridden.

Modifiers

The access specifier for an overriding method can allow more, but not less, access than the overridden method. For example, a protected instance method in the superclass can be made public, but not private, in the subclass.
You will get a compile-time error if you attempt to change an instance method in the superclass to a class method in the subclass, and vice versa.

Summary

The following table summarizes what happens when you define a method with the same signature as a method in a superclass.
Defining a Method with the Same Signature as a Superclass's Method
Superclass Instance Method Superclass Static Method
Subclass Instance Method Overrides Generates a compile-time error
Subclass Static Method Generates a compile-time error Hides

Note: In a subclass, you can overload the methods inherited from the superclass. Such overloaded methods neither hide nor override the superclass methods—they are new methods, unique to the subclass. 

Difference between method Overloading and Method Overriding.
There are three basic differences between the method overloading and method overriding. They are as follows:


Method Overloading Method Overriding
1) Method overloading is used to increase the readability of the program.Method overriding is used to provide the specific implementation of the method that is already provided by its super class.
2) method overlaoding is performed within a class.Method overriding occurs in two classes that have IS-A relationship.
3) In case of method overloading parameter must be different.In case of method overriding parameter must be same.



<<Previous <<   || Index ||   >>Next >>


Java Inheritance

In this section, you will learn about the inheritance with an example and its description.

 Different kinds of objects often have a certain amount in common with each other. Mountain bikes, road bikes, and tandem bikes, for example, all share the characteristics of bicycles (current speed, current pedal cadence, current gear). Yet each also defines additional features that make them different: tandem bicycles have two seats and two sets of handlebars; road bikes have drop handlebars; some mountain bikes have an additional chain ring, giving them a lower gear ratio.

Object-oriented programming allows classes to inherit commonly used state and behavior from other classes. In this example, Bicycle now becomes the superclass of MountainBike, RoadBike, and TandemBike. In the Java programming language, each class is allowed to have one direct superclass, and each superclass has the potential for an unlimited number of subclasses:
Java Inheritance
                                    A hierarchy of bicycle classes.

 The syntax for creating a subclass is simple. At the beginning of your class declaration, use the extends keyword, followed by the name of the class to inherit from:

class MountainBike extends Bicycle {

    // new fields and methods defining 
    // a mountain bike would go here

}

This gives MountainBike all the same fields and methods as Bicycle, yet allows its code to focus exclusively on the features that make it unique. This makes code for your subclasses easy to read. However, you must take care to properly document the state and behavior that each superclass defines, since that code will not appear in the source file of each subclass.

When we talk about inheritance the most commonly used keyword would be extends and implements. These words would determine whether one object IS-A type of another. By using these keywords we can make one object acquire the properties of another object.

IS-A Relationship:
IS-A is a way of saying : This object is a type of that object. Let us see how the extends keyword is used to achieve inheritance.

public class Bicycle {
}

class MountainBike extends Bicycle {

    // new fields and methods defining 
    // a mountain bike would go here

}

public class RoadBike extends Bicycle {

    // new fields and methods defining 
    // a RoadBike would go here
}

public class TandemBike extends Bicycle {

    // new fields and methods defining 
    // a TandemBike bike would go here
}


Now based on the above example, In Object Oriented terms following are true:

  • Bicycle is the superclass of MountainBike class.
  • Bicycle  is the superclass of RoadBike class.
  • RoadBike and MountainBike are sub classes of Bicycle class.
  • HondaShineBike is the subclass of both RoadBike and Bicycle  classes.
Now if we consider the IS-A relationship we can say:

  • MountainBike IS-A Bicycle
  • RoadBike IS-A Bicycle
  • HondaShineBike IS-A RoadBike
  • Hence : HondaShineBike IS-A Bicycle as well
With use of the extends keyword the subclasses will be able to inherit all the properties of the superclass except for the private properties of the superclass.
Example:
public class Dog extends Mammal{

   public static void main(String args[]){

      Bicycle bicycle = new Bicycle();
      RoadBike roadBike = new RoadBike();
      HondaShine myBike = new HondaShine();

      System.out.println(roadBike instanceof Bicycle);
      System.out.println(myBike instanceof RoadBike);
      System.out.println(myBike instanceof Bicycle);
   }
}

This would produce following result:
Output:
true
true
true

Since we have a good understanding of the extends keyword let us look into how the implements keyword is used to get the IS-A relationship.

The implements keyword is used by classes by inherit from interfaces. Interfaces can never be extended by the classes.
Example:
public interface Bicycle{

}

public class RoadBike implements Bicycle{

}

public class HondaShine extends RoadBike{

}

The instanceof Keyword:

Let us use the instanceof operator to check determine whether RoadBike is actually a Bicycle, and HondaShine is actually an Bicycle
public interface Bicycle{

}

public class RoadBike implements Bicycle{

}

public class HondaShine extends RoadBike{
   public static void main(String args[]){

      RoadBike roadBike = new RoadBike();
      HondaShine myBike = new HondaShine();

      System.out.println(roadBike instanceof Bicycle);
      System.out.println(myBike instanceof RoadBike);
      System.out.println(myBike instanceof Bicycle);
   }
}

This would produce following result:
output:
true
true
true

HAS-A relationship:

These relationships are mainly based on the usage. This determines whether a certain class HAS-A certain thing. This relationship helps to reduce duplication of code as well as bugs.

Lets us look into an example:
public class Vehicle{}
public class Speed{}
public class Van extends Vehicle{
 private Speed sp;
} 
This shows that class Van HAS-A Speed. By having a separate class for Speed we do not have to put the entire code that belongs to speed inside the Van class., which makes it possible to reuse the Speed class in multiple applications.

In Object Oriented feature the users do not need to bother about which object is doing the real work. To achieve this, the Van class hides the implementation details from the users of the Van class. So basically what happens is the users would ask the Van class to do a certain action and the Van class will either do the work by itself or ask another class to perform the action.

Note: A very important fact to remember is that Java only supports only single inheritance. This means that a class cannot extend more than one class. Therefore following is illegal:
public class HondaShine extends RoadBike, Bicycle{

}

Type of Inheritances:
1. Simple Inheritance
When a subclass is derived simply from it's parent class then this mechanism is known as simple inheritance. In case of simple inheritance there is only a sub class and it's parent class. It is also called single inheritance or one level inheritance.
class A {
  int x;
  int y;
  int get(int p, int q){
    x=p; 
    y=q; 
    return(0);
  }
  void Show(){
   System.out.println(x);
  }
}

class B extends A{
  public static void main(String args[]){
  A a = new A();
  a.get(5,6);
  a.Show();
  }
  void display(){
  System.out.println("B");
  }
}

2. Multilevel Inheritance
It is the enhancement of the concept of inheritance. When a subclass is derived from a derived class then this mechanism is known as the multilevel inheritance. The derived class is called the subclass or child class for it's parent class and this parent class works as the child class for it's just above ( parent ) class. Multilevel inheritance can go up to any number of level.
class A {
  int x;
  int y;
  int get(int p, int q){
  x=p; y=q; return(0);
  }
  void Show(){
  System.out.println(x);
  }
}
class B extends A{
  void Showb(){
  System.out.println("B");
  }
}

class C extends B{
  void display(){
  System.out.println("C");
  }
  public static void main(String args[]){
  A a = new A();
  a.get(5,6);
  a.Show();
  }
}

3. Multiple Inheritance
Note: Java does not support multiple Inheritance.

The mechanism of inheriting the features of more than one base class into a single class is known as multiple inheritance. Java does not support multiple inheritance but the multiple inheritance can be achieved by using the interface.

In Java Multiple Inheritance can be achieved through use of Interfaces by implementing more than one interfaces in a class.

super keyword

The super is java keyword. As the name suggest super is used to access the members of the super class.It is used for two purposes in java.
The first use of keyword super is to access the hidden data variables of the super class hidden by the sub class.

e.g. Suppose class A is the super class that has two instance variables as int a and float b. class B is the subclass that also contains its own data members named a and b. then we can access the super class (class A) variables a and b inside the subclass class B just by calling the following command.

super.member;

Here member can either be an instance variable or a method. This form of super most useful to handle situations where the local members of a subclass hides the members of a super class having the same name. The following example clarify all the confusions.

class A{
  int a;
  float b;
  void Show(){
  System.out.println("b in super class:  " + b);
  }

}

class B extends A{
  int a; 
  float b;
  B( int p, float q){
  a = p;
  super.b = q;
  }
  void Show(){
  super.Show();
  System.out.println("b in super class:  " + super.b);
  System.out.println("a in sub class:  " + a);
  }

  public static void main(String[] args){
  B subobj = new B(1, 5);
  subobj.Show();
  }
}
Output:
C:\>java B
b in super class: 5.0
b in super class: 5.0
a in sub class: 1

Use of super to call super class constructor:
The second use of the keyword super in java is to call super class constructor in the subclass. This functionality can be achieved just by using the following command.

super(param-list);


Here parameter list is the list of the parameter requires by the constructor in the super class. super must be the first statement executed inside a super class constructor. If we want to call the default constructor then we pass the empty parameter list. The following program illustrates the use of the super keyword to call a super class constructor. 

class A{
  int a;
  int b;
  int c;
  A(int p, int q, int r){
  a=p;
  b=q;
  c=r;
  }
}
  
  class B extends A{
  int d;
  B(int l, int m, int n, int o){
  super(l,m,n);
  d=o;
  }
  void Show(){
  System.out.println("a = " + a);
  System.out.println("b = " + b);
  System.out.println("c = " + c);
  System.out.println("d = " + d);
  }

  public static void main(String args[]){
  B b = new B(4,3,8,7);
  b.Show();
  }
  }

Output:
C:\>java B
a = 4
b = 3
c = 8
d = 7

What is not possible using java class Inheritance?
1. Private members of the superclass are not inherited by the subclass and can only be indirectly accessed.
2. Members that have default accessibility in the superclass are also not inherited by subclasses in other packages, as these members are only accessible by their simple names in subclasses within the same package as the superclass.
3. Since constructors and initializer blocks are not members of a class, they are not inherited by a subclass.
4. A subclass can extend only one superclass



<<Previous <<   || Index ||   >>Next >>


Constructors in Java

A java constructor has the same name as the name of the class to which it belongs. Constructor’s syntax does not include a return type, since constructors never return a value.

Constructors may include parameters of various types. When the constructor is invoked using the new operator, the types must match those that are specified in the constructor definition.

Java provides a default constructor which takes no arguments and performs no special actions or initializations, when no explicit constructors are provided.

The only action taken by the implicit default constructor is to call the superclass constructor using the super() call. Constructor arguments provide you with a way to provide parameters for the initialization of an object.

Below is an example of a Cuboid class containing 2 constructors. (one default and one parameterized constructor).
public class Cuboid {

 int length;
 int breadth;
 int height;
 public int getVolume() {
  return (length * breadth * height);
 }
 Cuboid () {
  length = 10;
  breadth = 10;
  height = 10;
 }
 Cuboid (int l, int b, int h) {
  length = l;
  breadth = b;
  height = h;
 }
 public static void main(String[] args) {
  Cuboid cubeObj1, cubeObj2;
  cubeObj1 = new Cuboid ();
  cubeObj2 = new Cuboid (10, 20, 30);
  System.out.println("Volume of Cuboid 1 is : " + cubeObj1.getVolume());
  System.out.println("Volume of Cuboid 1 is : " + cubeObj2.getVolume());
 }
}

output:
Volume of Cuboid 1 is : 1000
Volume of Cuboid 1 is : 6000

Note: If a class defines an explicit constructor, it no longer has a default constructor to set the state of the objects. If such a class requires a default constructor, its implementation must be provided. Any attempt to call the default constructor will be a compile time error if an explicit default constructor is not provided in such a case.

Java Overloaded Constructors:


Like methods, constructors can also be overloaded. Since the constructors in a class all have the same name as the class, />their signatures are differentiated by their parameter lists. The above example shows that the Cube1 constructor is overloaded one being the default constructor and the other being a parameterized constructor.

It is possible to use this() construct, to implement local chaining of constructors in a class. The this() call in a constructorinvokes the an other constructor with the corresponding parameter list within the same class. Calling the default constructor to create a Cube object results in the second and third parameterized constructors being called as well. Java requires that any this() call must occur as the first statement in a constructor.

Below is an example of a cube class containing 3 constructors which demostrates the this() method in Constructors context

public class Cuboid2 {

 int length;
 int breadth;
 int height;
 public int getVolume() {
  return (length * breadth * height);
 }
 Cuboid2 () {
  this(10, 10);
  System.out.println("Finished with Default Constructor");
 }
 Cuboid2 (int l, int b) {
  this(l, b, 10);
  System.out.println("Finished with Parameterized Constructor having 2 params");
 }
 Cuboid2 (int l, int b, int h) {
  length = l;
  breadth = b;
  height = h;
  System.out.println("Finished with Parameterized Constructor having 3 params");
 }
 public static void main(String[] args) {
  Cuboid2 cubeObj1, cubeObj2;
  cubeObj1 = new Cuboid2 ();
  cubeObj2 = new Cuboid2 (10, 20, 30);
  System.out.println("Volume of Cuboid2 1 is : " + cubeObj1.getVolume());
  System.out.println("Volume of Cuboid2 2 is : " + cubeObj2.getVolume());
 }
}


output:
Finished with Parameterized Constructor having 3 params
Finished with Parameterized Constructor having 2 params
Finished with Default Constructor
Finished with Parameterized Constructor having 3 params
Volume of Cube1 is : 1000
Volume of Cube2 is : 6000

Constructor Chaining:

Every constructor calls its superclass constructor. An implied super() is therefore included in each constructor which does not include either the this() function or an explicit super() call as its first statement. The super() statement invokes a constructor of the super class.
The implicit super() can be replaced by an explicit super(). The super statement must be the first statement of the constructor.
The explicit super allows parameter values to be passed to the constructor of its superclass and must have matching parameter types A super() call in the constructor of a subclass will result in the call of the relevant constructor from the superclass, based on the signature of the call. This is called constructor chaining.

Below is an example of a class demonstrating constructor chaining using super() method.

class Cube {

 int length;
 int breadth;
 int height;
 public int getVolume() {
  return (length * breadth * height);
 }
 Cube() {
  this(10, 10);
  System.out.println("Finished with Default Constructor of Cube");
 }
 Cube(int l, int b) {
  this(l, b, 10);
  System.out.println("Finished with Parameterized Constructor having
         2 params of Cube");
 }
 Cube(int l, int b, int h) {
  length = l;
  breadth = b;
  height = h;
  System.out.println("Finished with Parameterized Constructor having
         3 params of Cube");
 }
}

public class SpecialCube extends Cube {

 int weight;
 SpecialCube() {
  super();
  weight = 10;
 }
 SpecialCube(int l, int b) {
  this(l, b, 10);
  System.out.println("Finished with Parameterized Constructor having
         2 params of SpecialCube");
 }
 SpecialCube(int l, int b, int h) {
  super(l, b, h);
  weight = 20;
  System.out.println("Finished with Parameterized Constructor having
         3 params of SpecialCube");
 }
 public static void main(String[] args) {
  SpecialCube specialObj1 = new SpecialCube();
  SpecialCube specialObj2 = new SpecialCube(10, 20);
  System.out.println("Volume of SpecialCube1 is : "
    + specialObj1.getVolume());
  System.out.println("Weight of SpecialCube1 is : "
    + specialObj1.weight);
  System.out.println("Volume of SpecialCube2 is : "
    + specialObj2.getVolume());
  System.out.println("Weight of SpecialCube2 is : "
    + specialObj2.weight);
 }
}

Output:

Finished with Parameterized Constructor having 3 params of SpecialCube
Finished with Parameterized Constructor having 2 params of SpecialCube
Volume of SpecialCube1 is : 1000
Weight of SpecialCube1 is : 10
Volume of SpecialCube2 is : 2000
Weight of SpecialCube2 is : 20


The super() construct as with this() construct: if used, must occur as the first statement in a constructor, and it can only be used in a constructor declaration. This implies that this() and super() calls cannot both occur in the same constructor. Just as the this() construct leads to chaining of constructors in the same class, the super() construct leads to chaining of subclass constructors to superclass constructors.
if a constructor has neither a this() nor a super() construct as its first statement, then a super() call to the default constructor in the superclass is inserted.

Note: If a class only defines non-default constructors, then its subclasses will not include an implicit super() call. This will be flagged as a compile-time error. The subclasses must then explicitly call a superclass constructor, using the super() construct with the right arguments to match the appropriate constructor of the superclass.

Below is an example of a class demonstrating constructor chaining using explicit super() call.
class Cube {

 int length;
 int breadth;
 int height;
 public int getVolume() {
  return (length * breadth * height);
 }
 Cube(int l, int b, int h) {
  length = l;
  breadth = b;
  height = h;
  System.out.println("Finished with Parameterized Constructor having
        3 params of Cube");
 }
}

public class SpecialCube1 extends Cube {

 int weight;
 SpecialCube1() {
  super(10, 20, 30); //Will Give a Compilation Error without this line
  weight = 10;
 }
 public static void main(String[] args) {
  SpecialCube1 specialObj1 = new SpecialCube1();
  System.out.println("Volume of SpecialCube1 is : "+ specialObj1.getVolume());
 }
}

Output

Finished with Parameterized Constructor having 3 params of Cube
Volume of SpecialCube1 is : 6000


<<Previous <<   || Index ||   >>Next >>


Methods in Java

A Java method is a collection of statements that are grouped together to perform an operation. When you call the System.out.println method, for example, the system actually executes several statements in order to display a message on the console.

Now you will learn how to create your own methods with or without return values, invoke a method with or without parameters, overload methods using the same names, and apply method abstraction in the program design.

Creating a Method:

In general, a method has the following syntax:

modifier returnValueType methodName(list of parameters) {
  // Method body;
}
A method definition consists of a method header and a method body. Here are all the parts of a method:
  • Modifiers: The modifier, which is optional, tells the compiler how to call the method. This defines the access type of the method.
  • Return Type: A method may return a value. The returnValueType is the data type of the value the method returns. Some methods perform the desired operations without returning a value. In this case, the returnValueType is the keyword void.
  • Method Name: This is the actual name of the method. The method name and the parameter list together constitute the method signature.
  • Parameters: A parameter is like a placeholder. When a method is invoked, you pass a value to the parameter. This value is referred to as actual parameter or argument. The parameter list refers to the type, order, and number of the parameters of a method. Parameters are optional; that is, a method may contain no parameters.
  • Method Body: The method body contains a collection of statements that define what the method does.
Methods in Java

Note: In certain other languages, methods are referred to as procedures and functions. A method with a nonvoid return value type is called a function; a method with a void return value type is called a procedure.

Example:

Here is the source code of the above defined method called max(). This method takes two parameters num1 and num2 and returns the maximum between the two:
/** Return the max between two numbers */
public static int max(int num1, int num2) {
   int result;
   if (num1 > num2)
      result = num1;
   else
      result = num2;

   return result; 
}

Calling a Method:

In creating a method, you give a definition of what the method is to do. To use a method, you have to call or invoke it. There are two ways to call a method; the choice is based on whether the method returns a value or not.

When a program calls a method, program control is transferred to the called method. A called method returns control to the caller when its return statement is executed or when its method-ending closing brace is reached.

If the method returns a value, a call to the method is usually treated as a value. For example:
int larger = max(30, 40);

If the method returns void, a call to the method must be a statement. For example, the method println returns void. The following call is a statement:
System.out.println("Welcome to Java!");

Example:

Following is the example to demonstrate how to define a method and how to call it:
public class TestMax {
   /** Main method */
   public static void main(String[] args) {
      int i = 5;
      int j = 2;
      int k = max(i, j);
      System.out.println("The maximum between " + i +
                    " and " + j + " is " + k);
   }

   /** Return the max between two numbers */
   public static int max(int num1, int num2) {
      int result;
      if (num1 > num2)
         result = num1;
      else
         result = num2;

      return result; 
   }
}

This would produce following result:
output:
The maximum between 5 and 2 is 5

This program contains the main method and the max method. The main method is just like any other method except that it is invoked by the JVM.

The main method's header is always the same, like the one in this example, with the modifiers public and static, return value type void, method name main, and a parameter of the String[] type. String[] indicates that the parameter is an array of String.

The void Keyword:

This section shows how to declare and invoke a void method. Following example gives a program that declares a method named printGrade and invokes it to print the grade for a given score.

Example:
public class TestVoidMethod {

   public static void main(String[] args) {
      printGrade(78.5);
   }

   public static void printGrade(double score) {
      if (score >= 90.0) {
         System.out.println('A');
      }
      else if (score >= 80.0) {
         System.out.println('B');
      }
      else if (score >= 70.0) {
         System.out.println('C');
      }
      else if (score >= 60.0) {
         System.out.println('D');
      }
      else {
         System.out.println('F');
      }
   }
}

This would produce following result:
output:
C

Here the printGrade method is a void method. It does not return any value. A call to a void method must be a statement. So, it is invoked as a statement in line 3 in the main method. This statement is like any Java statement terminated with a semicolon.

Passing Parameters by Values:

When calling a method, you need to provide arguments, which must be given in the same order as their respective parameters in the method specification. This is known as parameter order association.

For example, the following method prints a message n times:
public static void nPrintln(String message, int n) {
  for (int i = 0; i < n; i++)
    System.out.println(message);
}

Here, you can use nPrintln("Hello", 3) to print "Hello" three times. The nPrintln("Hello", 3) statement passes the actual string parameter, "Hello", to the parameter, message; passes 3 to n; and prints "Hello" three times. However, the statement nPrintln(3, "Hello") would be wrong. When you invoke a method with a parameter, the value of the argument is passed to the parameter. This is referred to as pass-by-value. If the argument is a variable rather than a literal value, the value of the variable is passed to the parameter. The variable is not affected, regardless of the changes made to the parameter inside the method. For simplicity, Java programmers often say passing an argument x to a parameter y, which actually means passing the value of x to y.  

Example: 

Following is a program that demonstrates the effect of passing by value. The program creates a method for swapping two variables. The swap method is invoked by passing two arguments. Interestingly, the values of the arguments are not changed after the method is invoked.
public class TestPassByValue {

   public static void main(String[] args) {
      int num1 = 1;
      int num2 = 2;

      System.out.println("Before swap method, num1 is " +
                          num1 + " and num2 is " + num2);

      // Invoke the swap method
      swap(num1, num2);
      System.out.println("After swap method, num1 is " +
                         num1 + " and num2 is " + num2);
   }
   /** Method to swap two variables */
   public static void swap(int n1, int n2) {
      System.out.println("\tInside the swap method");
      System.out.println("\t\tBefore swapping n1 is " + n1
                           + " n2 is " + n2);
      // Swap n1 with n2
      int temp = n1;
      n1 = n2;
      n2 = temp;

      System.out.println("\t\tAfter swapping n1 is " + n1
                           + " n2 is " + n2);
   }
}
This would produce following result:
 
output: Before swap method, num1 is 1 and num2 is 2 Inside the swap method Before swapping n1 is 1 n2 is 2 After swapping n1 is 2 n2 is 1 After swap method, num1 is 1 and num2 is 2

Overloading Methods: 
The max method that was used earlier works only with the int data type. But what if you need to find which of two floating-point numbers has the maximum value? The solution is to create another method with the same name but different parameters, as shown in the following code: 

public static double max(double num1, double num2) {
  if (num1 > num2)
    return num1;
  else
    return num2;
}
If you call max with int parameters, the max method that expects int parameters will be invoked; if you call max with double parameters, the max method that expects double parameters will be invoked. This is referred to as method overloading; that is, two methods have the same name but different parameter lists within one class. The Java compiler determines which method is used based on the method signature. Overloading methods can make programs clearer and more readable. Methods that perform closely related tasks should be given the same name. Overloaded methods must have different parameter lists. You cannot overload methods based on different modifiers or return types. Sometimes there are two or more possible matches for an invocation of a method due to similar method signature, so the compiler cannot determine the most specific match. This is referred to as ambiguous invocation.

 The Scope of Variables:
 
The scope of a variable is the part of the program where the variable can be referenced. A variable defined inside a method is referred to as a local variable.

The scope of a local variable starts from its declaration and continues to the end of the block that contains the variable. A local variable must be declared before it can be used.

A parameter is actually a local variable. The scope of a method parameter covers the entire method.

A variable declared in the initial action part of a for loop header has its scope in the entire loop. But a variable declared inside a for loop body has its scope limited in the loop body from its declaration to the end of the block that contains the variable as shown below:

java variable scopes

You can declare a local variable with the same name multiple times in different non-nesting blocks in a method, but you cannot declare a local variable twice in nested blocks.

Using Command-Line Arguments:

Sometimes you will want to pass information into a program when you run it. This is accomplished by passing command-line arguments to main( ).

A command-line argument is the information that directly follows the program's name on the command line when it is executed. To access the command-line arguments inside a Java program is quite easy.they are stored as strings in the String array passed to main( ).

Example:

The following program displays all of the command-line arguments that it is called with:
public class CommandLine {

   public static void main(String args[]){ 
      for(int i=0; i<args.length; i++){
         System.out.println("args[" + i + "]: " +
                                           args[i]);
      }
   }
}

Try executing this program, as shown here:
java CommandLine this is a command line 200 -100

This would produce following result:
output:
args[0]: this
args[1]: is
args[2]: a
args[3]: command
args[4]: line
args[5]: 200
args[6]: -100

The Constructors:

A constructor initializes an object when it is created. It has the same name as its class and is syntactically similar to a method. However, constructors have no explicit return type.

Typically, you will use a constructor to give initial values to the instance variables defined by the class, or to perform any other startup procedures required to create a fully formed object.

All classes have constructors, whether you define one or not, because Java automatically provides a default constructor that initializes all member variables to zero. However, once you define your own constructor, the default constructor is no longer used.
Example:

Here is a simple example that uses a constructor:
// A simple constructor.
class MyClass {
   int x;
   
   // Following is the constructor
   MyClass() {
      x = 10;
   }
}
You would call constructor to initialize objects as follows:
public class ConsDemo {

   public static void main(String args[]) {
      MyClass t1 = new MyClass();
      MyClass t2 = new MyClass();
      System.out.println(t1.x + " " + t2.x);
   }
}

Most often you will need a constructor that accepts one or more parameters. Parameters are added to a constructor in the same way that they are added to a method:just declare them inside the parentheses after the constructor's name.

Here is a simple example that uses a constructor:
// A simple constructor.
class MyClass {
   int x;
   
   // Following is the constructor
   MyClass(int i ) {
      x = i;
   }
}
You would call constructor to initialize objects as follows:
public class ConsDemo {

   public static void main(String args[]) {
      MyClass t1 = new MyClass( 10 );
      MyClass t2 = new MyClass( 20 );
      System.out.println(t1.x + " " + t2.x);
   }
}

This would produce following result:
output:
10 20

Variable Arguments(var-args):


JDK 1.5 enables you to pass a variable number of arguments of the same type to a method. The parameter in the method is declared as follows:
typeName... parameterName
In the method declaration, you specify the type followed by an ellipsis (...) Only one variable-length parameter may be specified in a method, and this parameter must be the last parameter. Any regular parameters must precede it.
Example:
public class VarargsDemo {

   public static void main(String args[]) {
      // Call method with variable args  
   printMax(34, 3, 3, 2, 56.5);
      printMax(new double[]{1, 2, 3});
   }

   public static void printMax( double... numbers) {
   if (numbers.length == 0) {
      System.out.println("No argument passed");
      return;
   }

   double result = numbers[0];

   for (int i = 1; i <  numbers.length; i++)
      if (numbers[i] >  result)
      result = numbers[i];
      System.out.println("The max value is " + result);
   }
}

This would produce following result:
output:
The max value is 56.5
The max value is 3.0



<<Previous <<   || Index ||   >>Next >>



Java - How to use Singleton Class ?

In this tutorial we will discussing about the singleton class in the java based on the singleton pattern. Singleton pattern is a design solution where an application wants to have one and only one instance of any class, in all possible scenarios without any exceptional condition. It has been debated long enough in java community regarding possible approaches to make any class singleton. Still, you will find people not satisfied with any solution you give. They can not be overruled either. In this post, we will discuss some good approaches and will work towards our best possible effort.

The Singleton's purpose is to control object creation, limiting the number to one but allowing the flexibility to create more objects if the situation changes.

Since there is only one Singleton instance, any instance fields of a Singleton will occur only once per class, just like static fields. Singletons often control access to resources such as database connections or sockets.

For example, if you have a license for only one connection for your database or your JDBC driver has trouble with multithreading, the Singleton makes sure that only one connection is made or that only one thread can access the connection at a time.
Implementing Singleton Pattern:

The class’s default constructor is made private, which prevents the direct instantiation of the object by others (Other Classes). A static modifier is applied to the instance method that returns the object as it then makes this method a class level method that can be accessed without creating an object.

Eager initialization:

This is a design pattern where an instance of a class is created much before it is actually required. Mostly it is done on system start up. In singleton pattern, it refers to create the singleton instance irrespective of whether any other class actually asked for its instance or not.

The private field can be assigned from within a static initializer block or, more simply, using an initializer. The getInstance( ) method (which must be public) then simply returns this instance:

public class EagerSingleton {
    private static volatile EagerSingleton instance = new EagerSingleton();
 
    // private constructor
    private EagerSingleton() {
    }
 
    public synchronized static EagerSingleton getInstance() {
        if (instance == null) {
            instance = new EagerSingleton();
        }
        return instance;
    }
}

Above method works fine, but has one performance drawback. The getInstance() method is synchronized and each call will require extra locking/unlocking steps which are necessary only for first time, and never there after.

Lets solve above problem in next method.

Lazy initialization:


In computer programming, lazy initialization is the tactic of delaying the creation of an object, the calculation of a value, or some other expensive process until the first time it is needed. In singleton pattern, it restricts the creation of instance until requested first time. Lets see in code:

public final class LazySingleton {
    private static volatile LazySingleton instance = null;
 
    // private constructor
    private LazySingleton() {
    }
 
    public static LazySingleton getInstance() {
        if (instance == null) {
            synchronized (LazySingleton.class) {
                instance = new LazySingleton();
            }
        }
        return instance;
    }
}

On first invocation, above method will check if instance is already created using instance variable. If there is no instance i.e. instance is null, it will create an instance and will return its reference. If instance is already created, it will simply return the reference of instance.

But, this method also has its own drawbacks. Lets see how. Suppose there are two threads T1 and T2. Both comes to create instance and execute "instance==null", now both threads have identified instance variable to null thus assume they must create an instance. They sequentially goes to synchronized block and create the instances. At the end, we have two instances in our application.

This error can be solved using double-checked locking. This principle tells us to recheck the instance variable again in synchronized block in given below way:

public class EagerSingleton {
    private static volatile EagerSingleton instance = null;
 
    // private constructor
    private EagerSingleton() {
    }
 
    public static EagerSingleton getInstance() {
        if (instance == null) {
            synchronized (EagerSingleton.class) {
                // Double check
                if (instance == null) {
                    instance = new EagerSingleton();
                }
            }
        }
        return instance;
    }
}

Above code is the correct implementation of singleton pattern.

Please ensure to use “volatile” keyword with instance variable otherwise you can run into out of order write error scenario, where reference of instance is returned before actually the object is constructed i.e. JVM has only allocated the memory and constructor code is still not executed. In this case, your other thread, which refer to uninitialized object may throw null pointer exception and can even crash the whole application.

Static block initialization:

If you have little idea about class loading sequence, you can connect to the fact that static blocks are executed during the loading of class and even before the constructor is called. We can use this feature in our singleton pattern also like this:
public class StaticBlockSingleton {
    private static final StaticBlockSingleton INSTANCE;
 
    static {
        try {
            INSTANCE = new StaticBlockSingleton();
        } catch (Exception e) {
            throw new RuntimeException("Uffff, i was not expecting this!", e);
        }
    }
 
    public static StaticBlockSingleton getInstance() {
        return INSTANCE;
    }
 
    private StaticBlockSingleton() {
        // ...
    }
}

Above code has one drawback. Suppose there are 5 static fields in class and application code needs to access only 2 or 3, for which instance creation is not required at all. So, if we use this static initialization. we will have one instance created though we require it or not.

Next section will overcome this problem.

Bill pugh solution:

Bill pugh was main force behind java memory model changes. His principle “Initialization-on-demand holder idiom” also uses static block but in different way. It suggest to use static inner class.

public class BillPughSingleton {
    private BillPughSingleton() {
    }
 
    private static class LazyHolder {
        private static final BillPughSingleton INSTANCE = new BillPughSingleton();
    }
 
    public static BillPughSingletongetInstance() {
        return LazyHolder.INSTANCE;
    }
}

As you can see, until we need an instance, the LazyHolder class will not be initialized until required and you can still use other static members of BillPughSingleton class


Java - String valueOf() Method

Description:

This method has followings variants which depends on the passed parameters. This method returns the string representation of the passed argument.


  • valueOf(boolean b): Returns the string representation of the boolean argument.
  • valueOf(char c) : Returns the string representation of the char argument.
  • valueOf(char[] data) : Returns the string representation of the char array argument.
  • valueOf(char[] data, int offset, int count) : Returns the string representation of a specific subarray of the char array argument.
  • valueOf(double d) : Returns the string representation of the double argument.
  • valueOf(float f) : Returns the string representation of the float argument.
  • valueOf(int i) : Returns the string representation of the int argument.
  • valueOf(long l) : Returns the string representation of the long argument.
  • valueOf(Object obj) : Returns the string representation of the Object argument.

Syntax:

Here is the syntax of this method:

static String valueOf(boolean b) 

or 

static String valueOf(char c) 

or

static String valueOf(char[] data) 

or

static String valueOf(char[] data, int offset, int count) 

or

static String valueOf(double d) 

or

static String valueOf(float f) 

or

static String valueOf(int i)

or

static String valueOf(long l)

or

static String valueOf(Object obj) 

Parameters:

Here is the detail of parameters:


  • See the description.

Return Value :


  • This method returns the string representation.

Example:

import java.io.*;

public class Test{
   public static void main(String args[]){
      double d = 102939939.939;
      boolean b = true;
      long l = 1232874;
      char[] arr = {'a', 'b', 'c', 'd', 'e', 'f','g' };

      System.out.println("Return Value : " + String.valueOf(d) );
      System.out.println("Return Value : " + String.valueOf(b) );
      System.out.println("Return Value : " + String.valueOf(l) );
      System.out.println("Return Value : " + String.valueOf(arr) );
   }
}

This produces following result:

output:
Return Value : 1.02939939939E8
Return Value : true
Return Value : 1232874
Return Value : abcdefg



<<Previous <<   || Index ||   >>Next >>


Java - String trim() Method

Description:

This method returns a copy of the string, with leading and trailing whitespace omitted.

Syntax:

Here is the syntax of this method:

public String trim()

Parameters:

Here is the detail of parameters:


  • NA

Return Value:


  • It returns a copy of this string with leading and trailing white space removed, or this string if it has no leading or trailing white space.

Example:

import java.io.*;

public class Test{
   public static void main(String args[]){
      String Str = new String("   Welcome to Dineshonjava.com   ");

      System.out.print("Return Value :" );
      System.out.println(Str.trim() );
   }
}

This produces following result:

output:
Return Value :Welcome to Dineshonjava.com


<<Previous <<   || Index ||   >>Next >>



Java - String toUpperCase() Method

Description:

This method has two variants. First variant converts all of the characters in this String to upper case using the rules of the given Locale. This is equivalent to calling toUpperCase(Locale.getDefault()).

Second variant take locale as an argument to be used while converting into upper case.

Syntax:

Here is the syntax of this method:

public String toUpperCase()

or

public String toUpperCase(Locale locale)

Parameters:

Here is the detail of parameters:


  • NA

Return Value:


  • It returns the String, converted to uppercase.

Example:

import java.io.*;

public class Test{
   public static void main(String args[]){
      String Str = new String("Welcome to Dineshonjava.com");

      System.out.print("Return Value :" );
      System.out.println(Str.toUpperCase() );
   }
}

This produces following result:

output:
Return Value :WELCOME TO DINESHONJAVA.COM



<<Previous <<   || Index ||   >>Next >>