Free Data Structures and Algorithms Course









Subscribe below and get all best seller courses for free !!!










OR



Subscribe to all free courses

Java 7 new feature : Determining the file content type

Program to demonstrate Java 7 new feature : Determining the file content type.

package com.hubberspot.nio;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class FileContentType {

    public static void main(String[] args) {
        
        printContentType("D:/Downloads/java.txt");
        printContentType("D:/Downloads/java.ppt");
        printContentType("D:/Downloads/java.doc");
        printContentType("D:/Downloads/java.jar");

    }

    private static void printContentType(String pathToFile) {
        
        Path path = Paths.get(pathToFile);
        String contentType = null;
        try {
            contentType = Files.probeContentType(path);
        } catch (IOException e) {
     
            e.printStackTrace();
        }
        System.out.println("File content type is : " + contentType);
        
    }

}



Output of the program : 

 

How to set different Look and Feel in Java Swing ?.

A simple Java program to set different installed look and feel in Java Swing

package com.hubberspot.swing;

import java.awt.Color;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;

class LookAndFeel extends JFrame {

    private JPanel panel;
    private JTextField textField;
    
    public LookAndFeel() {
     
        setTitle("Look And Feel Demo");
        setSize(300, 200);
        
        panel = new JPanel();
        
        textField = new JTextField("Metal look and feel");
        textField.setBackground(Color.cyan);
        
        LookAndFeelInfo[] installedLookAndFeels = UIManager.getInstalledLookAndFeels();
        
        for(LookAndFeelInfo lookAndFeel : installedLookAndFeels) {
            
            final String name = lookAndFeel.getName();
            final String className = lookAndFeel.getClassName();
            
            JButton button = new JButton(name);
            panel.add(button);
            
            button.addActionListener(new ActionListener()
            {
               public void actionPerformed(ActionEvent event)
               {
                  try
                  {
                     UIManager.setLookAndFeel(className);
                     SwingUtilities.updateComponentTreeUI(LookAndFeel.this);
                     textField.setText(name + " look and feel");
                  }
                  catch (Exception e)
                  {
                     e.printStackTrace();
                  }
               }
            });
        }
        
        panel.add(textField);
        add(panel);
         
    }
}


public class LookAndFeelTest {

    public static void main(String[] args) {

        EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
                LookAndFeel frame = new LookAndFeel();
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setVisible(true);
            }
        });
    }

}   



Output of the program : 




 

Observer Design Pattern in Java

What is Observer Design Pattern in Java ?.

The Gang of Four book (Design Patterns: Elements of Reusable Object-Oriented Software, 1995, Pearson Education, Inc. Publishing as Pearson Addison Wesley) says that the Observer design pattern should

"Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically."

Example : Let's say there is Weather Broadcasting company which broadcast weather changes to its subscribers. The subscribers or observers such as News Channels , News Paper Agencies and Weather Information Provider websites etc ... gets updated as soon as weather changes by the Weather Broadcasting company. Let's see how we can implement this Subject - Observer model in Java.

Program to demonstrate how to implement Observer Design Pattern in Java.

1. Subject.java
package com.hubberspot.designpattern.behavioral.observer;

public interface Subject {
    
    public void addObserver(Observer observer);
    
    public void removeObserver(Observer observer);
    
    public void notifyObservers();

}


2. Observer.java
package com.hubberspot.designpattern.behavioral.observer;

public interface Observer {
    
    public void update(int temperature);

}


3. WeatherBroadcast.java
package com.hubberspot.designpattern.behavioral.observer;

import java.util.ArrayList;
import java.util.List;

public class WeatherBroadcast implements Subject {

    private List< Observer > listOfObservers;
    private int temperature;    
    
    public WeatherBroadcast() {
        listOfObservers = new ArrayList< Observer >();
    }
    
    @Override
    public void addObserver(Observer observer) {
        
        listOfObservers.add(observer);
        
    }

    @Override
    public void removeObserver(Observer observer) {
        
        listOfObservers.remove(observer);        
        
    }

