Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 36

Java programs

Question-1: Write code to filter duplicate elements from an array and


print as a list?
package simple.test;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class findDuplicates {

public static void main(String[] args) {

ArrayList<String> list = new ArrayList<String>();

// Form a list of numbers from 0-9.


for (int i = 0; i < 10; i++) {
list.add(String.valueOf(i));
}

// Insert a new set of numbers from 0-5.


for (int i = 0; i < 5; i++) {
list.add(String.valueOf(i));
}

System.out.println("Input list : " + list);


System.out.println("\nFiltered duplicates : " + processList(list));
}

public static Set<String> processList(List<String> listContainingDuplicates) {

final Set<String> resultSet = new HashSet<String>();


final Set<String> tempSet = new HashSet<String>();

for (String yourInt : listContainingDuplicates) {


if (!tempSet.add(yourInt)) {
resultSet.add(yourInt);
}
}
return resultSet;
}
}

Question-2: Write code to sort the list of strings using Java


collection?
package simple.test;

import java.util.Arrays;

public class sortStrings {

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

String[] inputList = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul",


"aug", "Sep", "Oct", "nov", "Dec" };

// Display input un-sorted list.


System.out.println("-------Input List-------");
showList(inputList);

// Call to sort the input list.


Arrays.sort(inputList);

// Display the sorted list.


System.out.println("\n-------Sorted List-------");
showList(inputList);

// Call to sort the input list in case-sensitive order.


System.out.println("\n-------Sorted list (Case-Sensitive)-------");
Arrays.sort(inputList, String.CASE_INSENSITIVE_ORDER);

// Display the sorted list.


showList(inputList);
}

public static void showList(String[] array) {


for (String str : array) {
System.out.print(str + " ");
}
System.out.println();
}

Question-3: Write a function to reverse a number in Java?


package simple.test;

public class invertNumber {

public long doInvert(long number) {

long invert = 0;
while (number != 0) {
invert = (invert * 10) + (number % 10);
number = number / 10;
}
return invert;
}

public static void main(String args[]) {


long lnum = 654321;
invertNumber input = new invertNumber();

System.out.println("Input value : " + lnum);


System.out.println("Inverted value : " + input.doInvert(lnum));
}
}

Further Reading:
? Top 20 Selenium Coding Tips for Software Testers.

Question-4: Write a method to check prime no. in Java?


package simple.test;

import java.util.Scanner;

