What is Method Overloading?

Method Overloading:

One or more methods  in a class having same name, but different number or type of arguments, is called method overloading.

When a overloaded method is called, the method with matching number and type of arguments gets executed.

If there is no exact match of argument types, type promotion is applied, before invoking the method.

For eg

class Abc{

void add(int i, int j){  //body of method }

void add(float i, float j, float k){ //body of method }

void add(int i,int j, int k){ //body of method }

}

NOTE:

1.Method overloading cannot be done, based only on return type of the method

2.Method overloading is compile time polymorphism, as the method which need to get called is decided/binded during compile time itself.

Question:

Can below methods be overloaded??

class Abc{

void add(int i, int j){  //body of method }

int add(int a, int b){ //body of method }

}

Sample Project interview Questions

Few of my students and other have been following up with me to provide list of commonly asked Project related Questions by Interviewer. Below are few of them I can think of

  1. Which are the Languages/Technologies used to implement your Project
  2. Which Software Model has been used
  3. Duration of Project, and your Role and Contribution to Project
  4. Which Configuration Management Tool was used for your Project?
  5. How many modules are there, and on which Modules you worked?
  6. Architecture diagram of your Project?
  7. Which Design Patterns are applied? and Which Frameworks were used?
  8. Who is the End user of your Project?
  9. What are the main Challenges you faced, during your Project?
  10. How many Lines of Code you developed?
  11. What are various Testings performed?
  12. Which Bug Tracking Tool was used?
  13. Have you applied MVC for your Project?

Please visit back for updates…

My Quora Profile

Purpose of Composite Design Pattern

"Compose objects into tree structure to represent part-whole hierarchies. 

Composite lets client treat individual objects and compositions of objects uniformly".

Composite design pattern treats each node in two ways-Composite or leaf. 
Composite means it can have other objects below it. Leaf does not have objects below it

Component
declares interface for objects in composition.
implements default behavior for the interface common to all classes as appropriate.
declares an interface for accessing and managing its child components.
Leaf
represents leaf objects in the composition. A leaf has no children.
defines behavior for primitive objects in the composition.
Composite
defines behavior for components having children.
stores child components.
implements child related operations in the component interface.
Client
manipulates objects in the composition through the component interface.

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


interface Employee {

 public void add(Employee employee) throws Exception;
 public void remove(Employee employee);
 public Employee getChild(int i);
 public String getName();
 public double getSalary();
 public String getDesignation();
 public void print();
}


class Director implements Employee{

 private String name;
 private double salary;

 public Director(String name,double salary){
 this.name = name;
 this.salary = salary;
 }

 List<Employee> employees = new ArrayList<Employee>();
 public void add(Employee obj) throws Exception{
 String c_name = obj.getClass().getName();
 if(c_name.equalsIgnoreCase("Manager"))
 {
 employees.add(obj);
 }
 else
 {
 throw new Exception("non Manager not allowed to add");
 }
 
 }

 public Employee getChild(int i) {
 return employees.get(i);
 }

 public String getName() {
 return name;
 }

 public double getSalary() {
 return salary;
 }

 public String getDesignation(){
 return "Director";
 }
 public void print() {
 System.out.println("-------------");
 System.out.println("Name ="+getName());
 System.out.println("Salary ="+getSalary());
 System.out.println("-------------");

 Iterator<Employee> employeeIterator = employees.iterator();
 while(employeeIterator.hasNext()){
 Employee employee = employeeIterator.next();
 employee.print();
 }
 }

 public void remove(Employee employee) {
 employees.remove(employee);
 }
 }


class Manager implements Employee{

 private String name;
 private double salary;

 public Manager(String name,double salary){
 this.name = name;
 this.salary = salary;
 }

 List<Employee> employees = new ArrayList<Employee>();
 public void add(Employee employee) {
 employees.add(employee);
 }

 public Employee getChild(int i) {
 return employees.get(i);
 }

 public String getName() {
 return name;
 }

 public double getSalary() {
 return salary;
 }

 public String getDesignation(){
 return "Manager";
 }
 public void print() {
 System.out.println("-------------");
 System.out.println("Name ="+getName());
 System.out.println("Salary ="+getSalary());
 System.out.println("-------------");

 Iterator<Employee> employeeIterator = employees.iterator();
 while(employeeIterator.hasNext()){
 Employee employee = employeeIterator.next();
 employee.print();
 }
 }

 public void remove(Employee employee) {
 employees.remove(employee);
 }
}


class Developer implements Employee{

 private String name;
 private double salary;

 public Developer(String name,double salary){
 this.name = name;
 this.salary = salary;
 }
 public void add(Employee employee) {
 //this is leaf node so this method is not applicable to this class.
 }

 public Employee getChild(int i) {
 //this is leaf node so this method is not applicable to this class.
 return null;
 }

 public String getName() {
 return name;
 }

 public double getSalary() {
 return salary;
 }

 public String getDesignation(){
 return "Developer"; 
 }
 
 public void print() {
 System.out.println("-------------");
 System.out.println("Name ="+getName());
 System.out.println("Salary ="+getSalary());
 System.out.println("-------------");
 }

 public void remove(Employee employee) {
 //this is leaf node so this method is not applicable to this class.
 }

 }
 

public class CompositeEg {
 public static void main(String[] args) {
 try
 {
 Employee dir1 = new Director("dir1", 80000);
 Employee manager1=new Manager("mgr1",25000);
 
 Employee emp1=new Developer("dev1", 10000);
 Employee emp2=new Developer("dev2", 15000);
 
 manager1.add(emp1);
 manager1.add(emp2);
 
 dir1.add(manager1);
 
 Employee gManager=new Manager("mgr2", 50000);
 Employee emp3=new Developer("dev3", 20000);
 
 gManager.add(emp3);
 gManager.add(manager1);
 
 dir1.add(gManager);
 dir1.print();
 
 dir1.add( new Developer("ldev",19000));
 
 System.out.println("Designation: "+gManager.getDesignation());
 }catch(Exception e)
 {
 e.printStackTrace();
 }
 }
}

Design Pattern Free PDF

Chain of Responsibility Design Pattern

Below is an example of Chain of Responsibility Design Pattern

One of the best example where Chain of Responsibility Design Pattern can be applied is below.
Say if you want to withdraw 2200 Rs, and ATM has 1000, 500 and 100 rupee notes.
As per chain of responsibility the request would be sent to object that dispenses 1000 rs note.
If 1000 rupee notes are NOT available then it would be sent to an object that dispenses 500 rs note.
The 500Rs object decides to dispense 4 notes and then 100 rs object would be asked to handle the rest.
* Advantage is, eventhough there are no 1000 rs not available, your request would be still handled by other objects like 500 and 100.

class Request{
	int value;
	String desc;
	
	public Request(int value, String desc)
	{
		this.value = value;
		this.desc = desc;
	}
	
	public int getValue() {
		return value;
	}
	public void setValue(int value) {
		this.value = value;
	}
	public String getDesc() {
		return desc;
	}
	public void setDesc(String desc) {
		this.desc = desc;
	}	
}

abstract class Handler{
	Handler scsr;
	
	public void setSuccessor(Handler scsr)
	{
		this.scsr = scsr;
	}
	
	public abstract void handleRequest(Request rqs);
}

class ConcreteHandlerOne extends Handler{
	public void handleRequest(Request rqs)
	{
		if(rqs.getValue()<0)
		{
			System.out.println(" Handling Request details<0:"+rqs.getValue()+" "+rqs.getDesc());
		}
		else
		{
			scsr.handleRequest(rqs);
		}
	}
}

class ConcreteHandlerTwo extends Handler{
	public void handleRequest(Request rqs)
	{
		if(rqs.getValue()>0)
		{
			System.out.println("Handling Request details>0:"+rqs.getValue()+" "+rqs.getDesc());
		}
		else
		{
			scsr.handleRequest(rqs);
		}
	}
}

class ConcreteHandlerThree extends Handler{
	public void handleRequest(Request rqs)
	{
		if(rqs.getValue()==0)
		{
			System.out.println("Handling Request details==0:"+rqs.getValue()+" "+rqs.getDesc());
		}
		else
		{
			scsr.handleRequest(rqs);
		}
	}
}

public class CoREg {
	public static void main(String[] args) {
		Handler h1 = new ConcreteHandlerOne();
		Handler h2 = new ConcreteHandlerTwo();
		Handler h3 = new ConcreteHandlerThree();
		
		h1.setSuccessor(h3);
		h3.setSuccessor(h2);
		
		Request req = new Request(25, "Test Purpose");
		h1.handleRequest(req);
		
		Request reqn = new Request(-25, "Test Purpose");
		h1.handleRequest(reqn);
	}
}

Mini Project – 1

Develop a mini project, a console based Java Application, which can provide below options to manage Employee details in Database.

1. Create New Employee.
2. Delete an Employee, based on Employee ID
3. View Details of an Employee, based on Employee ID
4. View Details of all Employee
5. Exit from Application.

Whenever user selects an option, that specific Task need to be performed, and again above options need to be displayed, until user selects option 5, above.

import java.io.BufferedReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;
import java.io.*;

public class Project {
	public static void main(String[] args) throws IOException {
		Scanner scanner=new Scanner(System.in);
		BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
		
		int choice='5';
		try{
			Class.forName("com.mysql.jdbc.Driver");
			Connection con=DriverManager.getConnection("jdbc:mysql://localhost/companydetails","root","cherry");
		System.out.println("Connection is Established...");
		System.out.println("\n");
		Statement st=con.createStatement();
		do{
			System.out.println("Employees Menu");
			System.out.println("1.To Create New Employees.");
			System.out.println("2.To Delete An Employees.");
			System.out.println("3.To Display Details of one Employees.");
			System.out.println("4.To Display Details of all Employees.");
			
			System.out.println("5.Exit.");
			System.out.println("Enter Your Choice.");
			choice=scanner.nextInt();
			switch(choice)
			{
			case 1:
				System.out.println("Enter Employees id");
				System.out.println("Enter Employees Name");
				System.out.println("Enter Employees salary");
				System.out.println("Enter Employees Age");
				String eid = br.readLine();
				String ename = br.readLine();
				String esalary=br.readLine();
				String eage=br.readLine();
				st.executeUpdate("insert into employees values(eid,'"+ename+"',"+eage+" ,"+esalary+" )");
				System.out.println("Succesfully Employees Added.");
				
			case 2:
				System.out.println("Enter Employees id");
			    String Eid = br.readLine();
				st.executeUpdate("delete from employees where eid="+Eid);
				System.out.println("Succesfully Employees Deleted.");
				break;
			case 3:
				System.out.println("Enter Employees id");
			    String Eid1 = br.readLine();
				//st.executeQuery("select * from employees where eid="+Eid1);
				Statement st4=con.createStatement();
            	
            	String sql5="select eid,ename,eage,esalary from employees where eid="+Eid1+"";
            	
            	ResultSet rs5=st4.executeQuery(sql5);
            while(rs5.next())
            	{
            		
            		int id1=rs5.getInt("eid");
            		
            		String name=rs5.getString("ename");
            		
            		int age=rs5.getInt("eage");
            		
            		int salary=rs5.getInt("esalary");
            		
            		System.out.println("Emp Id:"+Eid1);
            		
            		System.out.println("Emp Name:"+name);
            		
            		System.out.println("Emp Age:"+age);
            		
            		System.out.println("Emp Salary:"+salary);
            		
            		System.out.println("Verification sucessfull!!!");
            	}
            		break;
			
			case 4:
				ResultSet rs=st.executeQuery("select * from employees");
				while(rs.next())
				{
					System.out.println(rs.getInt(1)+"\t\t"+rs.getString(2)+"\t\t"+rs.getInt(3)+"\t\t"+rs.getInt(4));
				}
				break;
			}
		}while(choice!=6);
		con.close();
		}catch(ClassNotFoundException e)
		{
			e.printStackTrace();
			
		}catch(SQLException e)
		{
			e.printStackTrace();
			}

	}
		
	}

How to set or change priority of Main Thread?

As already specified, you need to use setPriority() and getPriority() methods of Thread class to change and to retrieve priority of a Thread. However, first we need to get the Thread object of main Thread. This can be achieved using Thread.getCurrentThread(), which returns Thread object of the current Thread. Below is snippet of code

public class MainThreadPriority {
	public static void main(String[] args) {
		Thread t = Thread.currentThread();
		
		System.out.println("Priority of "+t.getName()+" thread is: "+t.getPriority());
		
		t.setPriority(Thread.MAX_PRIORITY - 2);
		
		System.out.println("Now, Priority of "+t.getName()+" thread is: "+t.getPriority());
	}
}

You may also like to read:
All Threads examples

Hibernate HQL, how to retrieve selected fields

Below example code shows how to retrieve selected fields from database. As shown below a List of Object[] is being returned, by session.query(“SELECT Y.firstName, Y.lastName FROM Employee Y WHERE Y.salary >9000”);

Then List need to be iterated, in which each element is an Object array of size 2(since only two fields are being selected). You can download full NetBeans project sour code here.

import org.hibernate.HibernateException; 
import org.hibernate.Transaction;
import org.hibernate.Session;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HQLManageEmployee {
   private static SessionFactory factory; 
   public static void main(String[] args) {
      try{
          //step 1: Create Session Factory
         factory = new Configuration().configure().buildSessionFactory();
      }catch (Throwable ex) { 
         System.err.println("Failed to create sessionFactory object." + ex);
         throw new ExceptionInInitializerError(ex); 
      }
      HQLManageEmployee ME = new HQLManageEmployee();

      /* List down all the employees */
      ME.listEmployees();
   }

   /* Method to  READ all the employees */
   public void listEmployees( ){
      Session session = factory.openSession();
      Transaction tx = null;
      try{
         tx = session.beginTransaction();

         Query qry = session.createQuery("SELECT Y.firstName, Y.lastName FROM Employee Y WHERE Y.salary >9000");

          List<Object []> employees = qry.list(); 
         for (Iterator iterator = 
                           employees.iterator(); iterator.hasNext();){
            Object [] emp =  (Object [])iterator.next(); 

            System.out.println(emp[0]+" --- "+emp[1]);
         }
         tx.commit();
      }catch (HibernateException e) {
         if (tx!=null) tx.rollback();
         e.printStackTrace(); 
      }finally {
         session.close(); 
      }
   }
}

Example HibernateHQL

Facade Design Pattern

A Design Pattern is a documented and prooven design solution, which can be used to solve commonly occurring Design Problems.

A Facade Design Pattern is providing Simple, Single Unified interface to a set of classes. Below is an example of the same.

As shown in below diagram, an Application is directly dependent on Display, FileSystem, Networking etc….we are assuming each of these services are provided by corresponding class. Without using Facade Pattern, Application is directly dependent on the classes.

But by re designing above solution by using facade Pattern, Application is not directly dependent on each of individual classes, Hence any change in the public methods exposed by the individual class or change of class, may not directly impact Application. If any changes in the individual classes, changes need to be performed in the UnifiedAPI, and hence Application need not be changed.

Facade Pattern
Facade Pattern



class FileSystem{

   public void readFile() {
      System.out.println("readFile() in FileSystem");
   }
}

class Network {

   public void sendData() {
      System.out.println("sendData() in Network");
   }
}


class Display {

   public void draw() {
      System.out.println("draw() in Display");
   }
}

class AppLifeCycle {

   public void startApp() {
      System.out.println("startApp() in AppLifeCycle");
   }
}

interface OSAPI{
    public void readFileOS();
    public void sendDataOS();
    public void startAppOS();
    public void drawOS(); 
}

class FacadeClass implements OSAPI{
      public void readFileOS(){
          new FileSystem().readFile();
      }
      
    public void sendDataOS(){
            new Network().sendData();
    }
    
    public void startAppOS(){
        new AppLifeCycle().startApp();
    }
    
    public void drawOS(){
        new Display().draw();
    }
}

public class FacadePattern1 {
   public static void main(String[] args) {
      FacadeClass obj = new FacadeClass();

      obj.drawOS();
      obj.readFileOS();
      obj.sendDataOS();
      obj.startAppOS();
   }
}

purpose of wait() and notify() methods in Object class

As briefed in all methods of Object class these methods are final and defined in java.lang.Object class. Hence these methods are available in each and every class, because Object class is base class of all classes, in Java. These methods can be invoked only from synchronized block or synchronized method.
wait(); – It tells the calling thread to give up the lock and go to sleep until some other thread calls notify() method on same object.
notify(); -It wakes up one single thread that called wait() on the same object.
notifyAll(); – It wakes up all the threads that called wait() on the same object.
These methods can be used to solve producer consumer related problems.

Below is simple example in which Main thread invokes wait() on threadb, after threadb computes total sum, it invokes notify() method, so that Main thread gets the control, and prints total value.

public class NotifyWait {
	public static void main(String[] args) {
		NotifyWaitB b = new NotifyWaitB();
		b.start();
			synchronized(b){
			try{
				System.out.println("A:waiting for b thread to complete...");
				b.wait();
			}catch(Exception e) {
				System.out.println("Interrupted Exception:"+e.getMessage());
				//e.printStackTrace();
			}		
			System.out.println("Total is:"+b.total);
		}
	}
}


class NotifyWaitB extends Thread{
	int total;	
	public void run(){		
		System.out.println("in run() method of Child thread");
		synchronized(this)
		{
			for(int i=0;i<30;i++)
			{
				total += i;				
			}			
			notify();
			System.out.println("notify() invoked from Child thread");
		}		
	}
}

Below is some real time example on using wait() and notify() methods.

wait-notify-notifyall-example
wait-notify-notifyall-example

Here Display Thread, need to continuously check(with a infinite loop or so) Packet Queue, to find if new Packets are available, which may not be a professional approach. As continuously checking Packet Queue, may waste CPU time, and may adversely affect performance of overall Application. This problem can be solved better, by using wait() and notify(). Below are the steps involved…

Downloader Thread downloads packets, adds to Queue.
Calls notify() method on Queue, which wakes up Display Thread.

Now display Thread reads packets from Queue, processes them.
Calls wait() method on Queue, which goes on sleep, until notify() is called by Downloader Thread.

You may also like to read:
how to use join() method between child threads?
how to avoid deadlock in threads
can a child thread start another child thread?