    @Override
    public void notifyObservers() {
        
        for(Observer observer : listOfObservers) {
            observer.update(temperature);
        }
        
    }
    
    public void temperatureChanged(int newTemperature) { 
        temperature = newTemperature;
        notifyObservers();
    }

}


4. NewsPaperAgency.java
package com.hubberspot.designpattern.behavioral.observer;

public class NewsPaperAgency implements Observer {

    @Override
    public void update(int temperature) {

        System.out.println("News Paper Agencies gets current temperature as: "
                + temperature + " degrees");

    }

}


5. NewsChannel.java
package com.hubberspot.designpattern.behavioral.observer;

public class NewsChannel implements Observer {

    @Override
    public void update(int temperature) {

        System.out.println("News Channel gets current temperature as: "
                + temperature + " degrees");

    }

}


6. WeatherInfoWebsite.java
package com.hubberspot.designpattern.behavioral.observer;

public class WeatherInfoWebsite implements Observer {

    @Override
    public void update(int temperature) {

        System.out.println("Weather Info Websites gets current temperature as: "
                + temperature + " degrees");

    }

}


7. ObserverDesignPatternTest.java
package com.hubberspot.designpattern.behavioral.observer;

public class ObserverDesignPatternTest {

    public static void main(String[] args) throws InterruptedException {

        WeatherBroadcast weatherBroadcast = new WeatherBroadcast();

        Observer newsPaperAgency = new NewsPaperAgency();
        Observer newsChannel = new NewsChannel();
        Observer weatherInfoWebsite = new WeatherInfoWebsite();

        weatherBroadcast.addObserver(newsPaperAgency);
        weatherBroadcast.addObserver(newsChannel);
        weatherBroadcast.addObserver(weatherInfoWebsite);
        
        weatherBroadcast.temperatureChanged(30);
        
        System.out.println("\nAfter 2 minutes temperature changes to 33 degrees...\n");
        
        Thread.sleep(120000);
        
        weatherBroadcast.temperatureChanged(33);

    }

}


Output of the program : 

 



Video tutorial to demonstrate how to implement Observer Design Pattern in Java.







Decorator Design Pattern in Java


What is Decorator Design Pattern in Java.

The formal definition of the Decorator pattern from the GoF book (Design Patterns: Elements of Reusable Object-Oriented Software, 1995, Pearson Education, Inc. Publishing as Pearson Addison Wesley) says you can,

"Attach additional responsibilities to an object dynamically. Decorators
provide a flexible alternative to subclassing for extending functionality."


Let's say we have a Pizza and we want to decorate it with toppings such as Chicken Masala, Onion and Mozzarella Cheese. Let's see how to implement it in Java ...




Video tutorial to demonstrate how to implement Decorator Design Pattern in Java.






Click here to download source code 










Program to demonstrate how to implement Decorator Design Pattern in Java.

1. Pizza.java

package com.hubberspot.designpattern.structural.decorator;

public class Pizza {

    public Pizza() {
        
    }
    
    public String description(){
        return "Pizza";
    }    
}



2. PizzaToppings.java
package com.hubberspot.designpattern.structural.decorator;

public abstract class PizzaToppings extends Pizza {

    public abstract String description();
    
}



3. ChickenMasala.java

package com.hubberspot.designpattern.structural.decorator;

public class ChickenMasala extends PizzaToppings {

private Pizza pizza;
    
    public ChickenMasala(Pizza pizza) {
        this.pizza = pizza;
    }
    
    @Override
    public String description() {
        return pizza.description() + " with chicken masala, ";
    }

}



4. Onion.java

package com.hubberspot.designpattern.structural.decorator;

public class Onion extends PizzaToppings {

    private Pizza pizza;
    
    public Onion(Pizza pizza) {
        this.pizza = pizza;
    }
    
    @Override
    public String description() {
        return pizza.description() + "onions, ";
    }

}



5. Mozzarella.java

package com.hubberspot.designpattern.structural.decorator;

public class MozzarellaCheese extends PizzaToppings {

    private Pizza pizza;
    
    public MozzarellaCheese(Pizza pizza) {
        this.pizza = pizza;
    }
    
