Java Interview Questions - 4



Java Interview Questions


In this tutorial we will see about few simple interview programming questions.

1. Sort 3 numbers without IF condition or looping.


public class Sort3No {
 public static void main(String[] args) {
  int x = 9;
  int y = 3;
  int z = 7;

  int first = Math.min(x, Math.min(y, z));
  int third = Math.max(x, Math.max(y, z));
  int second = x + y + z - first - third;

  System.out.println("SORTED NO's : " + first + ", " + second + ", "+ third);
 }
}


OUTPUT:

SORTED NO's : 3, 7, 9





2. Reverse the number without using String


public class ReverseNumber {
 
 public static void main(String[] args) {
  
  int number = 123456;

  int revNo = 0;
  while(number > 0){
   revNo = (10 * revNo) + (number % 10);
   number = number / 10;
  }
  
  System.out.println("REVERSED NO : "+revNo);
 }
}


OUTPUT:

REVERSED NO : 654321





3. Print first N Fibonacci numbers.


public class Fibonacci {

  public static void main(String[] args) { 
       int input = 10;
       int fib = 0,  val= 1;
       System.out.print("First "+input+" Fibonacci Numbers : ");
       for (int i = 0; i < input; i++) {
          fib = fib + val;
          val = fib - val;
          System.out.print(fib+", "); 
       }
  }
}


OUTPUT:

First 10 Fibonacci Numbers : 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 





4. Convert String to Date Object 


public class StringToDate {
 
 public static void main(String args[]) {
  try{
         String strDate = "23-5-2013";

         SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
         Date date = format.parse(strDate);
         System.out.println("DATE : "+date);
  }catch (ParseException e) {
   e.printStackTrace();
  }
    }
}


OUTPUT:

DATE : Thu May 23 00:00:00 IST 2013





5. Find entered date is valid or not


public class ValidDate {

 public static void main(String[] args) {

  int day = 29;
  int month = 2;
  int year = 1984;

  int[] leapYearDays = { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
  int[] nonLeapYearDays = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };

  if (month >= 1 && month <= 12) {
   if (year % 4 == 0) {
    if (day >= 1 && day <= leapYearDays[month - 1]) {
     System.out.println("Valid Date...");
    } else {
     System.out.println("Invalid Date");
    }
   } else {
    if (day >= 1 && day <= nonLeapYearDays[month - 1]) {
     System.out.println("Valid Date...");
    } else {
     System.out.println("Invalid Date");
    }
   }
  } else {
   System.out.println("Invalid Date");
  }
 }
}


OUTPUT:

Valid Date...





6. Find the day of week by given date.


public class DayOfWeek {

 public static void main(String[] args) {

  int day = 23;
  int month = 5;
  int year = 2013;

  String days[] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };

  int a = year - (14 - month) / 12;
  int x = a + a / 4 - a / 100 + a / 400;
  int b = month + 12 * ((14 - month) / 12) - 2;
  int c = (day + x + (31 * b) / 12) % 7;

  System.out.println(days[c]);
 }
}


OUTPUT:

Thursday





7. Print 5 random numbers between 2 numbers


public class PrintRandom {
 
 public static void main(String[] args) {
  
  int min = 100;
  int max = 200;
  
  for(int i=0;i<5;i++){
   int rand = new Random().nextInt(max);
   if(rand > min){
    System.out.println(rand);
   }else{
    i--;
   }
  }
 }
}


OUTPUT:

122
180
193
114
187





8. Replace character in a string without using Java API functions


public class ReplaceChar {

 public static void main(String[] args) {
  String str = "This document is the API specification for version 6 of the Java";
  System.out.println("INPUT              : "+str);
  str = replaceChar(str, 'Q', 'i'); // Change all 'i' to 'Q' 
  System.out.println("AFTER CHAR REPLACE : "+str);
 }
 
 public static String replaceChar(String str, char newChar, char oldChar){
  try{
   char[] charAry = str.toCharArray();
   for(int i=0;i<str.length();i++){
    if(charAry[i] == oldChar){
     charAry[i] = newChar;
    }
   }
   str = new String(charAry);
  }catch (Exception e) {
   e.printStackTrace();
  }
  return str;
 }
}


OUTPUT:

INPUT               : This document is the API specification for version 6 of the Java
AFTER CHAR REP: ThQs document Qs the API specQfQcatQon for versQon 6 of the Java





9. Write a Java program to find given number is odd or even without / or % operators. 


public class OddOrEven {
 
 public static void main(String[] args) {
  int no = 25;
  while(no>2){
   no -= 2;
  }
  if(no == 1){
   System.out.println("Given no. is Odd Number...");
  }else{
   System.out.println("Given no. is Even Number...");
  }
 }
}


OUTPUT:

Given no. is Odd Number...





10.  This is a simple mathematical calculation program. 
    
Example: Raj purchased the bag for Rs.2750 which includes 10% tax of bag price. So what will be the price of bag and tax amount?. Program should work for whatever be the amount as input.


public class CalculatePrice {
 
