HomeAutomation

Java for Testers Interview Questions And Answers – Part 7

Java for Testers Interview Questions And Answers – Part 7

Java for Testers – Interview Questions and Answers Part-7

1. What is threading?

– A thread is a lightweight subprocess, the smallest unit of processing.
– It is a separate path of execution.
– Threads are independent.
– If there occurs exception in one thread, it doesn’t affect other threads.
– It uses a shared memory area.

2. How does multi-threading is achieved?

– Multithreading can be achieved by executing two or more threads simultaneously to maximum utilization of CPU.
– Multithreaded applications execute two or more threads run concurrently.
– Each thread runs parallel to each other.

3. How to initiate a thread in Java?

Thread can be initiated by the following ways:
– Extending the Thread class
– Implementing the Runnable Interface

4. What do you mean by thread safe?

Thread-safe code is code that will work even if many Threads are executing it simultaneously.
A piece of code is thread-safe if it only manipulates shared data structures in a manner that guarantees safe execution by multiple threads at the same time.

5. What is the difference between collection and collections?

The Collection is an interface whereas Collections is a class. The Collection interface provides the standard functionality of data structure to List, Set, and Queue. However, Collections class is to sort and synchronize the collection elements.

6. What is a Collection and what are the types of collections?

A Collection is a group of individual objects represented as a single unit. Java provides Collection Framework which defines several classes and interfaces to represent a group of objects as a single unit.
Different types of Collection are:
– Set
– List
– Map
– Queue

7. What is the difference between Array and ArrayList?

– Array is static in size but ArrayList is dynamic in size.
– It is mandatory to provide the size of array during initialization while arraylist can be created without declaring its size.
– Array is faster than Arraylist.
– Array can be multidimensioanl but Arraylist is always single-dimensional.

8. What is the difference between Set and HashSet?

– Set is an interface, HashSet – implementation of interface.
– The Set interface represents a set of some objects, non-ordered, without random-element access. HashSet – implementation of the Set interface, based on the .hashCode() function.

9. What is the difference between HashMap and HashTable?

– HashMap is non synchronized and not thread safe but HashTable is synchronized and thread safe
– HashMap allows one null key and multiple null values but HashTable doesn’t allow any null key or value
– HashMap is faster than HashTable

10. What is the difference between ArrayList and LinkedList?

– Insertions are easy and fast in LinkedList as compared to ArrayList.
– An ArrayList class can act as a list only because it implements List only. List only. LinkedList class can act as a list and queue both because it implements List and Deque interfaces.
– ArrayList internally uses a dynamic array to store the elements. LinkedList internally uses a doubly linked list to store the elements.

11. Write a Java program to calculate the power of a number using a while loop?

public class Power {
public static void main(String[] args) {
int base = 3, exponent = 4;
long result = 1;
while (exponent != 0)
{
result *= base;
--exponent;
}
System.out.println("Answer = " + result);
}
}

12. Can we have duplicate key value in HashMap?

HashMap doesn’t allow duplicate keys but allows duplicate values.

13. How to fetch values from a HashMap?

The java.util.HashMap.get() method of HashMap class is used to retrieve or fetch the value mapped by a particular key mentioned in the parameter.
Hash_Map.get(Object key_element)

14. Write a Java program to verify whether a number is perfect number or not?

class PerfectNumber 
{  
static boolean isPerfect(int n) 
{ 
    int sum = 1; 
    for (int i = 2; i * i <= n; i++) 
    { 
        if (n % i==0) 
        { 
            if(i * i != n) 
                sum = sum + i + n / i; 
            else
                sum = sum + i; 
        } 
    }  
    if (sum == n && n != 1) 
        return true; 
  
    return false; 
} 
public static void main (String[] args) 
{ 
    System.out.println("Below are all perfect" +  
                                "numbers till 10000"); 
    for (int n = 2; n < 10000; n++) 
        if (isPerfect(n)) 
            System.out.println( n +  
                    " is a perfect number"); 
} 
}

 

15. Write a Java program for printing the Fibonacci series from 1 to 10?

class FibonacciNumber
{ 
    // Method to print first n Fibonacci Numbers 
    static void printFibonacciNumbers(int n) 
    { 
        int f1 = 0, f2 = 1, i; 
      
        if (n < 1) 
            return; 
      
        for (i = 1; i <= n; i++) 
        { 
            System.out.print(f2+" "); 
            int next = f1 + f2; 
            f1 = f2; 
            f2 = next; 
        } 
    }  
    public static void main(String[] args)  
    { 
        printFibonacciNumbers(10); 
    } 
}

 

16. Write a Java program to find the greatest of three numbers?

public class GreatestNumber {
   public static void main(String args[]) {
      int num1 = 10;
      int num2 = 21;
      int num3 = 7;
      if (num1 >= num2 && num1 >= num3)
         System.out.println( num1 + " is the maximum number.");
      else if (num2 >= num1 && num2 >= num3)
         System.out.println( num2 + " is the maximum number.");
      else
         System.out.println( num3 + " is the maximum number.");
   }
}

 

17. Find and print the largest two numbers from an array of given numbers?