    @Override
    public String description() {
        return pizza.description() + "and mozzarella cheese.";
    }
}




6. TestDecorator.java

package com.hubberspot.designpattern.structural.decorator;

public class TestDecorator {

    public static void main(String[] args) {
        
        Pizza pizza = new Pizza();
        
        pizza = new ChickenMasala(pizza);
        pizza = new Onion(pizza);
        pizza = new MozzarellaCheese(pizza);
        
        System.out.println("You're getting " + pizza.description());

    }

}


Output of the program : 

 


























How to implement Iterator Design Pattern in Java ?.

Program to demonstrate how to implement Iterator Design Pattern in Java.

1. Song.java
package com.hubberspot.designpattern.behavioral.iterator;

public class Song {

    private String songName;
    private String singer;

    public Song(String songName, String singer) {
        super();
        this.songName = songName;
        this.singer = singer;
    }    

    public String getSongName() {
        return songName;
    }
    public String getSinger() {
        return singer;
    }

}



2. SongCollection.java
package com.hubberspot.designpattern.behavioral.iterator;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class SongCollection {

    private List< Song > songList = new ArrayList< Song >();

    public void addSong(Song song) {
        songList.add(song);
    }

    public Iterator< Song > getSongIterator() {

        return new SongIterator();
    } 

    private class SongIterator implements Iterator< Song > {

        int currentSongIndex = 0;

        @Override
        public boolean hasNext() {
            if (currentSongIndex >= songList.size()) {
                return false;
            } else {
                return true;
            }
        }

        @Override
        public Song next() {

            return songList.get(currentSongIndex++);

        }

        @Override
        public void remove() {

            songList.remove(--currentSongIndex);

        }

    }
}



3. SongIterationDemo.java
package com.hubberspot.designpattern.behavioral.iterator;

import java.util.Iterator;

public class SongIterationDemo {

    public static void main(String[] args) {

        Song s1 = new Song("Rock You !!!" , "Eric Martin");        
        Song s2 = new Song("Someone Gone !!!" , "Neuone Derek");        
        Song s3 = new Song("Remember Me !!!" , "Justin Diebler");        

        SongCollection songCollection = new SongCollection();
        songCollection.addSong(s1);
        songCollection.addSong(s2);
        songCollection.addSong(s3);

        System.out.println("Displaying Song Info : \n");
        Iterator< Song > songIterator = songCollection.getSongIterator();

        while(songIterator.hasNext()) {
            Song song = songIterator.next();
            System.out.println("Song Name : " + song.getSongName());
            System.out.println("Song Singer : " + song.getSinger());
            System.out.println();
        }

        System.out.println("Removing Song and Displaying :\n");

        songIterator.remove();

        songIterator = songCollection.getSongIterator();

        while(songIterator.hasNext()) {
            Song song = songIterator.next();
            System.out.println("Song Name : " + song.getSongName());
            System.out.println("Song Singer : " + song.getSinger());
            System.out.println();
        }
    }
}



Output of the program : 


 

How to implement Composite Design Pattern in Java ?.

Program to demonstrate how to implement Composite Design Pattern in Java.

1. Geographical.java 

package com.hubberspot.designpattern.structural.composite;

// This acts as a interface for every State(Leaf) and
// Country(Composite)
public abstract class GeographicalArea {

    // Name of the region 
    private String areaName;    

    public GeographicalArea(String areaName) {

        this.areaName = areaName;
    }    

    public String getAreaName() {
        return areaName;
    }

    // Create methods which will throw UnsupportedOperationException

    public void addGeographicalArea(GeographicalArea geographicalArea) {

        throw new UnsupportedOperationException(
                "Invalid Operation. Not Supported");
    }
    public GeographicalArea getGeographicalArea(int areaIndex) {

        throw new UnsupportedOperationException(
                "Invalid Operation. Not Supported");
    }

    public long getPopulation() {

        throw new UnsupportedOperationException(
                "Invalid Operation. Not Supported");
    }