 public static void main(String[] args) {
  int price = 2750;
  float bagPrice = ((price/11f)*10f);
  float taxAmt = (price/11f);
  System.out.println("BAG PRICE   : "+bagPrice);
  System.out.println("TAX AMOUNT  : "+taxAmt);
  System.out.println("TOTAL PRICE : "+(bagPrice+taxAmt));
 }
}


OUTPUT:

BAG PRICE   : 2500.0
TAX AMOUNT  : 250.0
TOTAL PRICE : 2750.0










Create ZIP File using Java Code

 


Create ZIP File using Java Code



We seen how to unzip a ZIP file using Java code in our earlier tutorial, now we will see how to create a ZIP file using Java code in this tutorial. Below sample code will read list of files in a folder and zip file name as input parameters. 



import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class CreateZIPFile {

 public static void main(String argv[]) {
  // List of files in a folder to zip
  String filesPath = "D:\\filesfolder";
  // ZIP file name and path to create
  String zipFileName = "D:\\myZipFile.zip";
  
  createZIPFile(filesPath, zipFileName);
 }
 
 public static void createZIPFile(String filesPath, String zipFileName){

  try {
  
   FileOutputStream dest = new FileOutputStream(zipFileName);
   ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(dest));

   byte buffer[] = new byte[1024];
   File file = new File(filesPath);
   String files[] = file.list();
   System.out.println("No. of files to ZIP : "+files.length);
   BufferedInputStream bis = null;
   for (int i = 0; i < files.length; i++) {
    FileInputStream fi = new FileInputStream(filesPath+ "\\"+ files[i]);
    bis = new BufferedInputStream(fi, 1024);
    ZipEntry entry = new ZipEntry(files[i]);
    out.putNextEntry(entry);
    int count;
    while ((count = bis.read(buffer, 0, 1024)) != -1) {
     out.write(buffer, 0, count);
    }
    bis.close();
   }
   out.close();
  } catch (Exception e) {
   e.printStackTrace();
  }
 }
}









Unzip a ZIP File using Java Code

 


Unzip a ZIP File using Java Code


In this tutorial we will see about unzipping a Zip file using Java code. Below example will gives you the code to unzip a zip file by taking zip file and output folder path as input parameters. 



import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.Enumeration;

public class UnZip {

 public static final void main(String[] args) {

  // Zip file path
  String zipFile = "D:\\myZipFile.zip";

  // Output folder to save the unzip files
  String outputFolder = "D:\\unzipfolder\\";
  
  unzipFile(zipFile, outputFolder);

 }
 
 public static void unzipFile(String zipFile, String outputFolder){
  
  ZipFile zFile = null;

  try {
   zFile = new ZipFile(zipFile);
   Enumeration zEntries = zFile.entries();

   while (zEntries.hasMoreElements()) {
    ZipEntry zipEntry = (ZipEntry) zEntries.nextElement();

    // Check for Directory or not
    if (zipEntry.isDirectory()) {
     // Creating directory
     (new File(zipEntry.getName())).mkdir();
     continue;
    }

    // Unzipping files
    createUnzipFile(zFile.getInputStream(zipEntry),
      new BufferedOutputStream(new FileOutputStream(
        outputFolder + zipEntry.getName())));
   }
   zFile.close();
  } catch (IOException e) {
   e.printStackTrace();
  
  } 
 }

 public static final void createUnzipFile(InputStream iStream,
   OutputStream oStream) {
  try {
   byte[] buffer = new byte[1024];
   int len;
   while ((len = iStream.read(buffer)) >= 0)
    oStream.write(buffer, 0, len);

  iStream.close();
  oStream.close();
  } catch (Exception e) {
   e.printStackTrace();
 
  } 
 }
}






DOM and SAX Parser


In this tutorial we will see about DOM and SAX parser along with simple Java code to parse the XML. 

Common XML document which we are going to use for both DOM and SAX parser are 


SAMPLE XML:
<?xml version="1.0" encoding="UTF-8"?>
<organization>
 <employee mode="permanent">
  <name>John</name>
  <empid>1234</empid>
  <designation>SE</designation>
  <technology>Java</technology>
 </employee>
 <employee mode="contract">
  <name>David</name>
  <empid>4545</empid>
  <designation>Manager</designation>
  <technology>.NET</technology>
 </employee>
</organization>


DOM Parser:

Document Object Model (DOM) parser will creates a complete tree structure in memory from the XML provided and reads each node values as and when required. 

The advantage of DOM parser is provided with lot of rich functionality where developers can make use without any additional coding. Also when the document loaded into memory developers can access any part of the DOM tree and can modify.

Disadvantages are need more memory in case of huge document in size. 
it takes a little bit longer to learn how to work with it.



DOM Parser for above XML document:



import java.io.File;
import java.io.IOException;
import org.w3c.dom.*;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.ParserConfigurationException;
import org.xml.sax.SAXException;

public class DOMParser {

 public static void main(String[] args) {
  String file = "document.xml";
  
  parseXMLUsingDOM(file);
 }
 
