Java Interview Programs PDF
Java Interview Programs PDF
Java Interview Programs PDF
Linked List?
Description:
Write a sample code to reverse Singly Linked List by iterating through
it only once.
Recursive Method:
1) Divide the list in two parts - first node and rest of the linked
list.
2) Call reverse for the rest of the linked list.
3) Link rest to first.
4) Fix head pointer.
Code:
?
1 package com.java2novice.ds.linkedlist;
2
3 public class SinglyLinkedListImpl<T> {
4
5 private Node<T> head;
6
7 public void add(T element){
8
9 Node<T> nd = new Node<T>();
10 nd.setValue(element);
11 System.out.println("Adding: "+element);
12 Node<T> tmp = head;
13 while(true){
14 if(tmp == null){
15 //since there is only one element,
16both head and
17 //tail points to the same object.
18 head = nd;
19 break;
20 } else if(tmp.getNextRef() == null){
21 tmp.setNextRef(nd);
22 break;
23 } else {
24 tmp = tmp.getNextRef();
25 }
26 }
27 }
28
29 public void traverse(){
30
31 Node<T> tmp = head;
32 while(true){
33 if(tmp == null){
34 break;
35 }
36 System.out.print(tmp.getValue()+"\t");
37 tmp = tmp.getNextRef();
38 }
39 }
40
41 public void reverse(){
42
43 System.out.println("\nreversing the linked list\n");
44 Node<T> prev = null;
45 Node<T> current = head;
46 Node<T> next = null;
47 while(current != null){
48 next = current.getNextRef();
49 current.setNextRef(prev);
50 prev = current;
51 current = next;
52 }
53 head = prev;
54 }
55
56 public static void main(String a[]){
57 SinglyLinkedListImpl<Integer> sl = new
58SinglyLinkedListImpl<Integer>();
59 sl.add(3);
60 sl.add(32);
61 sl.add(54);
62 sl.add(89);
63 System.out.println();
64 sl.traverse();
65 System.out.println();
66 sl.reverse();
67 sl.traverse();
68 }
69}
70
71class Node<T> implements Comparable<T> {
72
73 private T value;
74 private Node<T> nextRef;
75
76 public T getValue() {
77 return value;
78 }
79 public void setValue(T value) {
80 this.value = value;
81 }
82 public Node<T> getNextRef() {
83 return nextRef;
84 }
85 public void setNextRef(Node<T> ref) {
86 this.nextRef = ref;
87 }
88 @Override
89 public int compareTo(T arg) {
90 if(arg == this.value){
91 return 0;
92 } else {
93 return 1;
94 }
}
}
Output:
Adding: 3
Adding: 32
Adding: 54
Adding: 89
3 32 54 89
89 54 32 3
Program: Find out duplicate number
between 1 to N numbers.
Description:
You have got a range of numbers between 1 to N, where one of the number
is
repeated. You need to write a program to find out the duplicate number.
Code:
?
1 package com.java2novice.algos;
2
3 import java.util.ArrayList;
4 import java.util.List;
5
6 public class DuplicateNumber {
7
8 public int findDuplicateNumber(List<Integer> numbers){
9
10 int highestNumber = numbers.size() - 1;
11 int total = getSum(numbers);
12 int duplicate = total -
13(highestNumber*(highestNumber+1)/2);
14 return duplicate;
15 }
16
17 public int getSum(List<Integer> numbers){
18
19 int sum = 0;
20 for(int num:numbers){
21 sum += num;
22 }
23 return sum;
24 }
25
26 public static void main(String a[]){
27 List<Integer> numbers = new ArrayList<Integer>();
28 for(int i=1;i<30;i++){
29 numbers.add(i);
30 }
31 //add duplicate number into the list
32 numbers.add(22);
33 DuplicateNumber dn = new DuplicateNumber();
34 System.out.println("Duplicate Number:
35"+dn.findDuplicateNumber(numbers));
}
}
Output:
Duplicate Number: 22
Program: Find out middle index where
sum of both ends are equal.
Description:
You are given an array of numbers. Find out the array index or position
where sum of numbers preceeding the index is equals to sum of numbers
succeeding the index.
Code:
?
1 package com.java2novice.algos;
2
3 public class FindMiddleIndex {
4
5 public static int findMiddleIndex(int[] numbers) throws
6 Exception {
7
8 int endIndex = numbers.length - 1;
9 int startIndex = 0;
10 int sumLeft = 0;
11 int sumRight = 0;
12 while (true) {
13 if (sumLeft > sumRight) {
14 sumRight += numbers[endIndex--];
15 } else {
16 sumLeft += numbers[startIndex++];
17 }
18 if (startIndex > endIndex) {
19 if (sumLeft == sumRight) {
20 break;
21 } else {
22 throw new Exception(
23 "Please
24pass proper array to match the requirement");
25 }
26 }
27 }
28 return endIndex;
29 }
30
31 public static void main(String a[]) {
32 int[] num = { 2, 4, 4, 5, 4, 1 };
33 try {
34 System.out.println("Starting from index 0,
35adding numbers till index "
36 +
37findMiddleIndex(num) + " and");
38 System.out.println("adding rest of the
39numbers can be equal");
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
}
Output:
Starting from index 0, adding numbers till index 2 and
adding rest of the numbers can be equal
Program: Write a singleton class.
Description:
Singleton class means you can create only one object for the given class. You can
create a singleton class by making its constructor as private, so that you can restrict
the creation of the object. Provide a static method to get instance of the object,
wherein you can handle the object creation inside the class only. In this example we
are creating object by using static block.
Code:
?
1 package com.java2novice.algos;
2
3 public class MySingleton {
4
5 private static MySingleton myObj;
6
7 static{
8 myObj = new MySingleton();
9 }
10
11 private MySingleton(){
12
13 }
14
15 public static MySingleton getInstance(){
16 return myObj;
17 }
18
19 public void testMe(){
20 System.out.println("Hey.... it is working!!!");
21 }
22
23 public static void main(String a[]){
24 MySingleton ms = getInstance();
25 ms.testMe();
26 }
27}
Program: Write a program to create
deadlock between two threads.
Description:
Deadlock describes a situation where two or more threads are blocked forever,
waiting for each other. Deadlocks can occur in Java when the synchronized keyword
causes the executing thread to block while waiting to get the lock, associated with
the specified object. Since the thread might already hold locks associated with other
objects, two threads could each be waiting for the other to release a lock. In such
case, they will end up waiting forever.
Code:
?
1 package com.java2novice.algos;
2
3 public class MyDeadlock {
4
5 String str1 = "Java";
6 String str2 = "UNIX";
7
8 Thread trd1 = new Thread("My Thread 1"){
9 public void run(){
10 while(true){
11 synchronized(str1){
12 synchronized(str2){
13 System.out.println(str1 +
14 str2);
15 }
16 }
17 }
18 }
19 };
20
21 Thread trd2 = new Thread("My Thread 2"){
22 public void run(){
23 while(true){
24 synchronized(str2){
25 synchronized(str1){
26 System.out.println(str2 +
27 str1);
28 }
29 }
30 }
31 }
32 };
33
34 public static void main(String a[]){
35 MyDeadlock mdl = new MyDeadlock();
36 mdl.trd1.start();
37 mdl.trd2.start();
}
}
Program: Write a program to reverse
a string using recursive algorithm.
Description:
Write a program to reverse a string using recursive methods.
You should not use any string reverse methods to do this.
Code:
package com.java2novice.algos;
if(str.length() == 1){
return str;
} else {
reverse += str.charAt(str.length()-1)
+reverseString(str.substring(0,str.length()-1));
return reverse;
}
}
Output:
Result: ecivon2avaJ
Program: Write a program to reverse
a number.
Description:
Write a program to reverse a number using numeric operations. Below example
shows how to reverse a number using numeric operations.
Code:
?
package com.java2novice.algos;
1
2
public class NumberReverse {
3
4
public int reverseNumber(int number){
5
6
int reverse = 0;
7
while(number != 0){
8
reverse = (reverse*10)+(number%10);
9
number = number/10;
10
}
11
return reverse;
12
}
13
14
public static void main(String a[]){
15
NumberReverse nr = new NumberReverse();
16
System.out.println("Result:
17
"+nr.reverseNumber(17868));
18
}
19
}
Output:
Result: 86871
Program: Write a program to convert
decimal number to binary format.
Description:
Write a program to convert decimal number to binary format using numeric
operations. Below example shows how to convert decimal number to binary format
using numeric operations.
Code:
?
1 package com.java2novice.algos;
2
3 public class DecimalToBinary {
4
5 public void printBinaryFormat(int number){
6 int binary[] = new int[25];
7 int index = 0;
8 while(number > 0){
9 binary[index++] = number%2;
10 number = number/2;
11 }
12 for(int i = index-1;i >= 0;i--){
13 System.out.print(binary[i]);
14 }
15 }
16
17 public static void main(String a[]){
18 DecimalToBinary dtb = new DecimalToBinary();
19 dtb.printBinaryFormat(25);
20 }
21}
Output:
11001
Program: Write a program to find
perfect number or not.
Description:
A perfect number is a positive integer that is equal to the sum
of its proper positive divisors, that is, the sum of its positive
divisors excluding the number itself. Equivalently, a perfect number
is a number that is half the sum of all of its positive divisors.
The first perfect number is 6, because 1, 2 and 3 are its proper
positive divisors, and 1 + 2 + 3 = 6. Equivalently, the number 6
is equal to half the sum of all its positive divisors:
( 1 + 2 + 3 + 6 ) / 2 = 6.
Code:
?
1 package com.java2novice.algos;
2
3 public class IsPerfectNumber {
4
5 public boolean isPerfectNumber(int number){
6
7 int temp = 0;
8 for(int i=1;i<=number/2;i++){
9 if(number%i == 0){
10 temp += i;
11 }
12 }
13 if(temp == number){
14 System.out.println("It is a perfect number");
15 return true;
16 } else {
17 System.out.println("It is not a perfect
18number");
19 return false;
20 }
21 }
22
23 public static void main(String a[]){
24 IsPerfectNumber ipn = new IsPerfectNumber();
25 System.out.println("Is perfect number:
26"+ipn.isPerfectNumber(28));
}
}
Output:
28
It is a perfect number
Is perfect number: true
Program: Write a program to
implement ArrayList.
Description:
Write a program to implement your own ArrayList class. It should
contain add(), get(), remove(), size() methods. Use dynamic array logic.
It should increase its size when it reaches threshold.
Code:
?
1 package com.java2novice.algos;
2
3 import java.util.Arrays;
4
5 public class MyArrayList {
6
7 private Object[] myStore;
8 private int actSize = 0;
9
10 public MyArrayList(){
11 myStore = new Object[10];
12 }
13
14 public Object get(int index){
15 if(index < actSize){
16 return myStore[index];
17 } else {
18 throw new ArrayIndexOutOfBoundsException();
19 }
20 }
21
22 public void add(Object obj){
23 if(myStore.length-actSize <= 5){
24 increaseListSize();
25 }
26 myStore[actSize++] = obj;
27 }
28
29 public Object remove(int index){
30 if(index < actSize){
31 Object obj = myStore[index];
32 myStore[index] = null;
33 int tmp = index;
34 while(tmp < actSize){
35 myStore[tmp] = myStore[tmp+1];
36 myStore[tmp+1] = null;
37 tmp++;
38 }
39 actSize--;
40 return obj;
41 } else {
42 throw new ArrayIndexOutOfBoundsException();
43 }
44
45 }
46
47 public int size(){
48 return actSize;
49 }
50
51 private void increaseListSize(){
52 myStore = Arrays.copyOf(myStore, myStore.length*2);
53 System.out.println("\nNew length: "+myStore.length);
54 }
55
56 public static void main(String a[]){
57 MyArrayList mal = new MyArrayList();
58 mal.add(new Integer(2));
59 mal.add(new Integer(5));
60 mal.add(new Integer(1));
61 mal.add(new Integer(23));
62 mal.add(new Integer(14));
63 for(int i=0;i<mal.size();i++){
64 System.out.print(mal.get(i)+" ");
65 }
66 mal.add(new Integer(29));
67 System.out.println("Element at Index
685:"+mal.get(5));
69 System.out.println("List size: "+mal.size());
70 System.out.println("Removing element at index 2:
71"+mal.remove(2));
72 for(int i=0;i<mal.size();i++){
73 System.out.print(mal.get(i)+" ");
74 }
}
}
Output:
2 5 1 23 14
New length: 20
Element at Index 5:29
List size: 6
Removing element at index 2: 1
2 5 23 14 29
Program: Write a program to find
maximum repeated words from a file.
Description:
Write a program to read words from a file. Count the
repeated or duplicated words. Sort it by maximum repeated or
duplicated word count.
Code:
?
1 package com.java2novice.algos;
2
3 import java.io.BufferedReader;
4 import java.io.DataInputStream;
5 import java.io.FileInputStream;
6 import java.io.FileNotFoundException;
7 import java.io.IOException;
8 import java.io.InputStreamReader;
9 import java.util.ArrayList;
1 import java.util.Collections;
0 import java.util.Comparator;
1 import java.util.HashMap;
1 import java.util.List;
1 import java.util.Map;
2 import java.util.Set;
1 import java.util.StringTokenizer;
3 import java.util.Map.Entry;
1
4 public class MaxDuplicateWordCount {
1
5 public Map<String, Integer> getWordCount(String fileName){
1
6 FileInputStream fis = null;
1 DataInputStream dis = null;
7 BufferedReader br = null;
1 Map<String, Integer> wordMap = new HashMap<String,
8 Integer>();
1 try {
9 fis = new FileInputStream(fileName);
2 dis = new DataInputStream(fis);
0 br = new BufferedReader(new
2 InputStreamReader(dis));
1 String line = null;
2 while((line = br.readLine()) != null){
2 StringTokenizer st = new
2 StringTokenizer(line, " ");
3 while(st.hasMoreTokens()){
2 String tmp =
4 st.nextToken().toLowerCase();
2 if(wordMap.containsKey(tmp)
5 ){
2 wordMap.put(tmp,
6 wordMap.get(tmp)+1);
2 } else {
7 wordMap.put(tmp,
2 1);
8 }
2 }
9 }
3 } catch (FileNotFoundException e) {
0 e.printStackTrace();
3 } catch (IOException e) {
1 e.printStackTrace();
3 } finally{
2 try{if(br != null)
3 br.close();}catch(Exception ex){}
3 }
3 return wordMap;
4 }
3
5 public List<Entry<String, Integer>> sortByValue(Map<String,
3 Integer> wordMap){
6
3 Set<Entry<String, Integer>> set = wordMap.entrySet();
7 List<Entry<String, Integer>> list = new
3 ArrayList<Entry<String, Integer>>(set);
8 Collections.sort( list, new
3 Comparator<Map.Entry<String, Integer>>()
9 {
4 public int compare( Map.Entry<String,
0 Integer> o1, Map.Entry<String, Integer> o2 )
4 {
1 return
4 (o2.getValue()).compareTo( o1.getValue() );
2 }
4 } );
3 return list;
4 }
4
4 public static void main(String a[]){
5 MaxDuplicateWordCount mdc = new
4 MaxDuplicateWordCount();
6 Map<String, Integer> wordMap =
4 mdc.getWordCount("C:/MyTestFile.txt");
7 List<Entry<String, Integer>> list =
4 mdc.sortByValue(wordMap);
8 for(Map.Entry<String, Integer> entry:list){
4 System.out.println(entry.getKey()+" ====
9 "+entry.getValue());
5 }
0 }
5 }
1
5
2
5
3
5
4
5
5
5
6
5
7
5
8
5
9
6
0
6
1
6
2
6
3
6
4
6
5
6
6
6
7
6
8
6
9
7
0
7
1
7
2
7
3
7
4
7
5
Output:
one ==== 3
the ==== 3
that ==== 3
of ==== 2
in ==== 2
some ==== 2
to ==== 1
summary ==== 1
but ==== 1
have ==== 1
common ==== 1
least ==== 1
simplest ==== 1
Program: Write a program to find out
duplicate characters in a string.
Description:
Write a program to find out duplicate or repeated characters in a
string, and calculate the count of repeatation.
Code:
?
1 package com.java2novice.algos;
2
3 import java.util.HashMap;
4 import java.util.Map;
5 import java.util.Set;
6
7 public class DuplicateCharsInString {
8
9 public void findDuplicateChars(String str){
1
0 Map<Character, Integer> dupMap = new
1 HashMap<Character, Integer>();
1 char[] chrs = str.toCharArray();
1 for(Character ch:chrs){
2 if(dupMap.containsKey(ch)){
1 dupMap.put(ch, dupMap.get(ch)+1);
3 } else {
1 dupMap.put(ch, 1);
4 }
1 }
5 Set<Character> keys = dupMap.keySet();
1 for(Character ch:keys){
6 if(dupMap.get(ch) > 1){
1 System.out.println(ch+"--->"+dupMap
7 .get(ch));
1 }
8 }
1 }
9
2 public static void main(String a[]){
0 DuplicateCharsInString dcs = new
2 DuplicateCharsInString();
1 dcs.findDuplicateChars("Java2Novice");
2 }
2}
2
3
2
4
2
5
2
6
2
7
2
8
2
9
3
0
3
1
3
2
Output:
v--->2
a--->2
Program: Write a program to find top
two maximum numbers in a array.
Description:
Write a program to find top two maximum numbers in the
given array. You should not use any sorting functions. You
should iterate the array only once. You should not use any
kind of collections in java.
Code:
?
1 package com.java2novice.algos;
2
3 public class TwoMaxNumbers {
4
5 public void printTwoMaxNumbers(int[] nums){
6 int maxOne = 0;
7 int maxTwo = 0;
8 for(int n:nums){
9 if(maxOne < n){
10 maxTwo = maxOne;
11 maxOne =n;
12 } else if(maxTwo < n){
13 maxTwo = n;
14 }
15 }
16 System.out.println("First Max Number: "+maxOne);
17 System.out.println("Second Max Number: "+maxTwo);
18 }
19
20 public static void main(String a[]){
21 int num[] = {5,34,78,2,45,1,99,23};
22 TwoMaxNumbers tmn = new TwoMaxNumbers();
23 tmn.printTwoMaxNumbers(num);
24 }
25}
Output:
First Max Number: 99
Second Max Number: 78
Program: Write a program to sort a
map by value.
Description:
Sort or order a HashMap or TreeSet or any map item by value. Write a
comparator
which compares by value, not by key. Entry class might hleps you here.
Code:
?
1 package com.java2novice.algos;
2
3 import java.util.ArrayList;
4 import java.util.Collections;
5 import java.util.Comparator;
6 import java.util.HashMap;
7 import java.util.List;
8 import java.util.Map;
9 import java.util.Set;
10import java.util.Map.Entry;
11
12public class OrderByValue {
13
14 public static void main(String a[]){
15 Map<String, Integer> map = new HashMap<String,
16Integer>();
17 map.put("java", 20);
18 map.put("C++", 45);
19 map.put("Java2Novice", 2);
20 map.put("Unix", 67);
21 map.put("MAC", 26);
22 map.put("Why this kolavari", 93);
23 Set<Entry<String, Integer>> set = map.entrySet();
24 List<Entry<String, Integer>> list = new
25ArrayList<Entry<String, Integer>>(set);
26 Collections.sort( list, new
27Comparator<Map.Entry<String, Integer>>()
28 {
29 public int compare( Map.Entry<String,
30Integer> o1, Map.Entry<String, Integer> o2 )
31 {
32 return
33(o2.getValue()).compareTo( o1.getValue() );
34 }
35 } );
for(Map.Entry<String, Integer> entry:list){
System.out.println(entry.getKey()+" ====
"+entry.getValue());
}
}
}
Output:
Why this kolavari ==== 93
Unix ==== 67
C++ ==== 45
MAC ==== 26
java ==== 20
Java2Novice ==== 2
Program: Write a program to find
common elements between two arrays.
Description:
Write a program to identify common elements or numbers between
two given arrays. You should not use any inbuilt methods are list to
find common values.
Code:
?
1
2
3
4 package com.java2novice.algos;
5
6 public class CommonElementsInArray {
7
8 public static void main(String a[]){
9 int[] arr1 = {4,7,3,9,2};
1 int[] arr2 = {3,2,12,9,40,32,4};
0 for(int i=0;i<arr1.length;i++){
1 for(int j=0;j<arr2.length;j++){
1 if(arr1[i]==arr2[j]){
1 System.out.println(arr1[i])
2 ;
1 }
3 }
1 }
4 }
1 }
5
1
6
Output:
4
3
9
2
Program: How to swap two numbers
without using temporary variable?
Description:
Write a program to swap or exchange two numbers. You should
not use any temporary or third variable to swap.
Code:
?
1 package com.java2novice.algos;
2
3 public class MySwapingTwoNumbers {
4
5 public static void main(String a[]){
6 int x = 10;
7 int y = 20;
8 System.out.println("Before swap:");
9 System.out.println("x value: "+x);
10 System.out.println("y value: "+y);
11 x = x+y;
12 y=x-y;
13 x=x-y;
14 System.out.println("After swap:");
15 System.out.println("x value: "+x);
16 System.out.println("y value: "+y);
17 }
18}
Output:
Before swap:
x value: 10
y value: 20
After swap:
x value: 20
y value: 10
Program: Write a program to print
fibonacci series.
Description:
In mathematics, the Fibonacci numbers or Fibonacci series or Fibonacci sequence are
the numbers in the following integer sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89,
144... By definition, the first two numbers in the Fibonacci sequence are 0 and 1, and
each subsequent number is the sum of the previous two. Below example shows how
to create fibonacci series.
Code:
?
1 package com.java2novice.algos;
2
3 public class MyFibonacci {
4
5 public static void main(String a[]){
6
7 int febCount = 15;
8 int[] feb = new int[febCount];
9 feb[0] = 0;
10 feb[1] = 1;
11 for(int i=2; i < febCount; i++){
12 feb[i] = feb[i-1] + feb[i-2];
13 }
14
15 for(int i=0; i< febCount; i++){
16 System.out.print(feb[i] + " ");
17 }
18 }
19}
Output:
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377
Program: Write a program to find sum
of each digit in the given number
using recursion.
Description:
Below example shows how to find out sum of each digit in the given number using
recursion logic. For example, if the number is 259, then the sum should be 2+5+9 =
16.
Code:
?
package com.java2novice.algos;
1
2
public class MyNumberSumRec {
3
4
int sum = 0;
5
6
public int getNumberSum(int number){
7
8
if(number == 0){
9
return sum;
10
} else {
11
sum += (number%10);
12
getNumberSum(number/10);
13
}
14
return sum;
15
}
16
17
public static void main(String a[]){
18
MyNumberSumRec mns = new MyNumberSumRec();
19
System.out.println("Sum is:
20
"+mns.getNumberSum(223));
21
}
22
}
Output:
Sum is: 7
Program: Write a program to check the
given number is a prime number or
not?
Description:
A prime number (or a prime) is a natural number greater than 1 that has no positive
divisors other than 1 and itself. A natural number greater than 1 that is not a prime
number is called a composite number. For example, 5 is prime, as only 1 and 5 divide
it, whereas 6 is composite, since it has the divisors 2 and 3 in addition to 1 and 6. The
fundamental theorem of arithmetic establishes the central role of primes in number
theory: any integer greater than 1 can be expressed as a product of primes that is
unique up to ordering. This theorem requires excluding 1 as a prime.
Code:
?
package com.java2novice.algos;
1
public class MyPrimeNumCheck {
2
3
public boolean isPrimeNumber(int number){
4
5
for(int i=2; i<=number/2; i++){
6
if(number % i == 0){
7
return false;
8
}
9
}
10
return true;
11
}
12
13
public static void main(String a[]){
14
MyPrimeNumCheck mpc = new MyPrimeNumCheck();
15
System.out.println("Is 17 prime number?
16
"+mpc.isPrimeNumber(17));
17
System.out.println("Is 19 prime number?
18
"+mpc.isPrimeNumber(19));
19
System.out.println("Is 15 prime number?
20
"+mpc.isPrimeNumber(15));
21
}
}
Output:
Is 17 prime number? true
Is 19 prime number? true
Is 15 prime number? false
Program: Write a program to find the
given number is Armstrong number or
not?
Description:
Armstrong numbers are the sum of their own digits to the power of
the number of digits. It is also known as narcissistic numbers.
Code:
?
1 package com.java2novice.algos;
2
3 public class MyArmstrongNumber {
4
5 public boolean isArmstrongNumber(int number){
6
7 int tmp = number;
8 int noOfDigits = String.valueOf(number).length();
9 int sum = 0;
10 int div = 0;
11 while(tmp > 0)
12 {
13 div = tmp % 10;
14 int temp = 1;
15 for(int i=0;i<noOfDigits;i++){
16 temp *= div;
17 }
18 sum += temp;
19 tmp = tmp/10;
20 }
21 if(number == sum) {
22 return true;
23 } else {
24 return false;
25 }
26 }
27
28 public static void main(String a[]){
29 MyArmstrongNumber man = new MyArmstrongNumber();
30 System.out.println("Is 371 Armstrong number?
31 "+man.isArmstrongNumber(371));
32 System.out.println("Is 523 Armstrong number?
33 "+man.isArmstrongNumber(523));
34 System.out.println("Is 153 Armstrong number?
"+man.isArmstrongNumber(153));
}
}
Output:
Is 371 Armstrong number? true
Is 523 Armstrong number? false
Is 153 Armstrong number? true
Program: Write a program to convert
binary to decimal number.
Description:
Write a program to convert binary format to decimal number using numeric
operations. Below example shows how to convert binary to decimal format using
numeric operations.
Code:
?
package com.java2novice.algos;
1
2 public class BinaryToDecimal {
3
4 public int getDecimalFromBinary(int binary){
5
6 int decimal = 0;
7 int power = 0;
8 while(true){
9 if(binary == 0){
10 break;
11 } else {
12 int tmp = binary%10;
13 decimal += tmp*Math.pow(2, power);
14 binary = binary/10;
15 power++;
16 }
17 }
18 return decimal;
19 }
20
21 public static void main(String a[]){
22 BinaryToDecimal bd = new BinaryToDecimal();
23 System.out.println("11 ===>
24"+bd.getDecimalFromBinary(11));
25 System.out.println("110 ===>
26"+bd.getDecimalFromBinary(110));
27 System.out.println("100110 ===>
28"+bd.getDecimalFromBinary(100110));
}
}
Output:
11 ===> 3
110 ===> 6
100110 ===> 38
Program: Write a program to check the
given number is binary number or not?
Description:
The binary numeral system, or base-2 number system, represents numeric values
using two symbols: 0 and 1. More specifically, the usual base-2 system is a positional
notation with a radix of 2. Because of its straightforward implementation in digital
electronic circuitry using logic gates, the binary system is used internally by almost
all modern computers.
Code:
?
1 package com.java2novice.algos;
2
3 public class MyBinaryCheck {
4
5 public boolean isBinaryNumber(int binary){
6
7 boolean status = true;
8 while(true){
9 if(binary == 0){
10 break;
11 } else {
12 int tmp = binary%10;
13 if(tmp > 1){
14 status = false;
15 break;
16 }
17 binary = binary/10;
18 }
19 }
20 return status;
21 }
22
23 public static void main(String a[]){
24 MyBinaryCheck mbc = new MyBinaryCheck();
25 System.out.println("Is 1000111
26binary? :"+mbc.isBinaryNumber(1000111));
27 System.out.println("Is 10300111
28binary? :"+mbc.isBinaryNumber(10300111));
}
}
Output:
Is 1000111 binary? :true
Is 10300111 binary? :false
Program: Write a program for Bubble
Sort in java.
Description:
Bubble sort is a simple sorting algorithm that works by repeatedly stepping through
the list to be sorted, comparing each pair of adjacent items and swapping them if
they are in the wrong order. The pass through the list is repeated until no swaps are
needed, which indicates that the list is sorted. The algorithm gets its name from the
way smaller elements bubble to the top of the list. Because it only uses comparisons
to operate on elements, it is a comparison sort. You can see the code
implementation below:
Code:
?
1 package com.java2novice.algos;
2
3 public class MyBubbleSort {
4
5 // logic to sort the elements
6 public static void bubble_srt(int array[]) {
7 int n = array.length;
8 int k;
9 for (int m = n; m >= 0; m--) {
10 for (int i = 0; i < n - 1; i++) {
11 k = i + 1;
12 if (array[i] > array[k]) {
13 swapNumbers(i, k, array);
14 }
15 }
16 printNumbers(array);
17 }
18 }
19
20 private static void swapNumbers(int i, int j, int[] array) {
21
22 int temp;
23 temp = array[i];
24 array[i] = array[j];
25 array[j] = temp;
26 }
27
28 private static void printNumbers(int[] input) {
29
30 for (int i = 0; i < input.length; i++) {
31 System.out.print(input[i] + ", ");
32 }
33 System.out.println("\n");
34 }
35
36 public static void main(String[] args) {
37 int[] input = { 4, 2, 9, 6, 23, 12, 34, 0, 1 };
38 bubble_srt(input);
39
40 }
41}
Output:
2, 4, 6, 9, 12, 23, 0, 1, 34,
Description:
Insertion sort is a simple sorting algorithm that builds the final sorted array one item
at a time. It is much less efficient on large lists than more advanced algorithms such
as quicksort, heapsort, or merge sort. Every repetition of insertion sort removes an
element from the input data, inserting it into the correct position in the
already-sorted list, until no input elements remain. The choice of which element to
remove from the input is arbitrary, and can be made using almost any choice
algorithm. You can see the code implementation below:
Code:
?
1 package com.java2novice.algos;
2
3 public class MyInsertionSort {
4
5 public static void main(String[] args) {
6
7 int[] input = { 4, 2, 9, 6, 23, 12, 34, 0, 1 };
8 insertionSort(input);
9 }
10
11 private static void printNumbers(int[] input) {
12
13 for (int i = 0; i < input.length; i++) {
14 System.out.print(input[i] + ", ");
15 }
16 System.out.println("\n");
17 }
18
19 public static void insertionSort(int array[]) {
20 int n = array.length;
21 for (int j = 1; j < n; j++) {
22 int key = array[j];
23 int i = j-1;
24 while ( (i > -1) && ( array [i] > key ) ) {
25 array [i+1] = array [i];
26 i--;
27 }
28 array[i+1] = key;
29 printNumbers(array);
30 }
31 }
32}
Output:
2, 4, 9, 6, 23, 12, 34, 0, 1,
Description:
The hashcode of a Java Object is simply a number, it is 32-bit signed int, that allows
an object to be managed by a hash-based data structure. We know that hash code is
an unique id number allocated to an object by JVM. But actually speaking, Hash code
is not an unique number for an object. If two objects are equals then these two
objects should return same hash code. So we have to implement hashcode() method
of a class in such way that if two objects are equals, ie compared by equal() method
of that class, then those two objects must return same hash code. If you are
overriding hashCode you need to override equals method also.
The below example shows how to override equals and hashcode methods. The class
Price overrides equals and hashcode. If you notice the hashcode implementation, it
always generates unique hashcode for each object based on their state, ie if the
object state is same, then you will get same hashcode. A HashMap is used in the
example to store Price objects as keys. It shows though we generate different
objects, but if state is same, still we can use this as key.
Code:
?
1 package com.java2novice.algos;
2
3 import java.util.HashMap;
4
5 public class MyHashcodeImpl {
6
7 public static void main(String a[]){
8
9 HashMap<Price, String> hm = new HashMap<Price,
10String>();
11 hm.put(new Price("Banana", 20), "Banana");
12 hm.put(new Price("Apple", 40), "Apple");
13 hm.put(new Price("Orange", 30), "Orange");
14 //creating new object to use as key to get value
15 Price key = new Price("Banana", 20);
16 System.out.println("Hashcode of the key:
17"+key.hashCode());
18 System.out.println("Value from map: "+hm.get(key));
19 }
20}
21
22class Price{
23
24 private String item;
25 private int price;
26
27 public Price(String itm, int pr){
28 this.item = itm;
29 this.price = pr;
30 }
31
32 public int hashCode(){
33 System.out.println("In hashcode");
34 int hashcode = 0;
35 hashcode = price*20;
36 hashcode += item.hashCode();
37 return hashcode;
38 }
39
40 public boolean equals(Object obj){
41 System.out.println("In equals");
42 if (obj instanceof Price) {
43 Price pp = (Price) obj;
44 return (pp.item.equals(this.item) &&
45pp.price == this.price);
46 } else {
47 return false;
48 }
49 }
50
51 public String getItem() {
52 return item;
53 }
54 public void setItem(String item) {
55 this.item = item;
56 }
57 public int getPrice() {
58 return price;
59 }
60 public void setPrice(int price) {
61 this.price = price;
62 }
63
64 public String toString(){
return "item: "+item+" price: "+price;
}
}
Output:
In hashcode
In hashcode
In hashcode
In hashcode
Hashcode of the key: 1982479637
In hashcode
In equals
Value from map: Banana
Program: How to get distinct
elements from an array by avoiding
duplicate elements?
Description:
The below example shows how to avoid duplicate elements from an array and disply
only distinct elements. Please use only arrays to process it.
Code:
?
1 package com.java2novice.algos;
2
3 public class MyDisticntElements {
4
5 public static void printDistinctElements(int[] arr){
6
7 for(int i=0;i<arr.length;i++){
8 boolean isDistinct = false;
9 for(int j=0;j<i;j++){
10 if(arr[i] == arr[j]){
11 isDistinct = true;
12 break;
13 }
14 }
15 if(!isDistinct){
16 System.out.print(arr[i]+" ");
17 }
18 }
19 }
20
21 public static void main(String a[]){
22
23 int[] nums = {5,2,7,2,4,7,8,2,3};
24 MyDisticntElements.printDistinctElements(nums);
25 }
26}
Output:
5 2 7 4 8 3
Program: Write a program to get
distinct word list from the given
file.
Description:
Write a program to find all distinct words from the given file. Remove special chars
like ".,;:" etc. Ignore case sensitivity.
Code:
?
1 package com.java2novice.algos;
2
3 import java.io.BufferedReader;
4 import java.io.DataInputStream;
5 import java.io.FileInputStream;
6 import java.io.FileNotFoundException;
7 import java.io.IOException;
8 import java.io.InputStreamReader;
9 import java.util.ArrayList;
1 import java.util.List;
0 import java.util.StringTokenizer;
1
1 public class MyDistinctFileWords {
1
2 public List<String> getDistinctWordList(String fileName){
1
3 FileInputStream fis = null;
1 DataInputStream dis = null;
4 BufferedReader br = null;
1 List<String> wordList = new ArrayList<String>();
5 try {
1 fis = new FileInputStream(fileName);
6 dis = new DataInputStream(fis);
1 br = new BufferedReader(new
7 InputStreamReader(dis));
1 String line = null;
8 while((line = br.readLine()) != null){
1 StringTokenizer st = new
9 StringTokenizer(line, " ,.;:\"");
2 while(st.hasMoreTokens()){
0 String tmp =
2 st.nextToken().toLowerCase();
1 if(!wordList.contains(tmp))
2 {
2 wordList.add(tmp);
2 }
3 }
2 }
4 } catch (FileNotFoundException e) {
2 e.printStackTrace();
5 } catch (IOException e) {
2 e.printStackTrace();
6 } finally{
2 try{if(br != null)
7 br.close();}catch(Exception ex){}
2 }
8 return wordList;
2 }
9
3 public static void main(String a[]){
0
3 MyDistinctFileWords distFw = new
1 MyDistinctFileWords();
3 List<String> wordList =
2 distFw.getDistinctWordList("C:/sample.txt");
3 for(String str:wordList){
3 System.out.println(str);
3 }
4 }
3 }
5
3
6
3
7
3
8
3
9
4
0
4
1
4
2
4
3
4
4
4
5
4
6
4
7
4
8
4
9
5
0
5
1
5
2
5
3
Output:
the
while
statement
verifies
condition
before
entering
into
loop
to
see
whether
next
iteration
should
occur
or
not
do-while
executes
first
without
checking
it
after
finishing
each
will
always
execute
body
of
a
at
least
once
Program: Write a program to get a
line with max word count from the
given file.
Description:
Below example shows how to find out the line with maximum number of word count
in the given file. In case if it has multiple lines with max number of words, then it has
to list all those lines.
Code:
?
1 package com.java2novice.algos;
2
3 import java.io.BufferedReader;
4 import java.io.DataInputStream;
5 import java.io.FileInputStream;
6 import java.io.FileNotFoundException;
7 import java.io.IOException;
8 import java.io.InputStreamReader;
9 import java.util.ArrayList;
1 import java.util.List;
0
1 public class MaxWordCountInLine {
1
1 private int currentMaxCount = 0;
2 private List<String> lines = new ArrayList<String>();
1
3 public void readMaxLineCount(String fileName){
1
4 FileInputStream fis = null;
1 DataInputStream dis = null;
5 BufferedReader br = null;
1
6 try {
1 fis = new FileInputStream(fileName);
7 dis = new DataInputStream(fis);
1 br = new BufferedReader(new
8 InputStreamReader(dis));
1 String line = null;
9 while((line = br.readLine()) != null){
2
0 int count =
2 (line.split("\\s+")).length;
1 if(count > currentMaxCount){
2 lines.clear();
2 lines.add(line);
2 currentMaxCount = count;
3 } else if(count == currentMaxCount){
2 lines.add(line);
4 }
2 }
5 } catch (FileNotFoundException e) {
2 e.printStackTrace();
6 } catch (IOException e) {
2 e.printStackTrace();
7 } finally{
2 try{
8 if(br != null) br.close();
2 }catch(Exception ex){}
9 }
3 }
0
3 public int getCurrentMaxCount() {
1 return currentMaxCount;
3 }
2
3 public void setCurrentMaxCount(int currentMaxCount) {
3 this.currentMaxCount = currentMaxCount;
3 }
4
3 public List<String> getLines() {
5 return lines;
3 }
6
3 public void setLines(List<String> lines) {
7 this.lines = lines;
3 }
8
3 public static void main(String a[]){
9
4 MaxWordCountInLine mdc = new MaxWordCountInLine();
0 mdc.readMaxLineCount("/Users/ngootooru/MyTestFile.t
4 xt");
1 System.out.println("Max number of words in a line is:
4 "+mdc.getCurrentMaxCount());
2 System.out.println("Line with max word count:");
4 List<String> lines = mdc.getLines();
3 for(String l:lines){
4 System.out.println(l);
4 }
4 }
5 }
4
6
4
7
4
8
4
9
5
0
5
1
5
2
5
3
5
4
5
5
5
6
5
7
5
8
5
9
6
0
6
1
6
2
6
3
6
4
6
5
6
6
6
7
6
8
6
9
7
0
7
1
7
2
7
3
7
4
7
5
7
6
7
7
MyTestFile.txt:
true, false, and null might seem like keywords, but they are actually
literals.
You cannot use them as identifiers in your programs. The servlet context
is an interface which helps to communicate with other servlets. It
contains
information about the Web application and container. It is kind of
application environment. Using the context, a servlet can obtain URL
references to resources, and store attributes that other servlets in the
context can use.
Output:
Max number of words in a line is: 13
Line with max word count:
true, false, and null might seem like keywords, but they are actually
literals.
Description:
Below example shows how to convert string format of a number to number without
calling Integer.parseInt() method. We can do this by converting each character into
ascii format and form the number.
Code:
?
1 package com.java2novice.algos;
2
3 public class MyStringToNumber {
4
5 public static int convert_String_To_Number(String numStr){
6
7 char ch[] = numStr.toCharArray();
8 int sum = 0;
9 //get ascii value for zero
10 int zeroAscii = (int)'0';
11 for(char c:ch){
12 int tmpAscii = (int)c;
13 sum = (sum*10)+(tmpAscii-zeroAscii);
14 }
15 return sum;
16 }
17
18 public static void main(String a[]){
19
20 System.out.println("\"3256\" ==
21"+convert_String_To_Number("3256"));
22 System.out.println("\"76289\" ==
23"+convert_String_To_Number("76289"));
24 System.out.println("\"90087\" ==
"+convert_String_To_Number("90087"));
}
}
Output:
"3256" == 3256
"76289" == 76289
"90087" == 90087
Program: Write a program to find two
lines with max characters in
descending order.
Description:
Write a program to read a multiple line text file and write the 'N' longest lines to the
output console, where the file to be read is specified as command line aruguments.
The program should read an input file. The first line should contain the value of the
number 'N' followed by multiple lines. 'N' should be a valid positive integer.
Code:
?
1 package com.longest.lines;
2
3 import java.io.BufferedReader;
4 import java.io.File;
5 import java.io.FileNotFoundException;
6 import java.io.FileReader;
7 import java.io.IOException;
8 import java.util.Comparator;
9 import java.util.Set;
10import java.util.TreeSet;
11
12public class Main {
13
14 public static void main(String[] args) {
15
16 BufferedReader br = null;
17 String filePath = args[0];
18 int topList = 0;
19 Set<Entries> liSet = new TreeSet<Entries>(new
20MyComp());
21 try {
22 br = new BufferedReader(new FileReader(new
23File(filePath)));
24 String line = br.readLine();
25 topList = Integer.parseInt(line.trim());
26 while((line = br.readLine()) != null){
27 line = line.trim();
28 if(!"".equals(line)){
29 liSet.add(new
30Entries(line.length(), line));
31 }
32 }
33 int count = 0;
34 for(Entries ent:liSet){
35 System.out.println(ent.line);
36 if(++count == topList){
37 break;
38 }
39 }
40 } catch (FileNotFoundException e) {
41 // TODO Auto-generated catch block
42 e.printStackTrace();
43 } catch (IOException e) {
44 // TODO Auto-generated catch block
45 e.printStackTrace();
46 }
47 }
48
49 public static class Entries{
50 Integer length;
51 String line;
52 public Entries(Integer l,String line){
53 length = l;
54 this.line = line;
55 }
56 }
57
58 public static class MyComp implements Comparator<Entries>{
59
60 @Override
61 public int compare(Entries e1, Entries e2) {
62 if(e2.length > e1.length){
63 return 1;
64 } else {
65 return -1;
66 }
67 }
}
}
Sample input file:
3
Java2novice
My Test line 123
Java world
I know java language
Output:
This is a test program
I know java language
My Test line 123
Program: Write a program to find the
sum of the first 1000 prime numbers.
Description:
Write a program to find the sum of the first 1000 prime numbers.
Code:
?
1 package com.primesum;
2
3 public class Main {
4
5 public static void main(String args[]){
6
7 int number = 2;
8 int count = 0;
9 long sum = 0;
10 while(count < 1000){
11 if(isPrimeNumber(number)){
12 sum += number;
13 count++;
14 }
15 number++;
16 }
17 System.out.println(sum);
18 }
19
20 private static boolean isPrimeNumber(int number){
21
22 for(int i=2; i<=number/2; i++){
23 if(number % i == 0){
24 return false;
25 }
26 }
27 return true;
28 }
29}
Output:
3682913
Program: Find longest substring
without repeating characters.
Description:
Given a string, find the longest substrings without repeating characters. Iterate
through the given string, find the longest maximum substrings.
Code:
?
1 package com.java2novice.algos;
2
3 import java.util.HashSet;
4 import java.util.Set;
5
6 public class MyLongestSubstr {
7
8 private Set<String> subStrList = new HashSet<String>();
9 private int finalSubStrSize = 0;
1
0 public Set<String> getLongestSubstr(String input){
1 //reset instance variables
1 subStrList.clear();
1 finalSubStrSize = 0;
2 // have a boolean flag on each character ascii value
1 boolean[] flag = new boolean[256];
3 int j = 0;
1 char[] inputCharArr = input.toCharArray();
4 for (int i = 0; i < inputCharArr.length; i++) {
1 char c = inputCharArr[i];
5 if (flag[c]) {
1 extractSubString(inputCharArr,j,i);
6 for (int k = j; k < i; k++) {
1 if (inputCharArr[k] == c) {
7 j = k + 1;
1 break;
8 }
1 flag[inputCharArr[k]] =
9 false;
2 }
0 } else {
2 flag[c] = true;
1 }
2 }
2 extractSubString(inputCharArr,j,inputCharArr.length
2 );
3 return subStrList;
2 }
4
2 private String extractSubString(char[] inputArr, int start,
5 int end){
2
6 StringBuilder sb = new StringBuilder();
2 for(int i=start;i<end;i++){
7 sb.append(inputArr[i]);
2 }
8 String subStr = sb.toString();
2 if(subStr.length() > finalSubStrSize){
9 finalSubStrSize = subStr.length();
3 subStrList.clear();
0 subStrList.add(subStr);
3 } else if(subStr.length() == finalSubStrSize){
1 subStrList.add(subStr);
3 }
2
3 return sb.toString();
3 }
3
4 public static void main(String a[]){
3 MyLongestSubstr mls = new MyLongestSubstr();
5 System.out.println(mls.getLongestSubstr("java2novic
3 e"));
6 System.out.println(mls.getLongestSubstr("java_langu
3 age_is_sweet"));
7 System.out.println(mls.getLongestSubstr("java_java_
3 java_java"));
8 System.out.println(mls.getLongestSubstr("abcabcbb")
3 );
9 }
4 }
0
Output:
[a2novice]
[uage_is]
[_jav, va_j]
[cab, abc, bca]
Description:
Given array is already sorted, and it has duplicate elements. Write a program to
remove duplicate elements and return new array without any duplicate elements.
The array should contain only unique elements.
Code:
?
1 package com.java2novice.algos;
2
3 public class MyDuplicateElements {
4
5 public static int[] removeDuplicates(int[] input){
6
7 int j = 0;
8 int i = 1;
9 //return if the array length is less than 2
10 if(input.length < 2){
11 return input;
12 }
13 while(i < input.length){
14 if(input[i] == input[j]){
15 i++;
16 }else{
17 input[++j] = input[i++];
18 }
19 }
20 int[] output = new int[j+1];
21 for(int k=0; k<output.length; k++){
22 output[k] = input[k];
23 }
24
25 return output;
26 }
27
28 public static void main(String a[]){
29 int[] input1 = {2,3,6,6,8,9,10,10,10,12,12};
30 int[] output = removeDuplicates(input1);
31 for(int i:output){
32 System.out.print(i+" ");
33 }
34 }
35}
Output:
2 3 6 8 9 10 12
Program: How to sort a Stack using a
temporary Stack?
Description:
You have a stack with full of integers. Sort it in the ascending order using another
temporary array by using all stack functionality.
Code:
?
1 package com.java2novice.algo;
2
3 import java.util.Stack;
4
5 public class StackSort {
6
7 public static Stack<Integer> sortStack(Stack<Integer> input){
8
9 Stack<Integer> tmpStack = new Stack<Integer>();
10 System.out.println("=============== debug logs
11================");
12 while(!input.isEmpty()) {
13 int tmp = input.pop();
14 System.out.println("Element taken out:
15"+tmp);
16 while(!tmpStack.isEmpty() &&
17tmpStack.peek() > tmp) {
18 input.push(tmpStack.pop());
19 }
20 tmpStack.push(tmp);
21 System.out.println("input: "+input);
22 System.out.println("tmpStack: "+tmpStack);
23 }
24 System.out.println("=============== debug logs ended
25================");
26 return tmpStack;
27 }
28
29 public static void main(String a[]){
30
31 Stack<Integer> input = new Stack<Integer>();
32 input.add(34);
33 input.add(3);
34 input.add(31);
35 input.add(98);
36 input.add(92);
37 input.add(23);
System.out.println("input: "+input);
System.out.println("final sorted list:
"+sortStack(input));
}
}
Output:
input: [34, 3, 31, 98, 92, 23]
=============== debug logs ================
Element taken out: 23
input: [34, 3, 31, 98, 92]
tmpStack: [23]
Element taken out: 92
input: [34, 3, 31, 98]
tmpStack: [23, 92]
Element taken out: 98
input: [34, 3, 31]
tmpStack: [23, 92, 98]
Element taken out: 31
input: [34, 3, 98, 92]
tmpStack: [23, 31]
Element taken out: 92
input: [34, 3, 98]
tmpStack: [23, 31, 92]
Element taken out: 98
input: [34, 3]
tmpStack: [23, 31, 92, 98]
Element taken out: 3
input: [34, 98, 92, 31, 23]
tmpStack: [3]
Element taken out: 23
input: [34, 98, 92, 31]
tmpStack: [3, 23]
Element taken out: 31
input: [34, 98, 92]
tmpStack: [3, 23, 31]
Element taken out: 92
input: [34, 98]
tmpStack: [3, 23, 31, 92]
Element taken out: 98
input: [34]
tmpStack: [3, 23, 31, 92, 98]
Element taken out: 34
input: [98, 92]
tmpStack: [3, 23, 31, 34]
Element taken out: 92
input: [98]
tmpStack: [3, 23, 31, 34, 92]
Element taken out: 98
input: []
tmpStack: [3, 23, 31, 34, 92, 98]
=============== debug logs ended ================
final sorted list: [3, 23, 31, 34, 92, 98]