
Introduction
In this section, we are giving few java interview programs faced by some of my friends. If you come across any questions, post it to me. I can provide solutions. You can email me at dknitk@rediffmail.com.
How to reverse Singly Linked List?
We develop custom object to store data as singly linked list. please find code below –
package com.knowledgewala.interview;
/**
* This method helps to create Signally Linked List and reverse that LinkedList.
*/
import java.util.logging.Logger;
public class KWRevereseSingleLinkedList {
// Logger object to log data
Logger logger = Logger.getLogger(KWRevereseSingleLinkedList.class.getName());
/**
* This method helps to execute program.
*/
public static void main(String[] args) {
// Instantiate SinglyLinkedList Object
SinglyLinkedList singlyLinkedList = new SinglyLinkedList();
// Add records to Singly Linked List
singlyLinkedList.addAtEnd(144l);
// Add records to Singly Linked List
singlyLinkedList.addAtEnd(142l);
// Add records to Singly Linked List
singlyLinkedList.addAtEnd(1441l);
// Add records to Singly Linked List
singlyLinkedList.addAtEnd(120l);
// Add records to Singly Linked List
singlyLinkedList.addAtEnd(112l);
// Add records to Singly Linked List
singlyLinkedList.addAtEnd(125l);
// Call method to display Singly Linked List
singlyLinkedList.display();
// Call method to reverse Linked List
singlyLinkedList.reverseLinkedList();
System.out.println("Linked List After Rever!");
// Call method to display Linked List
singlyLinkedList.display();
}
}
/**
* This class helps to implement Linked List related methods.
*
* @author dsahu1
*
*/
class SinglyLinkedList {
Logger logger = Logger.getLogger(SinglyLinkedList.class.getName());
private Node start;
private Node end;
private int size;
SinglyLinkedList() {
start = null;
end = null;
size = 0;
}
public void addAtEnd(Long value) {
Node currentNode = new Node(value, null);
size++;
if (start == null) {
start = currentNode;
end = start;
} else {
end.setNextNode(currentNode);
end = currentNode;
}
}
public void display() {
if (size == 0 && start == null) {
logger.info("Linked List empty!");
}
if (start.getNextNode() == null) {
// logger.info(start.getValue().toString());
System.out.println(start.getValue().toString());
}
Node pre = start;
while (pre != null) {
// logger.info(pre.getValue().toString());
System.out.println(pre.getValue().toString());
pre = pre.getNextNode();
}
}
public Node reverseLinkedList() {
if (start == null && end == null) {
System.out.println("No Data to reverse!");
return null;
}
Node pre = null;
Node current = start;
Node next = null;
while (current != null) {
next = current.getNextNode();
current.setNextNode(pre);
pre = current;
current = next;
}
start = pre;
return pre;
}
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
}
/**
* This class helps to Construct Singly Linked List Object.
*
* @author dsahu1
*
*/
class Node {
// Attribute to store value
private Long value;
// Attribute to store next object
private Node next;
// Constructor
Node(Long value, Node next) {
this.value = value;
this.next = next;
}
public Long getValue() {
return value;
}
public void setValue(Long value) {
this.value = value;
}
public Node getNextNode() {
return next;
}
public void setNextNode(Node nextNode) {
this.next = nextNode;
}
}
Program Output:
[Console output redirected to file:C:\KW\LogFile.txt]
144
142
1441
120
112
125
Linked List After Rever!
125
112
120
1441
142
144
Find out duplicate number between 1 to N numbers.
This program helps to find out duplicate records exist in the list. We can write program using API like Set to filter out duplicate records but we did not use that simple way as it is uses Java api and interviewer wants some code from your side in place of direct api. May be below code is not perfect as we used List to add records, please try to make it using array and upload that code in the program. We will add more ways to write program for this ASAP.
KWFindDuplicateNumber.java
package com.knowledgewala.interview;
import java.util.ArrayList;
import java.util.List;
/**
* This class helps to find duplicate records from the list. We are not using any available api like contain etc.
*
* @author dsahu1
*
*/
public class KWFindDuplicateNumber {
/**
* This method helps to execute program.
*
* @param args
*/
public static void main(String[] args) {
System.out.print("**** Find Duplicate Number Program ****");
int totalNumberOfRecords = 30;
List<Integer> listOfNumber = new ArrayList<Integer>();
System.out.println("\n**** Before Removing Duplicate Records *****");
for (int i = 0; i < totalNumberOfRecords; i++) {
listOfNumber.add((int) Math.round(Math.random() * 100));
}
// Call method to display records
displayListOfRecords(listOfNumber);
// Instantiate attribute to store duplicate records
List<Integer> listOfNumberDuplicate = new ArrayList<Integer>();
// Call methods to search Duplicate records and return unique records
List<Integer> listOfNumberUnique = searchDuplicateRecords(listOfNumber,listOfNumberDuplicate);
System.out.println("\n**** After Removing Duplicate Records *****");
// Call method to display records
displayListOfRecords(listOfNumberUnique);
System.out.println("\n**** Duplicate Records *****");
// Call method to display records
displayListOfRecords(listOfNumberDuplicate);
}
/**
* This method helps to search Duplicate Records and removing duplicate records from the list. It will return the list
* of unique numbers.
*
* @param listOfNumber
* - Contains List of Numbers
* @param listOfNumberDuplicate
*/
public static List<Integer> searchDuplicateRecords(List<Integer> listOfNumber, List<Integer> listOfNumberDuplicate) {
// Attribute to hold unique records
List<Integer> tempListOfNumber = new ArrayList<Integer>();
// Iterate number and find out duplicate
for(Integer num : listOfNumber){
// Call method to check duplicate
if(!contain(tempListOfNumber, num)){
tempListOfNumber.add(num);
}else{
if(!contain(listOfNumberDuplicate, num)){
listOfNumberDuplicate.add(num);
}
}
}
return tempListOfNumber;
}
/**
* This method helps to check records already available or not.
* We can use List method contain also.
* @param listOfNumber
* @param num
* @return Boolean
*/
public static Boolean contain(List<Integer> listOfNumber, Integer num){
// Iterate records to check already exist or not.
for(Integer tempNum : listOfNumber){
if(tempNum == num){
return Boolean.TRUE.booleanValue();
}
}
return Boolean.FALSE.booleanValue();
}
/**
* This method helps to display records from the list.
*
* @param listOfNumber
*/
public static void displayListOfRecords(List<Integer> listOfNumber){
int counter = 0;
for (Integer number : listOfNumber) {
counter++;
if (counter == listOfNumber.size()) {
System.out.print(number);
} else {
System.out.print(number + " ,");
}
}
}
}
Program Output: User can execute this program using command prompt as well as using eclipse. We execute using eclipse, please find output below –
**** Find Duplicate Number Program ****
**** Before Removing Duplicate Records *****
42 ,90 ,60 ,40 ,67 ,69 ,7 ,40 ,38 ,7 ,33 ,59 ,77 ,58 ,33 ,16 ,63 ,53 ,64 ,6 ,85 ,36 ,2 ,19 ,96 ,43 ,93 ,41 ,74 ,94
**** After Removing Duplicate Records *****
42 ,90 ,60 ,40 ,67 ,69 ,7 ,38 ,33 ,59 ,77 ,58 ,16 ,63 ,53 ,64 ,6 ,85 ,36 ,2 ,19 ,96 ,43 ,93 ,41 ,74 ,94
**** Duplicate Records *****
40 ,7 ,33
Find out middle index where sum of both ends are equal
You are given an array of numbers. Find out the array index or position where sum of numbers preceding the index is equals to sum of numbers succeeding the index.
KWMiddleInxWhenBothSideEql.java
package com.knowledgewala.interview;
/**
* This class helps to find out index from where sum of right and left element equal.
*
* @author dsahu1
*
*/
public class KWMiddleInxWhenBothSideEql {
/**
* This method helps to execute program.
*
* @param args
*/
public static void main(String[] args){
System.out.println(" Program to find middle index when both Side equal");
Integer[] num = { 2, 3, 2, 3, 4, 4, 5, 4, 1 };
try {
Integer index = findOutIndexWhenSomeEql(num);
System.out.println("Index Number is :"+index);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* This method helps to find out index number.
*
* @param numberArrays
* @return Integer
* @throws Exception
*/
public static Integer findOutIndexWhenSomeEql(Integer[] numberArrays) throws Exception{
// Attribute to hold leftIndex
Integer leftIndex = 0;
// Attribute to hold rightIndex
Integer rightIndex = numberArrays.length-1;
// Attribute to hold sum of Left elements
Integer sumLeft = 0;
// Attribute to hold sum of Right elements
Integer sumRight = 0;
// Iterate Arrays
while(true){
// Check sum of left left elements with sum of right elements
if(sumLeft > sumRight){
sumRight += numberArrays[rightIndex--];
}else{
sumLeft += numberArrays[leftIndex++];
}
// Check leftIndex with right index
if(leftIndex > rightIndex){
if(sumLeft == sumRight){
break;
}else {
throw new Exception(
"Please pass proper array to match the requirement");
}
}
}
return rightIndex;
}
}
Program Output: User can execute this program using command prompt as well as using eclipse. We execute using eclipse, please find output below –
First Run: Program to find middle index when both Side equal Index Number is :4
Second Run: Integer[] num = { 2, 3, 2, 3, 3, 4, 4, 5, 4, 1 };
Program to find middle index when both Side equal java.lang.Exception:
Please pass proper array to match the requirement at com.knowledgewala.interview.KWMiddleInxWhenBothSideEql.findOutIndexWhenSomeEql(KWMiddleInxWhenBothSideEql.java:55)
at com.knowledgewala.interview.KWMiddleInxWhenBothSideEql.main(KWMiddleInxWhenBothSideEql.java:20)
A Singleton class
In software engineering, the singleton pattern is a design pattern that restricts the instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system.
Example 1:
package patterns.singleton;
public class SimpleSingleton {
private static SimpleSingleton simpleSingleton = new SimpleSingleton();
private SimpleSingleton(){
}
public static SimpleSingleton getInstance(){
return simpleSingleton;
}
}
package patterns.singleton;
public class RunSingleton {
public static void main(String args[]){
SimpleSingleton simpleSingleton = SimpleSingleton.getInstance();
System.out.println("Instance 1"+simpleSingleton);
SimpleSingleton simpleSingleton2 = SimpleSingleton.getInstance();
System.out.println("Instance 2"+simpleSingleton2);
}
}
Example 2:
package com.knowledgewala.interview;
public class KWLazyInitializedSingleton {
private static KWLazyInitializedSingleton instance;
private KWLazyInitializedSingleton(){}
public static KWLazyInitializedSingleton getInstance(){
if(instance == null){
instance = new KWLazyInitializedSingleton();
}
return instance;
}
}
package com.knowledgewala.interview;
public class KWThreadSafeSingleton {
private static KWThreadSafeSingleton instance;
private KWThreadSafeSingleton(){}
public static synchronized KWThreadSafeSingleton getInstance(){
if(instance == null){
instance = new KWThreadSafeSingleton();
}
return instance;
}
}
Program Output: User can execute this program using command prompt as well as using eclipse. We execute using eclipse, please find output below –
Example1:
Instance 1com.knowledgewala.interview.SimpleSingleton@3d4b7453
Instance 2com.knowledgewala.interview.SimpleSingleton@3d4b7453
Write a program to create deadlock between two threads
Deadlock is a programming situation where two or more threads are blocked forever, this situation arises with at least two threads and two or more resources. Here I have written a simple program that will cause deadlock scenario and then we will see how to analyze it.
KWCrunchifyThreadDeadLock.java
package com.knowledgewala.interview;
/**
* This method helps to create DeadLock program.
*
* @author dsahu1
*
*/
public class KWCrunchifyThreadDeadLock {
/**
* This method helps to execute program.
*
* @param args
* @throws InterruptedException
*/
public static void main(String[] args) throws InterruptedException {
Object obj1 = new Object();
Object obj2 = new Object();
Object obj3 = new Object();
Thread crunchifyThread1 = new Thread(new CrunchifySynchronizeThread(obj1, obj2), "crunchifyThread1");
Thread crunchifyThread2 = new Thread(new CrunchifySynchronizeThread(obj2, obj3), "crunchifyThread2");
Thread crunchifyThread3 = new Thread(new CrunchifySynchronizeThread(obj3, obj1), "crunchifyThread3");
crunchifyThread1.start();
Thread.sleep(3000);
crunchifyThread2.start();
Thread.sleep(3000);
crunchifyThread3.start();
}
}
class CrunchifySynchronizeThread implements Runnable {
private Object obj1;
private Object obj2;
public CrunchifySynchronizeThread(Object obj1, Object obj2) {
this.obj1 = obj1;
this.obj2 = obj2;
}
@Override
public void run() {
String name = Thread.currentThread().getName();
synchronized (obj1) {
System.out.println(name + " acquired lock on Object1: " + obj1);
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (obj2) {
System.out.println(name + " acquired lock on Object2: " + obj2);
}
System.out.println(name + " released lock on Object2: " + obj2);
}
System.out.println(name + " released lock on Object1: " + obj1);
System.out.println(name + " Finished Crunchify Deadlock Test.");
}
}
Program Output: User can execute this program using command prompt as well as using eclipse. We execute using eclipse, please find output below –
crunchifyThread1 acquired lock on Object1: java.lang.Object@1cc2ea3f
crunchifyThread2 acquired lock on Object1: java.lang.Object@1034bb5
crunchifyThread3 acquired lock on Object1: java.lang.Object@5b86d4c1