Actual use of interface in Java


We may come across with this interview question as "What is the actual use of interface in Java?". By this we may be thinking of, its an alternate for multiple interface which Java doesn't have and we can implement multiple interfaces in a Java class etc.,. Apart from these answers if we see in Object Oriented interface allows to use classes in different hierarchies by Polymorphism. Lets see simple example as how its works and interface used here



public interface Animal { 
 
 public int runningSpeed();
}

public class Horse implements Animal{

 @Override
 public int runningSpeed() {
  return 55;
 }
}

public class Zebra implements Animal{

 @Override
 public int runningSpeed() {
  return 40;
 }
}

public class AnimalsSpeed {
 
 public static void main(String[] args) {
  
  Animal a1 = new Horse();
  Animal a2 = new Zebra();
  
  System.out.println("Horse Speed "+a1.runningSpeed() + " mph");
  System.out.println("Zebra Speed "+a2.runningSpeed() + " mph");
  
 }
}

OUTPUT:

Horse Speed 55 mph
Zebra Speed 40 mph


If we see above example any number of classes, across class hierarchies could implement Animal interface in their own specific way. But still be used by some caller in a uniform way and by perspective of caller, it's just a Animal interface as we can see in AnimalsSpeed class. 

       Animal a1 = new Horse();
Animal a2 = new Zebra();

Welcome your comments for more use of interface in Java.




Using log4j API Logger


In each and every applications we will be seen logger to record the different types of logs like error, information, debug etc., In this tutorial we will see how to use Logger log4j API in our application and its usage. 



There are mainly 3 components like loggers, appenders and layouts. All these 3 components work together to enable developers to log messages according to message type and level and to control at run-time as how these messages are formatted and where they are stored. All these appender or logger settings will be made in the file called log4j.properties file. 

The advantage of using logger over System.out.print is to disable certain log statements while allowing others to print unhindered. This capability assumes that the logging space, that is, the space of all possible logging statements, is categorized according to some developer-chosen criteria. Loggers are named entities. Logger names are case-sensitive and they follow the hierarchical naming rule ie., "A logger is said to be an ancestor of another logger if its name followed by a dot is a prefix of the descendant logger name. A logger is said to be a parent of a child logger if there are no ancestors between itself and the descendant logger." as example given below


log4j.rootCategory=DEBUG, CONSOLE, TESTING 

log4j.logger.org.apache.commons.validator=DEBUG, CONSOLE

log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.Threshold=WARN
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=- %-5p %m%n

log4j.appender.LOGFILE=org.apache.log4j.FileAppender
log4j.appender.LOGFILE.File=/user/local/logFile.log
log4j.appender.LOGFILE.Append=true
log4j.appender.LOGFILE.Threshold=DEBUG
log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout
log4j.appender.LOGFILE.layout.ConversionPattern=%-4r [%15.15t] %-5p %c %x - %m%n

log4j.appender.TESTING=org.apache.log4j.RollingFileAppender
log4j.appender.TESTING.File=/user/local/application.log
log4j.appender.TESTING.Append=true
log4j.appender.TESTING.MaxFileSize=1024KB
log4j.appender.TESTING.MaxBackupIndex=10
log4j.appender.TESTING.layout=org.apache.log4j.PatternLayout
log4j.appender.TESTING.layout.ConversionPattern=[%d{EEE MMM d HH:mm:ss yyyy}] [%-5p] %c{1}.java(): %m%n


Set of possible logger levels are:
TRACE,
DEBUG,
INFO,
WARN,
ERROR and
FATAL

For more appenders and how to inclide in our project we can get it from the following link - http://logging.apache.org/log4j/1.2/manual.html

Now lets see simple example for how to start with the log4j API in our application with simple example to redirect all logs to a specified log file. For that first we need log4j.jar file (can use any latest version). I have used log4j-1.2.13.jar and we need to create log4j.properties file under classes directory.


log4j.rootLogger=INFO, file
 
# Direct log messages to a log file
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=D:\\logs\\application.log
log4j.appender.file.MaxFileSize=1MB
log4j.appender.file.MaxBackupIndex=10
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n



