Interview Questions and answer for 3-5 Years Exp

Write a program:
1: To create deadlock between two threads.
2: Find out duplicate number between 1 to N numbers.
3. Write a program to find maximum repeated words from a file.
4. To remove duplicates from sorted array.
5. Simple generics class example with two type parameters.
6. Write SQL Query to find second highest salary of Employee





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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package com.java2novice.algos;

public class MyDeadlock {

    String str1 = "Java";
    String str2 = "UNIX";
     
    Thread trd1 = new Thread("My Thread 1"){
        public void run(){
            while(true){
                synchronized(str1){
                    synchronized(str2){
                        System.out.println(str1 + str2);
                    }
                }
            }
        }
    };
     
    Thread trd2 = new Thread("My Thread 2"){
        public void run(){
            while(true){
                synchronized(str2){
                    synchronized(str1){
                        System.out.println(str2 + str1);
                    }
                }
            }
        }
    };
     
    public static void main(String a[]){
        MyDeadlock mdl = new MyDeadlock();
        mdl.trd1.start();
        mdl.trd2.start();
    }
}
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:
package com.java2novice.algos;

import java.util.ArrayList;
import java.util.List;

public class DuplicateNumber {

        public int findDuplicateNumber(List numbers){
              
               int highestNumber = numbers.size() - 1;
               int total = getSum(numbers);
               int duplicate = total - (highestNumber*(highestNumber+1)/2);
               return duplicate;
        }
       
        public int getSum(List numbers){
              
               int sum = 0;
               for(int num:numbers){
                       sum += num;
               }
               return sum;
        }
       
        public static void main(String a[]){
               List numbers = new ArrayList();
               for(int i=1;i<30 i="" o:p="">
                       numbers.add(i);
               }
               //add duplicate number into the list
               numbers.add(22);
               DuplicateNumber dn = new DuplicateNumber();
               System.out.println("Duplicate Number: "+dn.findDuplicateNumber(numbers));
        }
}

Output:
Duplicate Number: 22

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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package com.java2novice.algos;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.Map.Entry;

public class MaxDuplicateWordCount {
     
    public Map getWordCount(String fileName){

        FileInputStream fis = null;
        DataInputStream dis = null;
        BufferedReader br = null;
        Map wordMap = new HashMap();
        try {
            fis = new FileInputStream(fileName);
            dis = new DataInputStream(fis);
            br = new BufferedReader(new InputStreamReader(dis));
            String line = null;
            while((line = br.readLine()) != null){
                StringTokenizer st = new StringTokenizer(line, " ");
                while(st.hasMoreTokens()){
                    String tmp = st.nextToken().toLowerCase();
                    if(wordMap.containsKey(tmp)){
                        wordMap.put(tmp, wordMap.get(tmp)+1);
                    } else {
                        wordMap.put(tmp, 1);
                    }
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally{
            try{if(br != null) br.close();}catch(Exception ex){}
        }
        return wordMap;
    }
     
    public List> sortByValue(Map wordMap){
         
        Set> set = wordMap.entrySet();
        List> list = new ArrayList>(set);
        Collections.sort( list, new Comparator>()
        {
            public int compare( Map.Entry o1, Map.Entry o2 )
            {
                return (o2.getValue()).compareTo( o1.getValue() );
            }
        } );
        return list;
    }
     
    public static void main(String a[]){
        MaxDuplicateWordCount mdc = new MaxDuplicateWordCount();
        Map wordMap = mdc.getWordCount("C:/MyTestFile.txt");
        List> list = mdc.sortByValue(wordMap);
        for(Map.Entry entry:list){
            System.out.println(entry.getKey()+" ==== "+entry.getValue());
        }
    }
}

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 remove duplicates from sorted array.

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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package com.java2novice.algos;

public class MyDuplicateElements {

    public static int[] removeDuplicates(int[] input){
         
        int j = 0;
        int i = 1;
        //return if the array length is less than 2
        if(input.length < 2){
            return input;
        }
        while(i < input.length){
            if(input[i] == input[j]){
                i++;
            }else{
                input[++j] = input[i++];
            }   
        }
        int[] output = new int[j+1];
        for(int k=0; k
            output[k] = input[k];
        }
         
        return output;
    }
     
    public static void main(String a[]){
        int[] input1 = {2,3,6,6,8,9,10,10,10,12,12};
        int[] output = removeDuplicates(input1);
        for(int i:output){
            System.out.print(i+" ");
        }
    }
}

Output:
2 3 6 8 9 10 12
Program: Write a simple generics class example with two type parameters.

Below example shows how to create a simple generics class with two type parameters. Look at the class definition, we defined two types of parameters called U & V, seperated by ",". You can define multiple type parameters seperated by ",". Look at sample code for more comments.

package com.java2novice.generics;

public class MySimpleTwoGenerics {

        public static void main(String a[]){
              
               SimpleGen sample
                                      = new SimpleGen("JAVA2NOVICE", 100);
               sample.printTypes();
        }
}

/**
 * Simple generics class with two type parameters U, V.
 */
class SimpleGen{
       
        //type U object reference
        private U objUreff;
        //type V object reference
        private V objVreff;
       
        //constructor to accept object type U and object type V
        public SimpleGen(U objU, V objV){
               this.objUreff = objU;
               this.objVreff = objV;
        }
       
        public void printTypes(){
               System.out.println("U Type: "+this.objUreff.getClass().getName());
               System.out.println("V Type: "+this.objVreff.getClass().getName());
        }
}

Output:
U Type: java.lang.String
V Type: java.lang.Integer

SQL Query to find second highest salary of Employee

Answer : There are many ways to find second highest salary of Employee in SQL, you can either use SQL Join or Subquery to solve this problem. Here is SQL query using Subquery :

 select MAX(Salary) from Employee WHERE Salary NOT IN (select MAX(Salary) from Employee );

No comments:

Post a Comment