25 Java Programs
25 Java Programs
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.Arrays;
long invert = 0;
while (number != 0) {
invert = (invert * 10) + (number % 10);
number = number / 10;
}
return invert;
}
Further Reading:
? Top 20 Selenium Coding Tips for Software Testers.
import java.util.Scanner;
int maxOne = 0;
int maxTwo = 0;
for (int n : nums) {
if (maxOne < n) {
maxTwo = maxOne;
maxOne = n;
} else if (maxTwo < n) {
maxTwo = n;
}
import java.util.HashSet;
import java.util.Set;
return sb.toString();
}
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"));
}
}
import java.util.StringTokenizer;
while(substr.hasMoreElements()){
sb.append(substr.nextElement()).append(" ");
}
import java.io.BufferedReader;
import java.io.InputStreamReader;
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.");
}
}
}
System.out.println("");
System.out.println("");
/*
* 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
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 {
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;
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
/*
* 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.
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"));
while(current.next() != null){
length++;
if(length%2 ==0){
middle = middle.next();
}
current = current.next();
}
if(length%2 == 1){
middle = middle.next();
}
class LinkedList{
private Node head;
private Node tail;
public LinkedList(){
this.head = new Node("head");
tail = head;
}
Output:
length of LinkedList: 4
middle element of LinkedList: 2
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.
/*
* 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 {
System.out.println();
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;
}
/**
* 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
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
*/
bt.inOrder();
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);
}
inOrder(node.left);
System.out.printf("%s ", node.data);
inOrder(node.right);
}
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");
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
*/
/**
* 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;
}
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
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 {
/*
* 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 < 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.
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 < 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());
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
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
*/
insertionSort(unsorted);
/*
* Sort given integer array using Insertion sort algorithm. only good for
* small arrays.
*/
// move
unsorted[j] = unsorted[j - 1];
j--;
}
Output
integer array before sorting : [32, 23, 45, 87, 92, 31, 19]
integer array after sorting : [19, 23, 31, 32, 45, 87, 92]
/**
* Java Program to implement Iterative QuickSort Algorithm, without recursion.
*
* @author WINDOWS 8
*/
public class Sorting {
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:
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"));
while(current.next() != null){
length++;
if(length%2 ==0){
middle = middle.next();
}
current = current.next();
}
if(length%2 == 1){
middle = middle.next();
}
class LinkedList{
private Node head;
private Node tail;
public LinkedList(){
this.head = new Node("head");
tail = head;
}
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.
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.logging.Level;
import java.util.logging.Logger;
}
//Producer Class in java
class Producer implements Runnable {
@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);
}
}
}
@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
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
}
/*
* 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;
}