import java.util.Date;
import org.apache.log4j.Logger;

public class LogTest {

 static Logger logger = Logger.getLogger(LogTest.class.getName());
 
 public static void main(String[] args) {
  logger.info("Application starts .....................");
  
  long stime = new Date().getTime();
  
  try{
   logger.info("Process Started !!!");
   Thread.sleep(5300);
   logger.info("Process completed !!!");
  }catch (Exception e) {
   logger.error("Exception Occured : "+e.getMessage());
  }
  
  long etime = new Date().getTime();
  float diff = (float)(etime - stime)/1000;
  logger.info("Total time to complete ::: "+ diff +" second(s)");
  
  logger.info("Application Ends .......................");
 } 
}


OUTPUT:


log4j API Logger




File and Folder search through Java Code


Recently we can see most of the first round interview for experienced candidate will be written or programming test. One of the simple and easy programming question asked in interview is to search files and Folder from the given drive using java code.

Question:
Need to search File or Folder or both from the given root directory. 
Input parameters are File/Folder/Both and file to search and root directly.
Program should be run from command prompt. 
Need to use Java regular expression to match file or folder names.

By based on above conditions candidate need to write the code within an hour. In tutorial we will see a sample program for the above question.


import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class FileFolderSearch {
 
 private List<String> searchResult = new ArrayList<String>();
 private Pattern pattern;  
 private Matcher matcher; 

 public static void main(String[] args) {
  
  if(args.length < 3){
   System.err.println("Insufficient input. Please input search type and root folder");
   System.err.println("Example : FileFolderSearch <file/folder/both> <D:\\> <^*file*.j*> ");
   System.exit(0);
  }
  if(!(args[0].equalsIgnoreCase("file") || args[0].equalsIgnoreCase("folder") || args[0].equalsIgnoreCase("both"))){
   System.err.println("Invalid search type. Please enter file/folder/both");
   System.exit(0);
  }  
  File rFolder = new File(args[1]);
  if((!rFolder.isDirectory())){
   System.err.println("Invalid root folder or Folder not exisit !!!");
   System.exit(0);
  }
   
  String sType = args[0];
  String fileName = args[2];
  FileFolderSearch obj = new FileFolderSearch();
  obj.searchMyItems(rFolder, fileName, sType);
  obj.printSearchResult();
  
 }
 
 /**
  * Method to search files and folder from root directory 
  * @param target
  * @param fileName
  * @param sType
  */
 public void searchMyItems(File target, String fileName, String sType)     
    {     
        if(target != null && target.isDirectory()) {     
            File[] files = target.listFiles();  
            if (files != null) {  
                for(File file:files) {     
                        pattern = Pattern.compile(fileName);     
                        matcher = pattern.matcher(file.getName());     
                        if(matcher.find()){
                         if(sType.equalsIgnoreCase("both")){
                                searchResult.add(file.getAbsoluteFile().toString());
                         }else if(sType.equalsIgnoreCase("file") && (file.isFile()) ){
                          searchResult.add(file.getAbsoluteFile().toString());
                         }else if(sType.equalsIgnoreCase("folder") && (file.isDirectory()) ){
                          searchResult.add(file.getAbsoluteFile().toString());
                         }
                        }
                    if(file.isDirectory()){     
                     searchMyItems(file, fileName, sType);
                    }
                }     
            }  
        }     
    }    
 
 
 /**
  * Method used to search file/folder from the given root folder
  * @param sType
  * @param rFolder
  * @return
  */ 
 public void searchMyItems(String sType, File rFolder){
  try{
   File[] ff = rFolder.listFiles();
    for(int i=0;i<ff.length;i++){
     if(sType.equalsIgnoreCase("both") )
     if(new File(ff[i].getName()).isDirectory()){
      searchMyItems(sType, new File(ff[i].getName()));
     }
     System.out.println(ff[i].getName());  
    }
  }catch (Exception e) {
   e.printStackTrace();
  }
 }
 
 /**
  * Method used to print all search result items
  * @param searchResult
  */
 public void printSearchResult(){
  
  // check for no. of search items stored in list.
  if(searchResult.size() == 0){
   System.out.println("Oops, NOT FOUND !!!");
   return;
  }
  
  // Print all search items
  for (Iterator<String> iterator = searchResult.iterator(); iterator.hasNext();) {
   String string = (String) iterator.next();
   System.out.println(string);
  }
  
  System.out.println("Total no. of items found : "+searchResult.size());
 }
}


