Author: saqibkhan

  • Adapter Pattern

    Adapter pattern works as a bridge between two incompatible interfaces. This type of design pattern comes under structural pattern as this pattern combines the capability of two independent interfaces.

    This pattern involves a single class which is responsible to join functionalities of independent or incompatible interfaces. A real life example could be a case of card reader which acts as an adapter between memory card and a laptop. You plugin the memory card into card reader and card reader into the laptop so that memory card can be read via laptop.

    We are demonstrating use of Adapter pattern via following example in which an audio player device can play mp3 files only and wants to use an advanced audio player capable of playing vlc and mp4 files.

    Implementation

    We have a MediaPlayer interface and a concrete class AudioPlayer implementing the MediaPlayer interface. AudioPlayer can play mp3 format audio files by default.

    We are having another interface AdvancedMediaPlayer and concrete classes implementing the AdvancedMediaPlayer interface. These classes can play vlc and mp4 format files.

    We want to make AudioPlayer to play other formats as well. To attain this, we have created an adapter class MediaAdapter which implements the MediaPlayer interface and uses AdvancedMediaPlayer objects to play the required format.

    AudioPlayer uses the adapter class MediaAdapter passing it the desired audio type without knowing the actual class which can play the desired format. AdapterPatternDemo, our demo class will use AudioPlayer class to play various formats.

    Adapter Pattern UML Diagram

    Step 1

    Create interfaces for Media Player and Advanced Media Player.

    MediaPlayer.java

    public interface MediaPlayer {
       public void play(String audioType, String fileName);
    }

    AdvancedMediaPlayer.java

    public interface AdvancedMediaPlayer {	
       public void playVlc(String fileName);
       public void playMp4(String fileName);
    }

    Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

    Step 2

    Create concrete classes implementing the AdvancedMediaPlayer interface.

    VlcPlayer.java

    public class VlcPlayer implements AdvancedMediaPlayer{
       @Override
       public void playVlc(String fileName) {
    
      System.out.println("Playing vlc file. Name: "+ fileName);		
    } @Override public void playMp4(String fileName) {
      //do nothing
    } }

    Mp4Player.java

    public class Mp4Player implements AdvancedMediaPlayer{
    
       @Override
       public void playVlc(String fileName) {
    
      //do nothing
    } @Override public void playMp4(String fileName) {
      System.out.println("Playing mp4 file. Name: "+ fileName);		
    } }

    Step 3

    Create adapter class implementing the MediaPlayer interface.

    MediaAdapter.java

    public class MediaAdapter implements MediaPlayer {
    
       AdvancedMediaPlayer advancedMusicPlayer;
    
       public MediaAdapter(String audioType){
       
    
      if(audioType.equalsIgnoreCase("vlc") ){
         advancedMusicPlayer = new VlcPlayer();			
         
      }else if (audioType.equalsIgnoreCase("mp4")){
         advancedMusicPlayer = new Mp4Player();
      }	
    } @Override public void play(String audioType, String fileName) {
      if(audioType.equalsIgnoreCase("vlc")){
         advancedMusicPlayer.playVlc(fileName);
      }
      else if(audioType.equalsIgnoreCase("mp4")){
         advancedMusicPlayer.playMp4(fileName);
      }
    } }

    Step 4

    Create concrete class implementing the MediaPlayer interface.

    AudioPlayer.java

    public class AudioPlayer implements MediaPlayer {
       MediaAdapter mediaAdapter; 
    
       @Override
       public void play(String audioType, String fileName) {		
    
    
      //inbuilt support to play mp3 music files
      if(audioType.equalsIgnoreCase("mp3")){
         System.out.println("Playing mp3 file. Name: " + fileName);			
      } 
      
      //mediaAdapter is providing support to play other file formats
      else if(audioType.equalsIgnoreCase("vlc") || audioType.equalsIgnoreCase("mp4")){
         mediaAdapter = new MediaAdapter(audioType);
         mediaAdapter.play(audioType, fileName);
      }
      
      else{
         System.out.println("Invalid media. " + audioType + " format not supported");
      }
    } }

    Step 5

    Use the AudioPlayer to play different types of audio formats.

    AdapterPatternDemo.java

    public class AdapterPatternDemo {
       public static void main(String[] args) {
    
      AudioPlayer audioPlayer = new AudioPlayer();
      audioPlayer.play("mp3", "beyond the horizon.mp3");
      audioPlayer.play("mp4", "alone.mp4");
      audioPlayer.play("vlc", "far far away.vlc");
      audioPlayer.play("avi", "mind me.avi");
    } }

    Step 6

    Verify the output.

    Playing mp3 file. Name: beyond the horizon.mp3
    Playing mp4 file. Name: alone.mp4
    Playing vlc file. Name: far far away.vlc
    Invalid media. avi format not supported
    
  • Prototype Pattern

    Prototype pattern refers to creating duplicate object while keeping performance in mind. This type of design pattern comes under creational pattern as this pattern provides one of the best ways to create an object.

    This pattern involves implementing a prototype interface which tells to create a clone of the current object. This pattern is used when creation of object directly is costly. For example, an object is to be created after a costly database operation. We can cache the object, returns its clone on next request and update the database as and when needed thus reducing database calls.

    Implementation

    We’re going to create an abstract class Shape and concrete classes extending the Shape class. A class ShapeCache is defined as a next step which stores shape objects in a Hashtable and returns their clone when requested.

    PrototypPatternDemo, our demo class will use ShapeCache class to get a Shape object.

    Prototype Pattern UML Diagram

    Step 1

    Create an abstract class implementing Clonable interface.

    Shape.java

    public abstract class Shape implements Cloneable {
       
       private String id;
       protected String type;
       
       abstract void draw();
       
       public String getType(){
    
      return type;
    } public String getId() {
      return id;
    } public void setId(String id) {
      this.id = id;
    } public Object clone() {
      Object clone = null;
      
      try {
         clone = super.clone();
         
      } catch (CloneNotSupportedException e) {
         e.printStackTrace();
      }
      
      return clone;
    } }

    Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

    Step 2

    Create concrete classes extending the above class.

    Rectangle.java

    public class Rectangle extends Shape {
    
       public Rectangle(){
    
     type = "Rectangle";
    } @Override public void draw() {
      System.out.println("Inside Rectangle::draw() method.");
    } }

    Square.java

    public class Square extends Shape {
    
       public Square(){
    
     type = "Square";
    } @Override public void draw() {
      System.out.println("Inside Square::draw() method.");
    } }

    Circle.java

    public class Circle extends Shape {
    
       public Circle(){
    
     type = "Circle";
    } @Override public void draw() {
      System.out.println("Inside Circle::draw() method.");
    } }

    Step 3

    Create a class to get concrete classes from database and store them in a Hashtable.

    ShapeCache.java

    import java.util.Hashtable;
    
    public class ShapeCache {
    	
       private static Hashtable<String, Shape> shapeMap  = new Hashtable<String, Shape>();
    
       public static Shape getShape(String shapeId) {
    
      Shape cachedShape = shapeMap.get(shapeId);
      return (Shape) cachedShape.clone();
    } // for each shape run database query and create shape // shapeMap.put(shapeKey, shape); // for example, we are adding three shapes public static void loadCache() {
      Circle circle = new Circle();
      circle.setId("1");
      shapeMap.put(circle.getId(),circle);
      Square square = new Square();
      square.setId("2");
      shapeMap.put(square.getId(),square);
      Rectangle rectangle = new Rectangle();
      rectangle.setId("3");
      shapeMap.put(rectangle.getId(), rectangle);
    } }

    Step 4

    PrototypePatternDemo uses ShapeCache class to get clones of shapes stored in a Hashtable.

    PrototypePatternDemo.java

    public class PrototypePatternDemo {
       public static void main(String[] args) {
    
      ShapeCache.loadCache();
      Shape clonedShape = (Shape) ShapeCache.getShape("1");
      System.out.println("Shape : " + clonedShape.getType());		
      Shape clonedShape2 = (Shape) ShapeCache.getShape("2");
      System.out.println("Shape : " + clonedShape2.getType());		
      Shape clonedShape3 = (Shape) ShapeCache.getShape("3");
      System.out.println("Shape : " + clonedShape3.getType());		
    } }

    Step 5

    Verify the output.

    Shape : Circle
    Shape : Square
    Shape : Rectangle
    
  • Builder Pattern

    Builder pattern builds a complex object using simple objects and using a step by step approach. This type of design pattern comes under creational pattern as this pattern provides one of the best ways to create an object.

    A Builder class builds the final object step by step. This builder is independent of other objects.

    Implementation

    We have considered a business case of fast-food restaurant where a typical meal could be a burger and a cold drink. Burger could be either a Veg Burger or Chicken Burger and will be packed by a wrapper. Cold drink could be either a coke or pepsi and will be packed in a bottle.

    We are going to create an Item interface representing food items such as burgers and cold drinks and concrete classes implementing the Item interface and a Packing interface representing packaging of food items and concrete classes implementing the Packing interface as burger would be packed in wrapper and cold drink would be packed as bottle.

    We then create a Meal class having ArrayList of Item and a MealBuilder to build different types of Meal objects by combining ItemBuilderPatternDemo, our demo class will use MealBuilder to build a Meal.

    Builder Pattern UML Diagram

    Step 1

    Create an interface Item representing food item and packing.

    Item.java

    public interface Item {
       public String name();
       public Packing packing();
       public float price();	
    }

    Packing.java

    public interface Packing {
       public String pack();
    }

    Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

    Step 2

    Create concrete classes implementing the Packing interface.

    Wrapper.java

    public class Wrapper implements Packing {
    
       @Override
       public String pack() {
    
      return "Wrapper";
    } }

    Bottle.java

    public class Bottle implements Packing {
    
       @Override
       public String pack() {
    
      return "Bottle";
    } }

    Step 3

    Create abstract classes implementing the item interface providing default functionalities.

    Burger.java

    public abstract class Burger implements Item {
    
       @Override
       public Packing packing() {
    
      return new Wrapper();
    } @Override public abstract float price(); }

    ColdDrink.java

    public abstract class ColdDrink implements Item {
    
    	@Override
    	public Packing packing() {
    
       return new Bottle();
    } @Override public abstract float price(); }

    Step 4

    Create concrete classes extending Burger and ColdDrink classes

    VegBurger.java

    public class VegBurger extends Burger {
    
       @Override
       public float price() {
    
      return 25.0f;
    } @Override public String name() {
      return "Veg Burger";
    } }

    ChickenBurger.java

    public class ChickenBurger extends Burger {
    
       @Override
       public float price() {
    
      return 50.5f;
    } @Override public String name() {
      return "Chicken Burger";
    } }

    Coke.java

    public class Coke extends ColdDrink {
    
       @Override
       public float price() {
    
      return 30.0f;
    } @Override public String name() {
      return "Coke";
    } }

    Pepsi.java

    public class Pepsi extends ColdDrink {
    
       @Override
       public float price() {
    
      return 35.0f;
    } @Override public String name() {
      return "Pepsi";
    } }

    Step 5

    Create a Meal class having Item objects defined above.

    Meal.java

    import java.util.ArrayList;
    import java.util.List;
    
    public class Meal {
       private List<Item> items = new ArrayList<Item>();	
    
       public void addItem(Item item){
    
      items.add(item);
    } public float getCost(){
      float cost = 0.0f;
      
      for (Item item : items) {
         cost += item.price();
      }		
      return cost;
    } public void showItems(){
      for (Item item : items) {
         System.out.print("Item : " + item.name());
         System.out.print(", Packing : " + item.packing().pack());
         System.out.println(", Price : " + item.price());
      }		
    } }

    Step 6

    Create a MealBuilder class, the actual builder class responsible to create Meal objects.

    MealBuilder.java

    public class MealBuilder {
    
       public Meal prepareVegMeal (){
    
      Meal meal = new Meal();
      meal.addItem(new VegBurger());
      meal.addItem(new Coke());
      return meal;
    } public Meal prepareNonVegMeal (){
      Meal meal = new Meal();
      meal.addItem(new ChickenBurger());
      meal.addItem(new Pepsi());
      return meal;
    } }

    Step 7

    BuiderPatternDemo uses MealBuider to demonstrate builder pattern.

    BuilderPatternDemo.java

    public class BuilderPatternDemo {
       public static void main(String[] args) {
       
    
      MealBuilder mealBuilder = new MealBuilder();
      Meal vegMeal = mealBuilder.prepareVegMeal();
      System.out.println("Veg Meal");
      vegMeal.showItems();
      System.out.println("Total Cost: " + vegMeal.getCost());
      Meal nonVegMeal = mealBuilder.prepareNonVegMeal();
      System.out.println("\n\nNon-Veg Meal");
      nonVegMeal.showItems();
      System.out.println("Total Cost: " + nonVegMeal.getCost());
    } }

    Step 8

    Verify the output.

    Veg Meal
    Item : Veg Burger, Packing : Wrapper, Price : 25.0
    Item : Coke, Packing : Bottle, Price : 30.0
    Total Cost: 55.0
    
    
    Non-Veg Meal
    Item : Chicken Burger, Packing : Wrapper, Price : 50.5
    Item : Pepsi, Packing : Bottle, Price : 35.0
    Total Cost: 85.5
    
  • Singleton Pattern

    Singleton pattern is one of the simplest design patterns in Java. This type of design pattern comes under creational pattern as this pattern provides one of the best ways to create an object.

    This pattern involves a single class which is responsible to create an object while making sure that only single object gets created. This class provides a way to access its only object which can be accessed directly without need to instantiate the object of the class.

    Implementation

    We’re going to create a SingleObject class. SingleObject class have its constructor as private and have a static instance of itself.

    SingleObject class provides a static method to get its static instance to outside world. SingletonPatternDemo, our demo class will use SingleObject class to get a SingleObject object.

    Singleton Pattern UML Diagram

    Step 1

    Create a Singleton Class.

    SingleObject.java

    public class SingleObject {
    
       //create an object of SingleObject
       private static SingleObject instance = new SingleObject();
    
       //make the constructor private so that this class cannot be
       //instantiated
       private SingleObject(){}
    
       //Get the only object available
       public static SingleObject getInstance(){
    
      return instance;
    } public void showMessage(){
      System.out.println("Hello World!");
    } }

    Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

    Step 2

    Get the only object from the singleton class.

    SingletonPatternDemo.java

    public class SingletonPatternDemo {
       public static void main(String[] args) {
    
    
      //illegal construct
      //Compile Time Error: The constructor SingleObject() is not visible
      //SingleObject object = new SingleObject();
      //Get the only object available
      SingleObject object = SingleObject.getInstance();
      //show the message
      object.showMessage();
    } }

    Step 3

    Verify the output.

    Hello World!
    
  • Abstract Factory Pattern

    Abstract Factory patterns work around a super-factory which creates other factories. This factory is also called as factory of factories. This type of design pattern comes under creational pattern as this pattern provides one of the best ways to create an object.

    In Abstract Factory pattern an interface is responsible for creating a factory of related objects without explicitly specifying their classes. Each generated factory can give the objects as per the Factory pattern.

    Implementation

    We are going to create a Shape interface and a concrete class implementing it. We create an abstract factory class AbstractFactory as next step. Factory class ShapeFactory is defined, which extends AbstractFactory. A factory creator/generator class FactoryProducer is created.

    AbstractFactoryPatternDemo, our demo class uses FactoryProducer to get a AbstractFactory object. It will pass information (CIRCLE / RECTANGLE / SQUARE for Shape) to AbstractFactory to get the type of object it needs.

    Abstract Factory Pattern UML Diagram

    Step 1

    Create an interface for Shapes.

    Shape.java

    public interface Shape {
       void draw();
    }

    Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

    Step 2

    Create concrete classes implementing the same interface.

    RoundedRectangle.java

    public class RoundedRectangle implements Shape {
       @Override
       public void draw() {
    
      System.out.println("Inside RoundedRectangle::draw() method.");
    } }

    RoundedSquare.java

    public class RoundedSquare implements Shape {
       @Override
       public void draw() {
    
      System.out.println("Inside RoundedSquare::draw() method.");
    } }

    Rectangle.java

    public class Rectangle implements Shape {
       @Override
       public void draw() {
    
      System.out.println("Inside Rectangle::draw() method.");
    } }

    Step 3

    Create an Abstract class to get factories for Normal and Rounded Shape Objects.

    AbstractFactory.java

    public abstract class AbstractFactory {
       abstract Shape getShape(String shapeType) ;
    }

    Step 4

    Create Factory classes extending AbstractFactory to generate object of concrete class based on given information.

    ShapeFactory.java

    public class ShapeFactory extends AbstractFactory {
       @Override
       public Shape getShape(String shapeType){    
    
      if(shapeType.equalsIgnoreCase("RECTANGLE")){
         return new Rectangle();         
      }else if(shapeType.equalsIgnoreCase("SQUARE")){
         return new Square();
      }	 
      return null;
    } }

    RoundedShapeFactory.java

    public class RoundedShapeFactory extends AbstractFactory {
       @Override
       public Shape getShape(String shapeType){    
    
      if(shapeType.equalsIgnoreCase("RECTANGLE")){
         return new RoundedRectangle();         
      }else if(shapeType.equalsIgnoreCase("SQUARE")){
         return new RoundedSquare();
      }	 
      return null;
    } }

    Step 5

    Create a Factory generator/producer class to get factories by passing an information such as Shape

    FactoryProducer.java

    public class FactoryProducer {
       public static AbstractFactory getFactory(boolean rounded){   
    
      if(rounded){
         return new RoundedShapeFactory();         
      }else{
         return new ShapeFactory();
      }
    } }

    Step 6

    Use the FactoryProducer to get AbstractFactory in order to get factories of concrete classes by passing an information such as type.

    AbstractFactoryPatternDemo.java

    public class AbstractFactoryPatternDemo {
       public static void main(String[] args) {
    
      //get shape factory
      AbstractFactory shapeFactory = FactoryProducer.getFactory(false);
      //get an object of Shape Rectangle
      Shape shape1 = shapeFactory.getShape("RECTANGLE");
      //call draw method of Shape Rectangle
      shape1.draw();
      //get an object of Shape Square 
      Shape shape2 = shapeFactory.getShape("SQUARE");
      //call draw method of Shape Square
      shape2.draw();
      //get shape factory
      AbstractFactory shapeFactory1 = FactoryProducer.getFactory(true);
      //get an object of Shape Rectangle
      Shape shape3 = shapeFactory1.getShape("RECTANGLE");
      //call draw method of Shape Rectangle
      shape3.draw();
      //get an object of Shape Square 
      Shape shape4 = shapeFactory1.getShape("SQUARE");
      //call draw method of Shape Square
      shape4.draw();
      
    } }

    Step 7

    Verify the output.

    Inside Rectangle::draw() method.
    Inside Square::draw() method.
    Inside RoundedRectangle::draw() method.
    Inside RoundedSquare::draw() method.
    
  • Factory Pattern

    Factory pattern is one of the most used design patterns in Java. This type of design pattern comes under creational pattern as this pattern provides one of the best ways to create an object.

    In Factory pattern, we create object without exposing the creation logic to the client and refer to newly created object using a common interface.

    Implementation

    We’re going to create a Shape interface and concrete classes implementing the Shape interface. A factory class ShapeFactory is defined as a next step.

    FactoryPatternDemo, our demo class will use ShapeFactory to get a Shape object. It will pass information (CIRCLE / RECTANGLE / SQUARE) to ShapeFactory to get the type of object it needs.

    Factory Pattern UML Diagram

    Step 1

    Create an interface.

    Shape.java

    public interface Shape {
       void draw();
    }

    Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

    Step 2

    Create concrete classes implementing the same interface.

    Rectangle.java

    public class Rectangle implements Shape {
    
       @Override
       public void draw() {
    
      System.out.println("Inside Rectangle::draw() method.");
    } }

    Square.java

    public class Square implements Shape {
    
       @Override
       public void draw() {
    
      System.out.println("Inside Square::draw() method.");
    } }

    Circle.java

    public class Circle implements Shape {
    
       @Override
       public void draw() {
    
      System.out.println("Inside Circle::draw() method.");
    } }

    Step 3

    Create a Factory to generate object of concrete class based on given information.

    ShapeFactory.java

    public class ShapeFactory {
    	
       //use getShape method to get object of type shape 
       public Shape getShape(String shapeType){
    
      if(shapeType == null){
         return null;
      }		
      if(shapeType.equalsIgnoreCase("CIRCLE")){
         return new Circle();
         
      } else if(shapeType.equalsIgnoreCase("RECTANGLE")){
         return new Rectangle();
         
      } else if(shapeType.equalsIgnoreCase("SQUARE")){
         return new Square();
      }
      
      return null;
    } }

    Step 4

    Use the Factory to get object of concrete class by passing an information such as type.

    FactoryPatternDemo.java

    public class FactoryPatternDemo {
    
       public static void main(String[] args) {
    
      ShapeFactory shapeFactory = new ShapeFactory();
      //get an object of Circle and call its draw method.
      Shape shape1 = shapeFactory.getShape("CIRCLE");
      //call draw method of Circle
      shape1.draw();
      //get an object of Rectangle and call its draw method.
      Shape shape2 = shapeFactory.getShape("RECTANGLE");
      //call draw method of Rectangle
      shape2.draw();
      //get an object of Square and call its draw method.
      Shape shape3 = shapeFactory.getShape("SQUARE");
      //call draw method of square
      shape3.draw();
    } }

    Step 5

    Verify the output.

    Inside Circle::draw() method.
    Inside Rectangle::draw() method.
    Inside Square::draw() method.
    
  • Overview

    Design patterns represent the best practices used by experienced object-oriented software developers. Design patterns are solutions to general problems that software developers faced during software development. These solutions were obtained by trial and error by numerous software developers over quite a substantial period of time.

    What is Gang of Four (GOF)?

    In 1994, four authors Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides published a book titled Design Patterns – Elements of Reusable Object-Oriented Software which initiated the concept of Design Pattern in Software development.

    These authors are collectively known as Gang of Four (GOF). According to these authors design patterns are primarily based on the following principles of object orientated design.

    • Program to an interface not an implementation
    • Favor object composition over inheritance

    Usage of Design Pattern

    Design Patterns have two main usages in software development.

    Common platform for developers

    Design patterns provide a standard terminology and are specific to particular scenario. For example, a singleton design pattern signifies use of single object so all developers familiar with single design pattern will make use of single object and they can tell each other that program is following a singleton pattern.

    Best Practices

    Design patterns have been evolved over a long period of time and they provide best solutions to certain problems faced during software development. Learning these patterns helps unexperienced developers to learn software design in an easy and faster way.

    Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

    Types of Design Patterns

    As per the design pattern reference book Design Patterns – Elements of Reusable Object-Oriented Software , there are 23 design patterns which can be classified in three categories: Creational, Structural and Behavioral patterns. We’ll also discuss another category of design pattern: J2EE design patterns.

    S.N.Pattern & Description
    1Creational Patterns
    These design patterns provide a way to create objects while hiding the creation logic, rather than instantiating objects directly using new operator. This gives program more flexibility in deciding which objects need to be created for a given use case.
    2Structural Patterns
    These design patterns concern class and object composition. Concept of inheritance is used to compose interfaces and define ways to compose objects to obtain new functionalities.
    3Behavioral Patterns
    These design patterns are specifically concerned with communication between objects.
    4J2EE Patterns
    These design patterns are specifically concerned with the presentation tier. These patterns are identified by Sun Java Center.
  • Recursion

    Overview

    Recursion refers to a technique in a programming language where a function calls itself. The function which calls itself is called a recursive method.

    Characteristics

    A recursive function must posses the following two characteristics

    • Base Case(s)
    • Set of rules which leads to base case after reducing the cases.

    Learn Java in-depth with real-world projects through our Java certification course. Enroll and become a certified expert to boost your career.

    Recursive Factorial

    Factorial is one of the classical example of recursion. Factorial is a non-negative number satisfying following conditions.

    1. 0! = 1
    2. 1! = 1
    3. n! = n * n-1!

    Factorial is represented by “!”. Here Rule 1 and Rule 2 are base cases and Rule 3 are factorial rules.

    As an example, 3! = 3 x 2 x 1 = 6

    private int factorial(int n){
       //base case
       if(n == 0){
    
      return 1;
    }else{
      return n * factorial(n-1);
    } }

    Recursive Fibonacci Series

    Fibonacci Series is another classical example of recursion. Fibonacci series a series of integers satisfying following conditions.

    1. F0 = 0
    2. F1 = 1
    3. Fn = Fn-1 + Fn-2

    Fibonacci is represented by “F”. Here Rule 1 and Rule 2 are base cases and Rule 3 are fibonnacci rules.

    As an example, F5 = 0 1 1 2 3

    Demo Program

    RecursionDemo.java

    package com.tutorialspoint.algorithm;
    
    public class RecursionDemo {
       public static void main(String[] args){
    
      RecursionDemo recursionDemo = new RecursionDemo();
      int n = 5;
      System.out.println("Factorial of " + n + ": "
         + recursionDemo.factorial(n));
      System.out.print("Fibbonacci of " + n + ": ");
      for(int i=0;i&lt;n;i++){
         System.out.print(recursionDemo.fibbonacci(i) +" ");            
      }
    } private int factorial(int n){
      //base case
      if(n == 0){
         return 1;
      }else{
         return n * factorial(n-1);
      }
    } private int fibbonacci(int n){
      if(n ==0){
         return 0;
      }
      else if(n==1){
         return 1;
      }
      else {
         return (fibbonacci(n-1) + fibbonacci(n-2));
      }
    } }

    If we compile and run the above program then it would produce following result −

    Factorial of 5: 120
    Fibbonacci of 5: 0 1 1 2 3
    
  • Sorting techniques

    Sorting refers to arranging data in a particular format. Sorting algorithm specifies the way to arrange data in a particular order. Most common orders are numerical or lexicographical order.

    Importance of sorting lies in the fact that data searching can be optimized to a very high level if data is stored in a sorted manner. Sorting is also used to represent data in more readable formats. Some of the examples of sorting in real life scenarios are following.

    • Telephone Directory − Telephone directory keeps telephone no. of people sorted on their names. So that names can be searched.
    • Dictionary − Dictionary keeps words in alphabetical order so that searching of any work becomes easy.

    Types of Sorting

    Following is the list of popular sorting algorithms and their comparison.

    Sr.NoTechnique & Description
    1Bubble SortBubble sort is simple to understand and implement algorithm but is very poor in performance.
    2Selection SortSelection sort as name specifies use the technique to select the required item and prepare sorted array accordingly.
    3Insertion SortInsertion sort is a variation of selection sort.
    4Shell SortShell sort is an efficient version of insertion sort.
    5Quick SortQuick sort is a highly efficient sorting algorithm and is based on partitioning of array of data into smaller arrays.
    6Sorting ObjectsJava objects can be sorted easily using java.util.Arrays.sort()
  • Search techniques

    Search refers to locating a desired element of specified properties in a collection of items. We are going to start our discussion using following commonly used and simple search algorithms.

    Sr.NoTechnique & Description
    1Linear SearchLinear search searches all items and its worst execution time is n where n is the number of items.
    2Binary SearchBinary search requires items to be in sorted order but its worst execution time is constant and is much faster than linear search.
    3Interpolation SearchInterpolation search requires items to be in sorted order but its worst execution time is O(n) where n is the number of items and it is much faster than linear search.