    // Create a abstract method which will be implemented
    // by State and Country respectively
    public abstract void displayAreaInfo();

}



2. Country.java


package com.hubberspot.designpattern.structural.composite;

import java.util.ArrayList;
import java.util.List;

// It extends GeographicalArea and has a list of 
// objects containing the GeographicalArea such as 
// State in this case.
public class Country extends GeographicalArea {

    List< GeographicalArea > listOfGeographicalArea = new ArrayList< GeographicalArea >();

    public Country(String areaName) {
        super(areaName);
    }

    // adding states to country
    @Override
    public void addGeographicalArea(GeographicalArea geographicalArea)
            throws UnsupportedOperationException {
        listOfGeographicalArea.add(geographicalArea);
    }

    // getting states one by one based on index
    @Override
    public GeographicalArea getGeographicalArea(int areaIndex)
            throws UnsupportedOperationException {

        return listOfGeographicalArea.get(areaIndex);

    }

    // displaying the information for the country
    @Override
    public void displayAreaInfo() {

        System.out.println("Country name : " + getAreaName());
        System.out.println("It has following info : ");

        long totalPopulation = 0;
        int index = 1;

        System.out.println("It has following states : ");
        for(GeographicalArea geographicalArea : listOfGeographicalArea) {

            System.out.println(index + " : "+ geographicalArea.getAreaName() );
            System.out.println("It has population around : " + geographicalArea.getPopulation());
            totalPopulation = totalPopulation + geographicalArea.getPopulation();
            index++;
        }

        System.out.println("Total Population of "+ getAreaName()+ " is : " + totalPopulation);

    }

}



3. State.java


package com.hubberspot.designpattern.structural.composite;

//It extends GeographicalArea
public class State extends GeographicalArea {

    // has a property called as population 
    private long population;


    public long getPopulation() {
        return population;
    }

    public State(String areaName, long population) {
        super(areaName);
        this.population = population;        
    }

    // displaying the information for the states
    @Override
    public void displayAreaInfo() {

        System.out.println("State name : " + getAreaName());
        System.out.println("State population : " + getPopulation());

    }

}


4. TestCompositePattern.java

package com.hubberspot.designpattern.structural.composite;

public class TestCompositePattern {

    public static void main(String[] args) {

        // Create two countries such as India and USA
        GeographicalArea countryIndia = new Country("India");
        GeographicalArea countryUSA = new Country("USA");

        // Create two Indian States with name and population
        GeographicalArea stateMadhyaPradesh = new State("Madhya Pradesh", 10000000);
        GeographicalArea stateMaharashtra = new State("Maharashtra", 20000000);

        // Create two USA States with name and population
        GeographicalArea stateNewYork = new State("New York", 19570261);
        GeographicalArea stateWashington = new State("Washington", 6897012);

        // Add the Indian States to India 
        countryIndia.addGeographicalArea(stateMadhyaPradesh);
        countryIndia.addGeographicalArea(stateMaharashtra);

        // Add the USA States to USA
        countryUSA.addGeographicalArea(stateNewYork);
        countryUSA.addGeographicalArea(stateWashington);

        // Display Info for country India 
        countryIndia.displayAreaInfo();
        System.out.println();

        // Display Info for country USA
        countryUSA.displayAreaInfo();

    }

}



Output of the program :

How to implement Builder Design Pattern in Java ?.

Program to demonstrate how to implement Builder Design Pattern in Java.

package com.hubberspot.designpattern.creational.builder;

// 1. Create a Robot class which is to be build by 
// Builder Design Pattern.
public class Robot {

    // 2. Robot has few properties/characteristics
    private String robotHead;
    private String robotTorso;
    private String robotArms;
    private String robotLegs;

    // 3. Create getters for each characteristics
    public String getRobotHead() {
        return robotHead;
    }

    public String getRobotTorso() {
        return robotTorso;
    }

    public String getRobotArms() {
        return robotArms;
    }

    public String getRobotLegs() {
        return robotLegs;
    }

    // 4. Create a static class which will build our 
    // Robot
    public static class RobotBuilder {
        