OUTPUT:


File and Folder search through Java Code





Difference between Comparator and Comparable interface in Java


Comparator and Comparable are two interfaces which used to implement Object sorting in Java. It used to sort Objects stored in any Collection classes like HashMap, HashTable, ArrayList etc., Whenever we implement Comparator interface then we need to implement compare (Object o1, Object o2) method and compareTo(Object o) method for Comparable interface. 
Going further we will discuss on differene between these 2 interface and lets see small example on how to use Comparator and Comprable interfaces. 

Difference:

  • Comparator interface used to compare any class Objects by compare (Object o1, Object o2) method, whereas Comparable interface to sort same class Objects by compareTo(Object o) method. 
  • Comparator defined in java.util package which says to use it as utility to sort Objects, while Comparable interface defined in java.lang package.
  • Comparable interface used to implement natural ordering of Object which used in Date, String and Wrapper classes in Java. If its a same class Objects then compareTo(Onject o) is a good practice to use it. 
  • Collections.sort(List) here objects will be sorted on the basis of CompareTo method in Comparable. Collections.sort(List, Comparator) here objects will be sorted on the basis of Compare method in Comparator.

Comparator Example:


import java.util.Comparator;

class Employee implements Comparator<Employee>{
 
 private String name;
 private int id;
 
 public Employee() {
 }
 
 public String getName() {
  return name;
 }
 public int getId() {
  return id;
 }
 public Employee(String name,int id){
  this.id=id;
  this.name=name;
 }
 
 // Sorting based on Employee Name
 @Override
 public int compare(Employee obj1, Employee obj2) {
     if(obj1.name.toString().compareTo(obj2.name.toString())>0){
      return 1;
     }else if(obj1.name.toString().compareTo(obj2.name.toString())<0){
      return -1;
     }else 
      return 0;     
 }
 
 // Sorting based on Employee Id
 /*@Override
 public int compare(Employee obj1, Employee obj2) {
  return obj1.id - obj2.id; 
 }*/
}



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

public class ComparatorTest  {

 public static void main(String[] args) {
  
  List <Employee>list = new ArrayList<Employee>();
  
  Employee e1 = new Employee("Raj",22);
  Employee e2 = new Employee("Anna",25);
  Employee e3 = new Employee("David",12);
  Employee e4 = new Employee("Steve",100);
  Employee e5 = new Employee("Jobs",220);
  Employee e6 = new Employee("Bond",13);
  
  list.add(e1);
  list.add(e2);
  list.add(e3);
  list.add(e4);
  list.add(e5);
  list.add(e6);
  
  Collections.sort(list, new Employee());
  
                   for (Employee contact : list) {
   System.out.println(contact.getName());
  }
 }
}


OUTPUT:


Anna
Bond
David
Jobs
Raj
Steve



Comparable Example:


public class Employee implements Comparable<Employee> {

 private String empId;
 private String empName;

 public Employee() {
 }
 
 public Employee(String empId, String empName){
  this.empId = empId;
  this.empName = empName;
 }
 
 public String getEmpId() {
  return empId;
 }
 
 public String getEmpName() {
  return empName;
 }

 @Override
 public int compareTo(Employee emp) {
  return this.empName.compareTo(emp.empName);
 }
}



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