public class findPrime {

public static void main(String[] args) {


Scanner scan = new Scanner(System.in);
System.out.print("Enter an int value : ");
int input = scan.nextInt();
if (checkPrime(input)) {
System.out.println("Input value " + input + " is a prime number.");
} else {
System.out.println("Input value " + input
+ " is not a prime number.");
}
}

public static boolean checkPrime(int n) {


if (n <= 1) {
return false;
}
for (int i = 2; i < Math.sqrt(n); i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
}
Question-5: Write a Java program to find out the first two max values
from an array?
package simple.test;

public class findTwoMaxValue {


public void GetTwoMaxValues(int[] nums) {

int maxOne = 0;
int maxTwo = 0;
for (int n : nums) {
if (maxOne < n) {
maxTwo = maxOne;
maxOne = n;
} else if (maxTwo < n) {
maxTwo = n;
}

System.out.println("Max1 - " + maxOne);


System.out.println("Max2 - " + maxTwo);
}

public static void main(String[] args) {

int list[] = { 15, 24, 48, 21, 43, 11, 79, 93 };

findTwoMaxValue max = new findTwoMaxValue();


max.GetTwoMaxValues(list);
}
}

Question-6: Write a Java program to find the longest substring from a


given string which doesn’t contain any duplicate characters?
package simple.test;

import java.util.HashSet;
import java.util.Set;

public class findSubstr {

private Set<String> stringSet = new HashSet<String>();


private int lstringSet = 0;

public Set<String> findStr(String input) {

// Reset instance data.


stringSet.clear();
lstringSet = 0;
// Set a boolean flag on each char's ASCII value.
boolean[] flag = new boolean[256];
int j = 0;
char[] inputCharArr = input.toCharArray();
for (int i = 0; i < inputCharArr.length; i++) {
char c = inputCharArr[i];
if (flag[c]) {
extractSubString(inputCharArr, j, i);
for (int k = j; k < i; k++) {
if (inputCharArr[k] == c) {
j = k + 1;
break;
}
flag[inputCharArr[k]] = false;
}
} else {
flag[c] = true;
}
}
extractSubString(inputCharArr, j, inputCharArr.length);
return stringSet;
}

private String extractSubString(char[] inputArr, int start, int end) {

StringBuilder sb = new StringBuilder();


for (int i = start; i < end; i++) {
sb.append(inputArr[i]);
}
String subStr = sb.toString();
if (subStr.length() > lstringSet) {
lstringSet = subStr.length();
stringSet.clear();
stringSet.add(subStr);
} else if (subStr.length() == lstringSet) {
stringSet.add(subStr);
}

return sb.toString();
}

public static void main(String a[]) {

findSubstr substr = new findSubstr();

System.out
.println("Actual Strings ------------ | ---- Longest Non-Repeated Strings");
System.out.println("Software_Programmer"
+" | " + substr.findStr("Software_Programmer"));
System.out.println("Software_Developer_In_Test"
+ " | " + substr.findStr("Software_Developer_In_Test"));
System.out.println("developers_write_unit_tests"
+ "| " + substr.findStr("developers_write_unit_tests"));
System.out.println("javajavbasp.net"
+ " | " + substr.findStr("javajavbasp.net"));
}
}

Question-7: Write Java code to get rid of multiple spaces from a


string?
package simple.test;

import java.util.StringTokenizer;

public class removeExtraSpaces {

public static void main(String args[]){

String input = "Try to remove extra spaces.";


StringTokenizer substr = new StringTokenizer(input, " ");
StringBuffer sb = new StringBuffer();

while(substr.hasMoreElements()){
sb.append(substr.nextElement()).append(" ");
}

System.out.println("Actual string: " + input);


System.out.println("Processed string: " + sb.toString().trim());
}
}

Question-8: Write Java code to identify a number as Palindrome?


package simple.test;

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class identifyPalindrome {

public static void main(String[] args) {

try {
BufferedReader object = new BufferedReader(new InputStreamReader(
System.in));
System.out.println("Input number");
int inputValue = Integer.parseInt(object.readLine());
int n = inputValue;
int rev = 0;
System.out.println("Input value is : ");
System.out.println(" " + inputValue);
for (int i = 0; i <= inputValue; i++) {
int r = inputValue % 10;
inputValue = inputValue / 10;
rev = rev * 10 + r;
i = 0;
}
System.out.println("Post reversal : " + " ");
System.out.println(" " + rev);
if (n == rev) {
System.out.print("Input value is a palindrome.");
} else {
System.out.println("Input value is not a palindrome.");
}
} catch (Exception e) {
System.out.println("Out of Range.");
}
}
}

Question-9: Write Java code to swap two numbers without using


a temporary variable?
package simple.test;

public class smartSwapping {

public static void main(String args[]) {

int numX = 10;


int numY = 20;
System.out.println("Pre-swapping state:");
System.out.println("numX value: " + numX);
System.out.println("numY value: " + numY);

System.out.println("");

numX = numX + numY;


numY = numX - numY;
numX = numX - numY;
System.out.println("Post-swapping state:");
System.out.println("numX value: " + numX);
System.out.println("numY value: " + numY);
}
}

Question-10: Write a Java program to demonstrate string reverse with


and without StringBuffer class?
package simple.test;

public class invertString {


public String invertWithStringBuffer(String str) {

StringBuffer buffer = new StringBuffer(str);


buffer.reverse();
return buffer.toString();
}

public String invertWithoutStringBuffer(String str) {

int length = str.length();


String original = str;
String invert = "";
for (int i = length - 1; i >= 0; i--) {
invert = invert + original.charAt(i);
}
return invert;
}

public static void main(String[] args) {

invertString invertStr = new invertString();

System.out.println("Inverted String with StringBuffer class: "


+ invertStr.invertWithStringBuffer("987654321"));

System.out.println("");

System.out.println("Inverted String without StringBuffer class: "


+ invertStr.invertWithoutStringBuffer("kjihgfedcba"));
}
}

11:- Java Program to calculate GCD of two numbers


/**
* Java program to demonstrate How to find Greatest Common Divisor or GCD of
* two numbers using Euclid’s method. There are other methods as well to
* find GCD of two number in Java but this example of finding GCD of two number
* is most simple.
*
* @author Javin Paul
*/
public class GCDExample {

public static void main(String args[]){

//Enter two number whose GCD needs to be calculated.


Scanner scanner = new Scanner(System.in);
System.out.println("Please enter first number to find GCD");
int number1 = scanner.nextInt();
System.out.println("Please enter second number to find GCD");
int number2 = scanner.nextInt();
System.out.println("GCD of two numbers " + number1 +" and "
+ number2 +" is :" + findGCD(number1,number2));

/*
* Java method to find GCD of two number using Euclid's method
* @return GDC of two numbers in Java
*/
private static int findGCD(int number1, int number2) {
//base case
if(number2 == 0){
return number1;
}
return findGCD(number2, number1%number2);
}

Output:
Please enter first number to find GCD
54
Please enter second number to find GCD
24
GCD of two numbers 54 and 24 is :6

12:- java program to implement binary search?

Here is our implementation of the popular binary search algorithm in Java. Though, you
don't need to implement this algorithm if you want to use it in your production code. JDK
collection API already has a binarySearch() method on the java.util.Arrays class. This
implementation is for educational and for interview preparation purpose to teach
students how to code binary search in Java.

import java.util.Scanner;

/*
* Java Program to implement binary search without using recursion
*/
public class BinarySearch {

public static void main(String[] args) {

Scanner commandReader = new Scanner(System.in);


System.out.println("Welcome to Java Program to perform
binary search on int array");
System.out.println("Enter total number of elements : ");
int length = commandReader.nextInt();
int[] input = new int[length];
System.out.printf("Enter %d integers %n", length);
for (int i = 0; i < length; i++) {
input[i] = commandReader.nextInt();
}

System.out.println("Please enter number to be searched in array


(sorted order)");
int key = commandReader.nextInt();

int index = performBinarySearch(input, key);

if (index == -1) {
System.out.printf("Sorry, %d is not found in array %n", key);
} else {
System.out.printf("%d is found in array at index %d %n", key,
index);
}

commandReader.close();

/**
* Java method to perform binary search. It accept an integer array and a
* number and return the index of number in the array. If number doesn't
* exists in array then it return -1
*
* @param input
* @param number
* @return index of given number in array or -1 if not found
*/
public static int performBinarySearch(int[] input, int number) {
int low = 0;
int high = input.length - 1;

while (high >= low) {


int middle = (low + high) / 2;
if (input[middle] == number) {
return middle;
} else if (input[middle] < number) {
low = middle + 1;
} else if (input[middle] > number) {
high = middle - 1;
}
}
return -1;
}

Output
Welcome to Java Program to perform binary search on int array
Enter total number of elements :
4
Enter 4 integers
10
20
20
34
Please enter number to be searched in array
34
34 is found in array at index 3

13:-Write a Java program which will result in deadlock?

public class DeadLockDemo {

/*
* This method request two locks, first String and then Integer
*/
public void method1() {
synchronized (String.class) {
System.out.println("Aquired lock on String.class object");

synchronized (Integer.class) {
System.out.println("Aquired lock on Integer.class object");
}
}
}

/*
* This method also requests same two lock but in exactly
* Opposite order i.e. first Integer and then String.
* This creates potential deadlock, if one thread holds String lock
* and other holds Integer lock and they wait for each other, forever.
*/
public void method2() {
synchronized (Integer.class) {
System.out.println("Aquired lock on Integer.class object");

synchronized (String.class) {
System.out.println("Aquired lock on String.class object");
}
}
}
}

If method1() and method2() both will be called by two or many threads , there is a good
chance of deadlock because if thread 1 acquires lock on Sting object while executing
method1() and thread 2 acquires lock on Integer object while executing method2() both
will be waiting for each other to release lock on Integer and String to proceed further
which will never happen.

This diagram exactly demonstrates our program, where one thread holds a lock on one
object and waiting for other object locks which are held by other thread.

You can see that Thread 1 wants the lock on object 2 which is held by Thread 2, and
Thread 2 wants a lock on Object 1 which is held by Thread 1. Since no thread is willing
to give up, there is a deadlock and the Java program is stuck.

The idea is that you should know the right way to use common concurrent patterns, and
if you are not familiar with them then Applying Concurrency and Multi-threading to
Common Java Patterns by Jose Paumard is a good starting point to learn.

14:-Java Program to Find the Middle Node of a Linked list in a Single-pass

import test.LinkedList.Node;

/**
* Java program to find middle element of linked list in one
pass.
* In order to find middle element of a linked list
* we need to find the length first but since we can only
* traverse linked list one time, we will have to use two pointers
* one which we will increment on each iteration while
* other which will be incremented every second iteration.
* So when the first pointer will point to the end of a
* linked list, second will be pointing to the middle
* element of a linked list
*
* @author Javin Paul
*/
public class LinkedListTest {
public static void main(String args[]) {
//creating LinkedList with 5 elements including head
LinkedList linkedList = new LinkedList();
LinkedList.Node head = linkedList.head();
linkedList.add( new LinkedList.Node("1"));
linkedList.add( new LinkedList.Node("2"));
linkedList.add( new LinkedList.Node("3"));
linkedList.add( new LinkedList.Node("4"));

//finding middle element of LinkedList in single pass


LinkedList.Node current = head;
int length = 0;
LinkedList.Node middle = head;

while(current.next() != null){
length++;
if(length%2 ==0){
middle = middle.next();
}
current = current.next();
}

if(length%2 == 1){
middle = middle.next();
}

System.out.println("length of LinkedList: " + length);


System.out.println("middle element of LinkedList : "
+ middle);

class LinkedList{
private Node head;
private Node tail;

public LinkedList(){
this.head = new Node("head");
tail = head;
}

public Node head(){


return head;
}

public void add(Node node){


tail.next = node;
tail = node;
}

public static class Node{


private Node next;
private String data;

public Node(String data){


this.data = data;
}

public String data() {


return data;
}

public void setData(String data) {


this.data = data;
}

public Node next() {


return next;
}

public void setNext(Node next) {


this.next = next;
}

public String toString(){


return this.data;
}
}
}

Output:
length of LinkedList: 4
middle element of LinkedList: 2

15:-Java Program to traverse a Binary tree in PreOrder Algorithm

Here is our complete program to traverse a given binary tree in PreOrder. In this
program, you will find an implementation of both recursive and iterative pre-order
traversal algorithm. You can run this program from the command line or Eclipse IDE to
test and get a feel of how tree traversal works.

This program has a class called BinaryTree which represents a BinaryTree, remember
it's not a binary search tree because TreeNode doesn't implement Comparable or
Comparator interface. The TreeNode class represents a node in the binary tree, it
contains a data part and two references to left and right children.

I have created a preOrder() method in the BinaryTree class to traverse the tree in pre-
order. This is a public method but actual work is done by another private method which
is an overloaded version of this method.

The method accepts a TreeNode. Similarly, there is another method called


preOrderWithoutRecursion() to implement the iterative pre-order traversal of the
binary tree.
import java.util.Stack;

/*
* Java Program to traverse a binary tree using PreOrder traversal.
* In PreOrder the node value is printed first, followed by visit
* to left and right subtree.
* input:
* 1
* /\
* 2 5
* /\ \
*3 4 6
*
* output: 1 2 3 4 5 6
*/
public class PreOrderTraversal {

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

// construct the binary tree given in question


BinaryTree bt = new BinaryTree();
BinaryTree.TreeNode root = new BinaryTree.TreeNode("1");
bt.root = root;
bt.root.left = new BinaryTree.TreeNode("2");
bt.root.left.left = new BinaryTree.TreeNode("3");

bt.root.left.right = new BinaryTree.TreeNode("4");


bt.root.right = new BinaryTree.TreeNode("5");
bt.root.right.right = new BinaryTree.TreeNode("6");

// printing nodes in recursive preOrder traversal algorithm


bt.preOrder();

System.out.println();

// traversing binary tree in PreOrder without using recursion


bt.preOrderWithoutRecursion();

class BinaryTree {
static class TreeNode {
String data;
TreeNode left, right;

TreeNode(String value) {
this.data = value;
left = right = null;
}

boolean isLeaf() {
return left == null ? right == null : false;
}

// root of binary tree


TreeNode root;

/**
* Java method to print tree nodes in PreOrder traversal
*/
public void preOrder() {
preOrder(root);
}

/**
* traverse the binary tree in PreOrder
*
* @param node
* - starting node, root
*/
private void preOrder(TreeNode node) {
if (node == null) {
return;
}
System.out.printf("%s ", node.data);
preOrder(node.left);
preOrder(node.right);
}

/**
* Java method to visit tree nodes in PreOrder traversal without recursion.
*/
public void preOrderWithoutRecursion() {
Stack<TreeNode> nodes = new Stack<>();
nodes.push(root);

while (!nodes.isEmpty()) {
TreeNode current = nodes.pop();
System.out.printf("%s ", current.data);

if (current.right != null) {
nodes.push(current.right);
}
if (current.left != null) {
nodes.push(current.left);
}
}
}

Output
123456
123456

16:-Java Program to traverse binary tree using InOrder Algorithm


Here is our complete program to implement inorder traversal of a binary tree in Java.
This is similar to the preOrder example we have seen earlier, with the only difference
that root is visited second instead of first. The recursive algorithm is straightforward but
iterative one is a little bit difficult to understand. You must remember that Stack is a
LIFO data structure and node you push first will be popped later. Since you need to visit
node in left-node-right order, you have to push nodes of left tree until you reach the leaf
node. Thereafter you print the value and start exploring right subtree.

We have used same BinaryTree and TreeNode class, which is used to represent a
binary tree in earlier tree based problems e.g. counting leaf nodes. The BinaryTree is
your regular binary tree and TreeNode represents a node in the binary tree.
import java.util.Stack;
/*
* Java Program to traverse a binary tree
* using inorder traversal without recursion.
* In InOrder traversal first left node is visited, followed by root
* and right node.
*
* input:
* 4
* /\
* 2 5
* /\ \
*1 3 6
*
* output: 1 2 3 4 5 6
*/

public class InOrderTraversal {

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

// construct the binary tree given in question


BinaryTree bt = BinaryTree.create();

// traversing binary tree using InOrder traversal using recursion


System.out
.println("printing nodes of a binary tree on InOrder using recursion");

bt.inOrder();

System.out.println(); // insert new line

// traversing binary tree on InOrder traversal without recursion


System.out
.println("printing nodes of binary tree on InOrder using iteration");
bt.inOrderWithoutRecursion();
}

class BinaryTree {
static class TreeNode {
String data;
TreeNode left, right;

TreeNode(String value) {
this.data = value;
left = right = null;
}

boolean isLeaf() {
return left == null ? right == null : false;
}

}
// root of binary tree
TreeNode root;

/**
* traverse the binary tree on InOrder traversal algorithm
*/
public void inOrder() {
inOrder(root);
}

private void inOrder(TreeNode node) {


if (node == null) {
return;
}

inOrder(node.left);
System.out.printf("%s ", node.data);
inOrder(node.right);
}

public void inOrderWithoutRecursion() {


Stack nodes = new Stack<>();
TreeNode current = root;

while (!nodes.isEmpty() || current != null) {

if (current != null) {
nodes.push(current);
current = current.left;
} else {
TreeNode node = nodes.pop();
System.out.printf("%s ", node.data);
current = node.right;
}

}
}

/**
* Java method to create binary tree with test data
*
* @return a sample binary tree for testing
*/
public static BinaryTree create() {
BinaryTree tree = new BinaryTree();
TreeNode root = new TreeNode("4");
tree.root = root;
tree.root.left = new TreeNode("2");
tree.root.left.left = new TreeNode("1");

tree.root.left.right = new TreeNode("3");


tree.root.right = new TreeNode("5");
tree.root.right.right = new TreeNode("6");
return tree;
}

Output
printing nodes of a binary tree on InOrder using recursion
123456
printing nodes of a binary tree on InOrder using iteration
123456

17:-Java Program to print all leaf nodes of a binary tree using recursion
Here is the complete program, which you can run and test. It first creates a binary tree
as shown in below and then calls the printLeaves() method to print all leaf nodes of a
binary tree.

This program uses recursion because of printLeaves() method call itself to recursively
print leaf nodes from the left and right subtree. See Data Structures and Algorithms:
Deep Dive Using Java to learn more about the binary tree and other tree algorithms.
*
* Java Program to print all leaf nodes of binary tree
* using recursion
* input : a
* /\
* b f
* /\ /\
* c eg h
* / \
* d k
*
* output: d e g k
*/

public class Main {

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

// let's create a binary tree


TreeNode d = new TreeNode("d");
TreeNode e = new TreeNode("e");
TreeNode g = new TreeNode("g");
TreeNode k = new TreeNode("k");

TreeNode c = new TreeNode("c", d, null);


TreeNode h = new TreeNode("h", k, null);

TreeNode b = new TreeNode("b", c, e);


TreeNode f = new TreeNode("f", g, h);
TreeNode root = new TreeNode("a", b, f);

// print all leaf nodes of binary tree using recursion


System.out
.println("Printing all leaf nodes of binary tree in Java (recursively)");
printLeaves(root);

/**
* A class to represent a node in binary tree
*/
private static class TreeNode {
String value;
TreeNode left;
TreeNode right;

TreeNode(String value) {
this.value = value;
}

TreeNode(String data, TreeNode left, TreeNode right) {


this.value = data;
this.left = left;
this.right = right;
}

boolean isLeaf() {
return left == null ? right == null : false;
}
}

/**
* Java method to print leaf nodes using recursion
*
* @param root
*
*/
public static void printLeaves(TreeNode node) {
// base case
if (node == null) {
return;
}

if (node.isLeaf()) {
System.out.printf("%s ", node.value);
}

printLeaves(node.left);
printLeaves(node.right);

}
}
Output
Printing all leaf nodes of binary tree in Java (recursively)
degk

18:- Java Program to Print All Permutation of a String


Here is our sample Java program to print all permutations of given String using
recursive algorithm. It uses both loop and recursive call to solve this problem. It also
demonstrate a technique of hiding your implementation detail using a private method
and exposing a much cleaner public method as API. In our solution, we have two
permutation method, one is public and other is private.

First method is clean and exposed to client but second method require you to pass an
empty String as initial value of perm parameter which is used to store intermediate
permutation of String.

/**
* Java program to find all permutations of a given String using recursion.
* For example, given a String "XYZ", this program will print all 6 possible permutations of
* input e.g. XYZ, XZY, YXZ, YZX, ZXY, XYX
*
* @author Javin Paul
*/
public class StringPermutations {

public static void main(String args[]) {


permutation("123");
}

/*
* A method exposed to client to calculate permutation of String in Java.
*/
public static void permutation(String input){
permutation("", input);
}

/*
* Recursive method which actually prints all permutations
* of given String, but since we are passing an empty String
* as current permutation to start with,
* I have made this method private and didn't exposed it to client.
*/
private static void permutation(String perm, String word) {
if (word.isEmpty()) {
System.err.println(perm + word);
} else {
for (int i = 0; i &lt; word.length(); i++) {
permutation(perm + word.charAt(i), word.substring(0, i)
+ word.substring(i + 1, word.length()));
}
}

}
}

Output:
123
132
213
231
312
321

Explanation of Code :
All code for calculating permutation of String is inside permutation(String perm, String
word) method, I have purposefully made this method private because of additional
parameter I am passing as an initial value of permutation.

This demonstrates a technique of hiding implementation detail from a client and


exposing much cleaner API to client e.g. just permutation(String input) method,
passing empty String is an implementation detail and ugly for a client to pass whenever
it needs to calculate permutation. It is also an exercise for you to see if you can improve
the code by getting rid of that empty String.

Algorithm is nothing but keeping one character fix and then calculating permutations of
others. Crux of program is in following code segment :
for (int i = 0; i &lt; word.length(); i++) {
permutation(perm + word.charAt(i), word.substring(0, i)
+ word.substring(i + 1, word.length()));
}

Here we have a for loop to go through each character of String e.g. for input "123" this
loop will run three times. In each iteration, we are making a recursive call to function
itself i.e. permutation(String perm, String word) method, where the first parameter is
used to store the result.
After 1st iteration perm (first parameter of permutation() method) will be "" + 1 as we
are doing word.charAt(i) and i is zero. Next, we take out that character and pass the
remaining characters to permutation method again e.g. "23" in the first iteration.
Recursive call ends when it reaches to base case i.e. when remaining word becomes
empty, at that point "perm" parameter contains a valid permutation to be printed. You
can also store it into a List if you want to.

Here is a nice diagram which visually shows what this algorithm does :

That's all on how to find all permutations of a String in Java using recursion. It's a
very good exercise for preparing Java coding interviews. Why not you give it a try and
come up with another solution? also could you calculate complexity of this algorithm, to
me it looks n*!n because loop will run for n times and for each n, we will call
permutation method. Also, how about writing some JUnit test cases to see if this
solution works for various input e.g. empty String, one letter String, many letters String,
String with duplicate characters etc? It's a good practice to become hands-on writing
JUnit tests.

19:- java program to remove all white space form String in Java
Here is Java program which uses standard Java library to remove all white spaces from any String in Java. This
program gives example of trim() method to delete white space from beginning as well ad from end. For removing
all white space we have used regular expression along with replaceAll() method of String in Java. Regular
expression to find white space is \s, which finds all white spaces including tab character.

package test;

/**
* Java program to remove while space in String. In this program we will
* see techniques to remove white space not only from beginning and end by using
* trim() method of String class but also remove white space between String in Java.
* e.g. " ABC DEF " will turn to "ABCDEF". replaceAll() accepts regular expression
* and \s can be used to remove all white space from String including space between
* words.
*
* @author http://java67.blogspot.com
*/
public class StringRemoveWhiteSpace {
public static void main(String args[]) {

//removing white space from String from beginning and end in Java
String strWhiteSpace = " This String contains White Space at beginning and
end and middle ";
System.out.printf("String before removing White space : %n %s %n",
strWhiteSpace);
System.out.printf("length of String before removing white space %d : ",
strWhiteSpace.length());

//trim() method can remove white space from beginning and end of String in
Java
String strWithoutWhiteSpace = strWhiteSpace.trim();
System.out.printf("String after removing white space from beginning and end %n
%s %n", strWithoutWhiteSpace);
System.out.printf("length of String after removing white space from beginning
and end %d : ", strWithoutWhiteSpace.length());

//removing white space between String in Java


String white space = "ABC DEF GHI";
System.out.println("String with white space between words: " + white space);

// \s is regular expression for white space tab etc


String withoutspace = whitespace.replaceAll("\\s", "");
System.out.println("String after removing white space between words and
everywhere: " + withoutspace);

Output:
String before removing White space :
This String contains White Space at beginning and end and middle
length of String before removing white space 72 : String after removing white space
from beginning and end
This String contains White Space at beginning and end and middle
length of String after removing white space from beginning and end 64 : String with
white space between words: ABC DEF GHI

String after removing white space between words and everywhere: ABCDEFGHI

20:-java program to implement insertion sort.


In this Java program, we will sort an integer array using Insertion sort algorithm in Java.
As I said, insertion sort should only be used with small arrays or linked list, we are going
to use an integer array of length 7, which contains numbers in random order.

We have a method called insertionSort(int[] input) which takes an unsorted array and
sorts it. If you look at the logic, you will first see that we are looping over integer array,
starting from the second element.

On inner loop, we initialize the index with next element e.g. in the first iteration, j=1 and
it will point to the second element. The inner loop is used to compare current element
with the already sorted element, that's why after each iteration we decrease j by 1, here
j>0 condition stops when we reach the beginning of the array.

Shifting and swapping of element occur only if the current element is less than the
already sorted element. Like in our code example, 32 is the first element so it is sorted,
next is 23 so we compare it to 32, now 23 is less than 32 so we will swap 32 and 23
positions.

I have inline swapping logic but you can also create a method swap just to make the
algorithm more readable. If you don't understand how swapping of integer works, then
see this article. Once we came out of the outer loop, our int array is sorted in ascending
order.
import java.util.Arrays;

/**
* Java program to implement insertion sort in Java. In this example, we will
* sort an integer array using insertion sort algorithm. This logic can be used
* to sort array of String, or any other object which implements Comparable or
* Comparator interface in Java.
*
* @author Javin Paul
*/

public class Pattern {


public static void main(String args[]) {
// unsorted integer array
int[] unsorted = { 32, 23, 45, 87, 92, 31, 19 };
System.out.println("integer array before sorting : "
+ Arrays.toString(unsorted));

insertionSort(unsorted);

System.out.println("integer array after sorting : "


+ Arrays.toString(unsorted));
}

/*
* Sort given integer array using Insertion sort algorithm. only good for
* small arrays.
*/

public static void insertionSort(int[] unsorted) {


for (int i = 1; i < unsorted.length; i++) {
int current = unsorted[i];
int j = i;
// create right place by moving elements
while (j > 0 && unsorted[j - 1] > current) {

// move
unsorted[j] = unsorted[j - 1];
j--;
}

// found the right place, insert now


unsorted[j] = current;
}
}
}

Output
integer array before sorting : [32, 23, 45, 87, 92, 31, 19]
integer array after sorting : [19, 23, 31, 32, 45, 87, 92]

21:- java program to implement quick sort


Here is our sample Java program to implement Quicksort using for loop and stack,
without using recursion. This is also known as iterative quicksort algorithm.
import java.util.Arrays;
import java.util.Scanner;
import java.util.Stack;

/**
* Java Program to implement Iterative QuickSort Algorithm, without recursion.
*
* @author WINDOWS 8
*/
public class Sorting {

public static void main(String args[]) {

int[] unsorted = {34, 32, 43, 12, 11, 32, 22, 21, 32};
System.out.println("Unsorted array : " + Arrays.toString(unsorted));

iterativeQsort(unsorted);
System.out.println("Sorted array : " + Arrays.toString(unsorted));
}

/*
* iterative implementation of quicksort sorting algorithm.
*/
public static void iterativeQsort(int[] numbers) {
Stack stack = new Stack();
stack.push(0);
stack.push(numbers.length);

while (!stack.isEmpty()) {
int end = stack.pop();
int start = stack.pop();
if (end - start < 2) {
continue;
}
int p = start + ((end - start) / 2);
p = partition(numbers, p, start, end);

stack.push(p + 1);
stack.push(end);

stack.push(start);
stack.push(p);

}
}

/*
* Utility method to partition the array into smaller array, and
* comparing numbers to rearrange them as per quicksort algorithm.
*/
private static int partition(int[] input, int position, int start, int end) {
int l = start;
int h = end - 2;
int piv = input[position];
swap(input, position, end - 1);

while (l < h) {
if (input[l] < piv) {
l++;
} else if (input[h] >= piv) {
h--;
} else {
swap(input, l, h);
}
}
int idx = h;
if (input[h] < piv) {
idx++;
}
swap(input, end - 1, idx);
return idx;
}

/**
* Utility method to swap two numbers in given array
*
* @param arr - array on which swap will happen
* @param i
* @param j
*/
private static void swap(int[] arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}

Output:
Unsorted array : [34, 32, 43, 12, 11, 32, 22, 21, 32]
Sorted array : [11, 12, 21, 22, 32, 32, 32, 34, 43]

That's all about how to implement quicksort in Java without recursion. Just
remember, when you use for loop and stack to implement quicksort, it's known as
iterative implementation and when you call the method itself, it's known as recursive
implementation. The recursive solution of quicksort is easier to write and understand but
the iterative solution is much faster. Though average and worst case time complexity of
both recursive and iterative quicksorts are O(N log N) average case and O(n^2).

Btw, if you want to remember or review the time complexity of different sorting
algorithms e.g. quicksort, merge sort, insertion sort, radix sort, shell sort, or bubble sort,
here is a nice slide you can print and use:

22:-Java Program to Find the Middle Node of a Linked list in a Single-pass

import test.LinkedList.Node;

/**
* Java program to find middle element of linked list in one
pass.
* In order to find middle element of a linked list
* we need to find the length first but since we can only
* traverse linked list one time, we will have to use two pointers
* one which we will increment on each iteration while
* other which will be incremented every second iteration.
* So when the first pointer will point to the end of a
* linked list, second will be pointing to the middle
* element of a linked list
*
* @author Javin Paul
*/
public class LinkedListTest {
public static void main(String args[]) {
//creating LinkedList with 5 elements including head
LinkedList linkedList = new LinkedList();
LinkedList.Node head = linkedList.head();
linkedList.add( new LinkedList.Node("1"));
linkedList.add( new LinkedList.Node("2"));
linkedList.add( new LinkedList.Node("3"));
linkedList.add( new LinkedList.Node("4"));

//finding middle element of LinkedList in single pass


LinkedList.Node current = head;
int length = 0;
LinkedList.Node middle = head;

while(current.next() != null){
length++;
if(length%2 ==0){
middle = middle.next();
}
current = current.next();
}

if(length%2 == 1){
middle = middle.next();
}

System.out.println("length of LinkedList: " + length);


System.out.println("middle element of LinkedList : "
+ middle);

class LinkedList{
private Node head;
private Node tail;
public LinkedList(){
this.head = new Node("head");
tail = head;
}

public Node head(){


return head;
}

public void add(Node node){


tail.next = node;
tail = node;
}

public static class Node{


private Node next;
private String data;

public Node(String data){


this.data = data;
}

public String data() {


return data;
}

public void setData(String data) {


this.data = data;
}

public Node next() {


return next;
}

public void setNext(Node next) {


this.next = next;
}

public String toString(){


return this.data;
}
}
}

Output:
length of LinkedList: 4
middle element of LinkedList: 2

That’s all on How to find middle element of LinkedList in one pass. As I said this is
a good interview question to separate programmers from non-programmers. Also, the
technique mentioned here to find middle node of LinkedList can be used to find the 3rd
element from Last or nth element from last in a LinkedList as well.

23:- java program to implement producer consumer problem


BlockingQueue amazingly simplifies implementation of Producer-Consumer design pattern by providing outofbox
support of blocking on put() and take(). Developer doesn't need to write confusing and critical piece of wait-notify
code to implement communication. BlockingQuue is an interface and Java 5 provides different implantation like
ArrayBlockingQueue and LinkedBlockingQueue , both implement FIFO order or elements, while
ArrayLinkedQueue is bounded in nature LinkedBlockingQueue is optionally bounded. here is a complete code
example of Producer Consumer pattern with BlockingQueue. Compare it with classic wait notify code, its much
simpler and easy to understand.

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.logging.Level;
import java.util.logging.Logger;

public class ProducerConsumerPattern {

public static void main(String args[]){

//Creating shared object


BlockingQueue sharedQueue = new LinkedBlockingQueue();

//Creating Producer and Consumer Thread


Thread prodThread = new Thread(new Producer(sharedQueue));
Thread consThread = new Thread(new Consumer(sharedQueue));

//Starting producer and Consumer thread


prodThread.start();
consThread.start();
}

}
//Producer Class in java
class Producer implements Runnable {

private final BlockingQueue sharedQueue;

public Producer(BlockingQueue sharedQueue) {


this.sharedQueue = sharedQueue;
}

@Override
public void run() {
for(int i=0; i<10; i++){
try {
System.out.println("Produced: " + i);
sharedQueue.put(i);
} catch (InterruptedException ex) {
Logger.getLogger(Producer.class.getName()).log(Level.SEVERE, null, ex);
}
}
}

//Consumer Class in Java


class Consumer implements Runnable{

private final BlockingQueue sharedQueue;

public Consumer (BlockingQueue sharedQueue) {


this.sharedQueue = sharedQueue;
}

@Override
public void run() {
while(true){
try {
System.out.println("Consumed: "+ sharedQueue.take());
} catch (InterruptedException ex) {
Logger.getLogger(Consumer.class.getName()).log(Level.SEVERE, null, ex);
}
}
}

Output:
Produced: 0
Produced: 1
Consumed: 0
Produced: 2
Consumed: 1
Produced: 3
Consumed: 2
Produced: 4
Consumed: 3
Produced: 5
Consumed: 4
Produced: 6
Consumed: 5
Produced: 7
Consumed: 6
Produced: 8
Consumed: 7
Produced: 9
Consumed: 8
Consumed: 9

24:- java program to find missing integer in a sorted array or series.


import java.util.Arrays;
/**
* Java Program to find the missing number in a sorted array with integers in range 0 to n -1
*
* @author Javin Paul
*/
public class MissingNumberFinder {

public static void main(String args[]) {

System.out.println("Test #1 : Missing number in sorted array ");


int[] input = new int[]{1, 2, 3, 4, 6};
int missing = missingNumberFromSortedArray(input);
System.out.println("Missing number from array : " + Arrays.toString(input) + " is : " + missing);

public static int missingNumberFromSortedArray(int[] numbers) {


if (numbers == null || numbers.length <= 0) {
throw new IllegalArgumentException("Null or Empty array not permitted");
}

int left = 0;
int right = numbers.length - 1;
while (left <= right) {
int middle = (right + left) >> 1;
if (numbers[middle] != middle) {
if (middle == 0 || numbers[middle - 1] == middle - 1) {
return middle;
}
right = middle - 1;
} else {
left = middle + 1;
}
}
throw new RuntimeException("No missing number");
}
}

Output:
Test #1 : Missing number in sorted array
Missing number from array : [1, 2, 3, 4, 6] is : 0

25:- java program to check if number is power of two or not

public class PowerOf2Test {

public static void main(String args[]) {

int[] numbers = {0,1,2,6,8};

for(int num: numbers){


System.out.println("isPowerOfTwo()-- is " + num + " power of two in Java
:" + isPowerOfTwo(num));
System.out.println("powerOfTwo()-- is " + num + " power of two in Java
:" + powerOfTwo(num));
System.out.println("checkPowerOfTwo()-- is " + num + " power of two in
Java :" + checkPowerOfTwo(num));
System.out.println("---------------------------------------------------
--------");
}

}
/*
* checking if number is power of 2 using bit shift operator in java
* e.g. 4 in binary format is "0000 0000 0000 0000 0000 0000 0000 0100";
* and -4 is "1111 1111 1111 1111 1111 1111 1111 1100";
* and 4&-4 will be "0000 0000 0000 0000 0000 0000 0000 0100"
*/
private static boolean isPowerOfTwo(int number) {
if(number <0){
throw new IllegalArgumentException("number: " + number);
}
if ((number & -number) == number) {
return true;
}
return false;
}

You might also like