        // 5. Provide it with properties with which it will
        // prepare the required Robot
        private String robotHead = "";
        private String robotTorso = "" ;
        private String robotArms = "";
        private String robotLegs = "";

        public RobotBuilder() {

        }

        // 6. Create methods for each properties which Robot 
        // requires to get in action. The client will pass
        // necessary values for the type of Robot they want.
        public RobotBuilder buildRobotHead(String robotHead) {
            this.robotHead = robotHead;
            return this;
        }

        public RobotBuilder buildRobotTorso(String robotTorso) {
            this.robotTorso = robotTorso;
            return this;
        }

        public RobotBuilder buildRobotArms(String robotArms) {
            this.robotArms = robotArms;
            return this;
        }

        public RobotBuilder buildRobotLegs(String robotLegs) {
            this.robotLegs = robotLegs;
            return this;
        }

        // 7. Final build method will return us back the required 
        // Robot
        public Robot build() {
            return new Robot(this);
        }
    }

    // 8. Actual preparation of Robot by RobotBuilder
    private Robot(RobotBuilder robotBuilder) {
        robotHead = robotBuilder.robotHead;
        robotTorso = robotBuilder.robotTorso;
        robotArms = robotBuilder.robotArms;
        robotLegs = robotBuilder.robotLegs;
    }

    // 9. Creation of Iron Robot and Steel Robot by the 
    // client.
    public static void main(String[] args) {

        System.out.println("Let's build a Iron Robot .... \n");
        
        Robot ironRobot = new Robot.RobotBuilder()
              .buildRobotHead("Iron Head")
              .buildRobotTorso("Iron Torso")
              .buildRobotArms("Iron Arms")
              .buildRobotLegs("Iron Legs")
              .build();
        
        System.out.println("Iron Robot is build with following specs : \n");

        System.out.println("Robot Head : " + ironRobot.getRobotHead());
        System.out.println("Robot Torso : " + ironRobot.getRobotTorso());
        System.out.println("Robot Arms : " + ironRobot.getRobotArms());
        System.out.println("Robot Legs : " + ironRobot.getRobotLegs());
        
        System.out.println();
        
        System.out.println("Let's build a Steel Robot .... \n");
        
        Robot steelRobot = new Robot.RobotBuilder()
              .buildRobotHead("Steel Head")
              .buildRobotTorso("Steel Torso")
              .buildRobotArms("Steel Arms")
              .buildRobotLegs("Steel Legs")
              .build();
        
        System.out.println("Steel Robot is build with following specs : \n");

        System.out.println("Robot Head : " + steelRobot.getRobotHead());
        System.out.println("Robot Torso : " + steelRobot.getRobotTorso());
        System.out.println("Robot Arms : " + steelRobot.getRobotArms());
        System.out.println("Robot Legs : " + steelRobot.getRobotLegs());
              
    }
}



Output of the program :

 

How to implement Factory Design Pattern in Java ?.

Program to demonstrate how to implement Factory Design Pattern in Java.

1. Animal.java 

package com.hubberspot.designpattern.creational.factorymethod;

// 1. Create a Animal interface
// having a method definition say eat
public interface Animal {

    public void eat();

}


2. AnimalFactory.java 

package com.hubberspot.designpattern.creational.factorymethod;

// 2. Create a AnimalFactory which 
// will create instances of concrete
// Animals
public class AnimalFactory {

    // 3. Create a static getAnimal method which will
    // take package name + class name of class whose
    // instance is to be created.
    public static Animal getAnimal(String classInfo) {
        Animal animal = null;
        try {
            // 4. Class.forName(String) dynamically loads class
            // passed as a String to it. 
            // 5. newInstance() method creates a concrete instance of
            // the class passed to Class.forName() as a String.
            animal = (Animal) Class.forName(classInfo).newInstance();
        } catch (Exception e) {           
            e.printStackTrace();
        } 
        // 6. We return the concrete instance.
        return animal;
    }

}


3. Dog.java 

package com.hubberspot.designpattern.creational.factorymethod;

// 8. Concrete animal Dog for the Animal interface
public class Dog implements Animal {