public class CompratorTest {
 public static void main(String[] args) {
  
  List<Employee> arr = new ArrayList<Employee>();
  
  arr.add(new Employee("22","Raj"));
  arr.add(new Employee("25","Anna"));
  arr.add(new Employee("12","David"));
  arr.add(new Employee("100","Steve"));
  arr.add(new Employee("220","Jobs"));
  arr.add(new Employee("13","Bond"));
  
  //Object sort using Comparable
  Collections.sort(arr);

  Iterator<Employee> itr1 = arr.iterator();
  
  while (itr1.hasNext()) {
   Employee empobj = (Employee) itr1.next();
   System.out.println(empobj.getEmpName()+" \t\t "+empobj.getEmpId());
  }
 }
}


OUTPUT:


Anna    25
Bond    13
David    12
Jobs    220
Raj    22
Steve    100

Difference between Runnable and Callable interface in Java?

 

Runnable and Callable interface both are designed to represent task, which can be executed by any thread. Both does same task for the programmer with few difference between each other. In this tutorial we will see about difference between Runnable and Callable interface difference and when we need to use Runnable and Callable interface in our application. 

  • Runnable interface introduced in JDK 1.0, whereas Callable interface introduced in Java 5 release along with other major changes e.g. Generics, Enum, Static imports and variable argument method.
  • Since both are interface when we implement these interface we need to implement run() method from Runnable interface and call() method from Callable interface.
  • run() method didn't not return any value, whereas call() method returns Object where Callable interface is a generic parameterized interface and Type of value is provided at implementation. 
  • Callable interface can throw checked exception because it's call method throws Exception where as run() method has its limitation. 

Basically if our application needs to return any value from executor method then we need to for Callable interface than Runnable interface.

Bu keeping all these differences and usage between Runnalbe and Callable interface programmer need to be in a position to decide which interface he needs to choose for his application. 

As this is one of the important interview question asked in most of the interviews followed by multi-threading question and mostly asked in Banking domain Java interviews. 


Future and Callable in Java

 

In our previous tutorial we have see about Java Thread Pool with Executor Framework and simple example as how its works. By using same Thread pool we will see about Callable interface working in this tutorial. 

Normally we use Runnable interface to execute multi-threading in Java. Suppose if we need to get some output or return value from run() method then we can't use Runnable interface and it won't return any value.  In case if we expect threads to return a computed result then we can use java.util.concurrent.Callable interface. The Callable object allows to return values after completion of each Thread execution. The Callable object uses generics to define the type of object which is returned and we will see simple example below as how its works along with Future.

If we submit a Callable object to an Executor the framework returns an object of type java.util.concurrent.Future. This Future object can be used to check the status of a Callable and to retrieve the result from the Callable. On the Executor you can use the method submit to submit a Callable and to get a future. To retrieve the result of the future use the get() method. 


import java.util.concurrent.Callable;

public class MyCallable implements Callable<Integer> {
 
 private String name;
 
 public MyCallable(String name) {
  this.name = name;
 }
 
 @Override
 public Integer call() throws Exception {
  return name.length();
 } 
}


import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class MyCallableTest {

 public static void main(String[] args) {
  
  String names[] = {"John", "David", "Steve", "Jobs", "Bill", "Gates", "Arnold"};
  
  // Thread pool size set as "5"
  ExecutorService executor = Executors.newFixedThreadPool(5);
  List<Future<Integer>> list = new ArrayList<Future<Integer>>();
     for (int i = 0; i < names.length; i++) {
       Callable<Integer> worker = new MyCallable(names[i]);
       Future<Integer> fur = executor.submit(worker);
       list.add(fur);
     }
     
     for (int i = 0; i < names.length; i++) {
      try {
       Future<Integer> future = list.get(i);
       System.out.println("NAME : ("+names[i] + ") - LENGTH : "+future.get());
   } catch (InterruptedException e) {
    e.printStackTrace();
   } catch (ExecutionException e) {
    e.printStackTrace();
   }
     }  
 }
}

OUTPUT:


NAME : (John) - LENGTH : 4
NAME : (David) - LENGTH : 5
NAME : (Steve) - LENGTH : 5
NAME : (Jobs) - LENGTH : 4
NAME : (Bill) - LENGTH : 4
NAME : (Gates) - LENGTH : 5
NAME : (Arnold) - LENGTH : 6