 public static void parseXMLUsingDOM(String file){
  
  try {
   DocumentBuilderFactory builderFac = DocumentBuilderFactory.newInstance();
   DocumentBuilder builder = builderFac.newDocumentBuilder();
      Document doc = builder.parse(new File(file));

      System.out.println ("ROOT: " + doc.getDocumentElement().getNodeName());
            NodeList list = doc.getElementsByTagName("employee");
            System.out.println("No. Of Employees: " + list.getLength());
            
            for(int i= 0; i<list.getLength(); i++){
                    Node node = list.item(i);
                    if(node.getNodeType() == Node.ELEMENT_NODE) {
                        Element element = (Element)node;
                        System.out.println("\nEMP MODE: "+element.getAttribute("mode"));
                        
                        NodeList nList = element.getElementsByTagName("name");
                        Element nElement = (Element)nList.item(0);
                        NodeList tList = nElement.getChildNodes();
                        System.out.println("NAME: " + ((Node)tList.item(0)).getNodeValue().trim());
                        
                        nList = element.getElementsByTagName("empid");
                        nElement = (Element)nList.item(0);
                        tList = nElement.getChildNodes();
                        System.out.println("EMP_ID: " + ((Node)tList.item(0)).getNodeValue().trim());
                        
                        nList = element.getElementsByTagName("designation");
                        nElement = (Element)nList.item(0);
                        tList = nElement.getChildNodes();
                        System.out.println("DESIGNATION: " + ((Node)tList.item(0)).getNodeValue().trim());
                        
                        nList = element.getElementsByTagName("technology");
                        nElement = (Element)nList.item(0);
                        tList = nElement.getChildNodes();
                        System.out.println("TECHNOLOGY: " + ((Node)tList.item(0)).getNodeValue().trim());
                    }
            }            
     } catch (ParserConfigurationException e) {
      e.printStackTrace();  
  } catch (SAXException e) {
      e.printStackTrace();
  } catch (IOException e) {
      e.printStackTrace();
  } 
 }
}


OUTPUT:

ROOT: organization
No. Of Employees: 2

EMP MODE: permanent
NAME: John
EMP_ID: 1234
DESIGNATION: SE
TECHNOLOGY: Java

EMP MODE: contract
NAME: David
EMP_ID: 4545
DESIGNATION: Manager
TECHNOLOGY: .NET



SAX Parser:

Simple API for XML (SAX) parser will not create any internal tree structure as like DOM. It just search for the component occurrences as per input and it will gives the values. Always SAX parser will read only specific document values as requested. 

As advantage SAX parser is much more space efficient in case of a huge document, because its not creating complete tree structure like DOM. Next its faster and easy to implement with basic needs. 
From functionality side it serves less as compared to DOM.


SAX Parser for above XML document:

import java.io.IOException;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class SAXParserDemo {
 
 public static void main(String[] args) {
  String file = "document.xml";
  
  parseXMLUsingSAX(file);
 }
 
 public static void parseXMLUsingSAX(String file) {
  try{
   DefaultHandler handler = createHandler();
   
   SAXParserFactory factory = SAXParserFactory.newInstance();
   SAXParser parser = factory.newSAXParser();
   
   parser.parse(file, handler);
   
  }catch (ParserConfigurationException  e) {
   e.printStackTrace();
  }catch (SAXException e) {
   e.printStackTrace();
  }catch (IOException e) {
   e.printStackTrace();
  }
 }
 
 public static DefaultHandler createHandler(){
  DefaultHandler handler = null;
  try{
   handler = new DefaultHandler(){
    boolean fName = false;
    boolean fEmpId = false;
    boolean fDesig = false;
    boolean fTech = false;
    public void startElement(String uri, String vName, String tagName, Attributes attri){
     try{
      if(tagName.equalsIgnoreCase("employee")){
       System.out.println("\nMODE: " + attri.getValue("mode"));
      }
      if(tagName.equalsIgnoreCase("name")) fName = true;
      if(tagName.equalsIgnoreCase("empid")) fEmpId = true;
      if(tagName.equalsIgnoreCase("designation")) fDesig = true;
      if(tagName.equalsIgnoreCase("technology")) fTech = true;
     }catch (Exception e) {
      e.printStackTrace();
     }     
    }
    
    public void characters(char chars[], int id, int size) throws SAXException {
     if (fName) {
      System.out.println("NAME: " + new String(chars, id, size));
      fName = false;
     }else if (fEmpId) {
      System.out.println("EMP_ID: " + new String(chars, id, size));
      fEmpId = false;
     }else if (fDesig) {
      System.out.println("DESIGNATION: " + new String(chars, id, size));
      fDesig = false;
     }else if (fTech) {
      System.out.println("TECHNOLOGY: " + new String(chars, id, size));
      fTech = false;
     }    
    }
   };
   
  }catch (Exception e) {
   e.printStackTrace();
  }
  return handler;
 }
}


OUTPUT:

MODE: permanent
NAME: John
EMP_ID: 1234
DESIGNATION: SE
TECHNOLOGY: Java

MODE: contract
NAME: David
EMP_ID: 4545
DESIGNATION: Manager
TECHNOLOGY: .NET