    @Override
    public void eat() {

        System.out.println("Dog eating .... ");

    }

}


4. Cat.java 

package com.hubberspot.designpattern.creational.factorymethod;

// 7. Concrete animal Cat for the Animal interface
public class Cat implements Animal {

    @Override
    public void eat() {

        System.out.println("Cat eating .... ");

    }

}


5. TestFactoryDesignPattern.java 

package com.hubberspot.designpattern.creational.factorymethod;

import com.hubberspot.designpattern.creational.factorymethod.Dog;

public class TestFactoryDesignPattern {

    public static void main(String[] args) {

        // 9. Create a Dog object from the AnimalFactory by passing fully
        // qualified name for the concrete Dog class
        Dog dog = (Dog) AnimalFactory.getAnimal(
                "com.hubberspot.designpattern.creational.factorymethod.Dog"
                );
        dog.eat();

        // 10. Create a Cat object from the AnimalFactory by passing fully
        // qualified name for the concrete Cat class
        Cat cat = (Cat) AnimalFactory.getAnimal(
                "com.hubberspot.designpattern.creational.factorymethod.Cat"
                );
        cat.eat();

    }


}


Output of the program : 


 




Video tutorial to demonstrate how to implement Factory Design Pattern in Java.















How to implement Prototype Design Pattern in Java ?.

Program to demonstrate how to implement Prototype Design Pattern in Java.

package com.hubberspot.designpattern.creational.prototype;

// 1. Create a class Dog implementing Cloneable
// interface
public class Dog implements Cloneable {

    // 2. Create few properties to Dog object.
    private String name;
    private String breed;

    // 3. Create a constructor for properties
    // initialization
    public Dog(String name, String breed) {
        super();
        this.name = name;
        this.breed = breed;
    }

    // 4. Create getters and setters for the properties
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getBreed() {
        return breed;
    }

    public void setBreed(String breed) {
        this.breed = breed;
    }

    // 5. Create a method which will create a
    // prototype or clone of the object invoking
    // this method
    public Dog makeCopyOfDog() {

        Dog clonedDog = null;

        // 6. super.clone() returns clone of the object
        // invoking it.
        try {
            clonedDog = (Dog) super.clone();
        } catch (CloneNotSupportedException e) {

            e.printStackTrace();
        }
        return clonedDog;
    }



    public static void main(String[] args) {

        // 7. Create a original dog
        Dog originalDog = new Dog("Jimmy" , "Bulldog"); 

        // 8. Create clone of dog created in step 7 by calling
        // originalDog.makeCopyOfDog() method
        Dog clonedDog = originalDog.makeCopyOfDog();

        System.out.println("Original Dog's name is: " + originalDog.getName());
        System.out.println("Original Dog's breed is: " + originalDog.getBreed());
        System.out.println();
        System.out.println("Cloned Dog's name is: " + clonedDog.getName());
        System.out.println("Cloned Dog's breed is: " + clonedDog.getBreed());

    } 

}



Output of the program :


How to make a class singleton in Java using Singleton Design Pattern ?.

Program to demonstrate how to make a class singleton in Java using Singleton Design Pattern.
package com.hubberspot.designpattern.creational.singleton;

//Steps to make a class Singleton in nature :-

//   1. Create a class by name say SingletonClass 
public class SingletonClass {

    //   2. Create a private default constructor of the
    //      class created above in step 1.

    private SingletonClass() { 

    }

    //   3. Create a private static variable of type class
    //      created in step 1 itself. It should be private,
    //      static and gets reference to instance of class itself.

    private static SingletonClass SINGLETON_INSTANCE = 
            new SingletonClass();

    //   4. Create a static accessor method which always 
    //      return us back the same instance created in 
    //      step 3. The name of the method could be
    //      according to good naming convention as : 
    //      getInstance()

    public static SingletonClass getInstance() {
        return SINGLETON_INSTANCE;
    }
    
    //   5. There should not be any method or constructor
    //      which creates another object of SingletonClass.
}


 
© 2021 Learn Java by Examples Template by Hubberspot