public class LargestTwoNumbers
{
    public static void main (String[] args)
    {
        Scanner scn = new Scanner (System.in);
        System.out.print("Enter no. of elements you want in array:");
                int n = scn.nextInt();
 
        int array[] = new int[n];
                System.out.println("Enter all the elements:");
        for (int i = 0; i < array.length; i++)
        {
            array[i] = scn.nextInt();
        }
 
        int largest1, largest2, temp;
 
        largest1 = array[0];
        largest2 = array[1];
 
        if (largest1 < largest2)
        {
            temp = largest1;
            largest1 = largest2;
            largest2 = temp;
        }
 
        for (int i = 2; i < array.length; i++)
        {
            if (array[i] > largest1)
            {
                largest2 = largest1;
                largest1 = array[i];
            }
            else if (array[i] > largest2 && array[i] != largest1)
            {
                largest2 = array[i];
            }
        }
 
        System.out.println ("The First largest is " + largest1);
        System.out.println ("The Second largest is " + largest2);
 
    }
}

 

18. In the given String, remove the white spaces, reverse it and print only the odd position characters?

public Class PrintOddChars{
public static void main(String[] args) {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Enter the string: ");
        String name = br.readLine();
        String odd = "";
        String reversedString = reverseString(name.replaceAll("\\s",""));
        for(int i=0;i<reversedString.length();i++){
            if(i%2!=0){
              odd = odd + reversedString.charAt(i);
            }

        }
        System.out.println(odd);
    }
    public static String reverseString(String s){
        String rev="";
        char[] arr = s.toCharArray();
        for(int i=arr.length-1;i>=0;i--)
            rev = rev + arr[i];
        return rev;
    }
}

 

19. Check whether a string is anagram of another string?

public class AnagramString {  
    static void isAnagram(String str1, String str2) {  
        String s1 = str1.replaceAll("\\s", "");  
        String s2 = str2.replaceAll("\\s", "");  
        boolean status = true;  
        if (s1.length() != s2.length()) {  
            status = false;  
        } else {  
            char[] ArrayS1 = s1.toLowerCase().toCharArray();  
            char[] ArrayS2 = s2.toLowerCase().toCharArray();  
            Arrays.sort(ArrayS1);  
            Arrays.sort(ArrayS2);  
            status = Arrays.equals(ArrayS1, ArrayS2);  
        }  
        if (status) {  
            System.out.println(s1 + " and " + s2 + " are anagrams");  
        } else {  
            System.out.println(s1 + " and " + s2 + " are not anagrams");  
        }  
    }  
}

 

20. In a given string, change few characters to upper case as asked?

public class ChangeCharCase {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Enter the string: ");
        String name = br.readLine();
        String s1 = name.substring(0, 1).toUpperCase();
        String nameCapitalized = s1 + name.substring(1);
        System.out.println(nameCapitalized);
    }
}

 

21. In a given string, print the occurrence of each character?

public class FindFrequencyOfCharactersInString {
    public static void main(String[] args){
        Map<Character,Integer> map = new HashMap<>();
        map = findFrequency("Java J2EE Java JSP J2EE");
        for(Map.Entry<Character,Integer> entry: map.entrySet()){
            System.out.println("Frequency of character " + entry.getKey() + " is "+ entry.getValue());
        }
    }
    public static Map<Character,Integer> findFrequency(String input){
        char[] arr = input.toLowerCase().replaceAll("\\s+","").toCharArray();
        Map<Character,Integer> frequency = new HashMap<>();
        for(char c: arr){
            if(frequency.containsKey(c)){
                frequency.put(c,frequency.get(c) + 1);
            }
            else{
                frequency.put(c,1);
            }
        }
        return frequency;
    }
}

 

22. Find the duplicate strings in a given statement and remove them?

public class RemoveDuplicateWords 
{
    public static void main(String[] args)
    {
        String input="Welcome to QAScript Java Interview Question in QAScript"; 		
        String[] words=input.split(" ");
        for(int i=0;i<words.length;i++)	
        {
            if(words[i]!=null)
            {
            for(int j=i+1;j<words.length;j++)
            {			
            if(words[i].equals(words[j]))
                {
                    words[j]=null;
                }
            }
        }
    }
        for(int k=0;k<words.length;k++)
        {
            if(words[k]!=null)
            {
                System.out.println(words[k]);
            }
            
         }  
    }
}

 

23. Use split method to print each word of a statement?

public class SplitStatement{  
public static void main(String args[]){  
String strMain ="Welcome to QAScript"; 
String[] arrSplit = strMain.split("\\s");
    for (int i=0; i < arrSplit.length; i++){
      System.out.println(arrSplit[i]);
    }
  }
}

 

24. Find and remove the duplicate characters from a given string and print ?

public static String removeDuplicates(String word){
    Set<Character> chars = new HashSet<>();
    StringBuilder output = new StringBuilder(word.length());
    for (int i = 0; i < word.length(); i++) {
    char ch = word.charAt(i);
    if (chars.add(ch)) {
    output.append(ch);
    }
   }
   return output.toString();
}

 

25. Write a Java program to print the triangle of numbers?

public class FloydTriangle {
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the number of rows");
        int rows = sc.nextInt();
        printFloydTriangle(rows);
    }
    public static void printFloydTriangle(int n){
        int number = 1;
        for(int i=0;i<n;i++){
            for(int j=0;j<=i;j++){
                System.out.print(number +" ");
                number++;
            }
            System.out.println();
        }
    }
}

 

Next Steps:

> More interview questions and answers on Java, continue to the next post (Click on Next Post link below)

> Check complete Java interview questions and answers here (Click here)

Please leave your questions/comments/feedback below.

Happy Learning 🙂

About Me > Bijan Patel

Connect to me on Linked In (Click here)

On a mission to contribute to the Software Testing Community in all possible ways.

Comments (0)

Leave a Reply

Your email address will not be published. Required fields are marked *