1. Write a program to sort ArrayList using Comparable and Comparator

Solution: Sort ArrayList using Comparable

import java.util.ArrayList;

import java.util.Collections;

//Using Comparable

class Employee implements Comparable<Employee> {

     private String name;

     private int empId;

     private int age;

   

     public Employee(String name, int empId, int age) {

           this.name= name;

           this.empId=empId;

           this.age=age;

     }

     

    @Override

    public int compareTo(Employee employee) {

           return this.age - employee.age;

    }

   

    @Override

    public String toString() {

           return "[ Name= " + name + ", Employee Id = " + empId + ", Employee age = " + age + "]";

    }

}

class Main {

    public static void main(String[] args) {

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

          list.add(new Employee("Rahul",6589586,35));

          list.add(new Employee("John",854756,30));

          list.add(new Employee("Robin",784125,32));

         

           Collections.sort(list);

           for(Employee e: list){

                      System.out.println(e);

             }

    }

}

Output:

[ Name= John, Employee Id = 854756, Employee age = 30]

[ Name= Robin, Employee Id = 784125, Employee age = 32]

[ Name= Rahul, Employee Id = 6589586, Employee age = 35]

Solution: Sort ArrayList using Comparator

import java.util.ArrayList;

import java.util.Collections;

import java.util.Comparator;

//Using Comparator

class Employee {

    private String name;

    private int empId;

    private int age;

    public Employee(String name, int empId, int age) {

          this.name = name;

          this.empId = empId;

          this.age = age;

    }

    public String getName() {

          return this.name;

    }

    public int getEmpId() {

          return this.empId;

    }

    public int getAge() {

          return this.age;

    }

    public static Comparator<Employee> EmployeeNameComparator = new Comparator<Employee>() {

          public int compare(Employee e1, Employee e2) {

                String empName1 = e1.getName().toLowerCase();

                String empName2 = e2.getName().toLowerCase();

                return empName1.compareTo(empName2);

          }

    };

    public static Comparator<Employee> EmployeeAgeComparator = new Comparator<Employee>() {

          public int compare(Employee e1, Employee e2) {

                int empAge1 = e1.getAge();

                int empAge2 = e2.getAge();

                return empAge1 - empAge2;

          }

    };

    @Override

    public String toString() {

          return "[ Name= " + name + ", Employee Id = " + empId + ", Employee age = " + age + "]";

    }

}

class Main {

    public static void main(String[] args) {

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

          list.add(new Employee("Rahul", 6589586, 35));

          list.add(new Employee("John", 854756, 32));

          list.add(new Employee("Lukas", 784125, 30));

          System.out.println("Sort Employee List by Name");

          Collections.sort(list, Employee.EmployeeNameComparator);

          for (Employee e : list) {

                System.out.println(e);

          }

          System.out.println("\nSort Employee List by Age");

          Collections.sort(list, Employee.EmployeeAgeComparator);

          for (Employee e : list) {

                System.out.println(e);

          }

    }

}

Output:

Sort Employee List by Name

[ Name= John, Employee Id = 854756, Employee age = 32]

[ Name= Lukas, Employee Id = 784125, Employee age = 30]

[ Name= Rahul, Employee Id = 6589586, Employee age = 35]

Sort Employee List by Age

[ Name= Lukas, Employee Id = 784125, Employee age = 30]

[ Name= John, Employee Id = 854756, Employee age = 32]

[ Name= Rahul, Employee Id = 6589586, Employee age = 35]

import java.util.ArrayList;

class Main {

    public static void main(String[] args) {

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

          list.add("Test1");

          list.add("Test1");

          list.add("Test2");

          list.add("Test3");

          list.add("Test4");

         

          System.out.println("ArrayList before Replace");

          System.out.println(list);

         

          int index = list.indexOf("Test2");

          list.set(index,"ReplacedTest");

         

          System.out.println("\nArrayList after Replace");

          System.out.println(list);

    }

}

Output:

ArrayList before Replace

[Test1, Test1, Test2, Test3, Test4]

ArrayList after Replace

[Test1, Test1, ReplacedTest, Test3, Test4]

import java.util.LinkedList;

class Main {

    public static void main(String[] args) {

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

          list.add("Test1");

          list.add("Test1");

          list.add("Test2");

          list.add("Test3");

          list.add("Test4");

         

          System.out.println("LinkedList before Inserting Element at the End/Last");

          System.out.println(list);

         

          list.offerLast("LastInsertedElement");

         

          System.out.println("\nLinkedList after Inserting Element at the End/Last");

          System.out.println(list);

    }

}

Output:

LinkedList before Inserting Element at the End/Last

[Test1, Test1, Test2, Test3, Test4]

LinkedList after Inserting Element at the End/Last

[Test1, Test1, Test2, Test3, Test4, LastInsertedElement]

4. Write a program to perform Pairwise swap elements of a given linked list

In Pairwise swapping each pair will be swapped

Example:

Input  1 > 2 > 3 > 4 > 5

Output 2 > 1 > 4 > 3 > 5

Solution:

//Pairwise Swap

public class LinkedList {

    Node head;

    class Node {

          int data;

          Node next;

          Node(int d)

          {

                data = d;

                next = null;

          }

    }

    void pairWiseSwap()

    {

          Node temp = head;

          while (temp != null && temp.next != null) {

                int k = temp.data;

                temp.data = temp.next.data;

                temp.next.data = k;

                temp = temp.next.next;

          }

    }

    public void push(int new_data)

    {

          Node new_node = new Node(new_data);

          new_node.next = head;

          head = new_node;

    }

    void print()

    {

          Node temp = head;

          while (temp != null) {

                System.out.print(temp.data + " ");

                temp = temp.next;

          }

          System.out.println();

    }

    public static void main(String args[])

    {

          LinkedList list = new LinkedList();

          list.push(5);

          list.push(4);

          list.push(3);

          list.push(2);

          list.push(1);

          System.out.println("Linked List before PairWise Swap ");

          list.print();

          list.pairWiseSwap();

          System.out.println("Linked List after PairWise Swap");

          list.print();

    }

}

Output:

Linked List before PairWise Swap

1 2 3 4 5

Linked List after PairWise Swap

2 1 4 3 5

5. Check if two arrays have same number of items and values

Consider I have two arrays

a = [1,2,3,4]

b = [2,1,4,3]

Considering the above array, We have the same Item in both the arrays, but the index is different

Write a program to check a is having the same number of items and same values compared with b

You should not use Arrays.Equals() method

Solution:

There are two requirements here

1. Number of Elements in a[] should be same as b[] //a.length == b.length

2. Both a[] and b[] should have the same element, order sequence can be different

3. You should not use Arrays.Equals method

import java.util.Arrays;

public class Main {

    public static void main(String args[]) {

          int[] array1 = { 1, 2, 3, 4 };

          int[] array2 = { 2, 1, 4, 3 };

          boolean b = false;

          if (array1.length != array2.length) {

                 b = false;

          } else {

                Arrays.sort(array1);

                Arrays.sort(array2);

                for(int i=0;i<array1.length;i++) {

                      if(array1[i]!=array2[i]) {

                            b=false;

                            break;

                      }

                      b=true;

                }

          }

          if (b)

                System.out.println("Arrays are having same values");

          else

                System.out.println("Arrays are not having same values");

    }

}

Output:

Arrays are having same values

public class Main {

     public static void main(String[] args){

           String string = "Rahul Shetty Academy is the best";

           String[] words = string.trim().replaceAll("\\s+", " ").split(" ");

              String shortest = words[0];

              String longest =  words[0];

              for(String word : words){

                if(word.length() < shortest.length()){

                      shortest = word;

                  }

                if(word.length() > longest.length()){

                      longest = word;

                  }

              }

              System.out.println("The Shortest Word = "+shortest);  

              System.out.println("The Longest Word = "+ longest);

      } 

}

Output:

The Shortest Word = is

The Longest Word = Academy

7. Java Program to Check if a Given Number is Perfect Square

A perfect square is a positive integer, it is the product of the number itself

Example:

49 = 7*7, So the 49 is Perfect Square

Solution:

class Main {

    static boolean isPerfectSquare(int x)

    {

          if (x >= 0) {

                int sqrt = (int)Math.sqrt(x);

                return ((sqrt*sqrt) == x);

          }

          return false;

    }

    public static void main(String[] args)

    {

          int x = 8100;

          if (isPerfectSquare(x))

                System.out.print("Given Number is a Perfect Square");

          else

                System.out.print("Given Number is Not a Perfect Square");

    }

}

Output:

Given Number is a Perfect Square

8. Write a Program to cover all major concepts of OOPs

Note: There are multiple ways to write this program, we have shown one way.

Solution:

//Abstraction

interface Car {

    void printName();

}

//Inheritance

class Ford {

    private String name; //Encapsulation

    public String getName() {

          return name;

    }

    public void setName(String newName) {

          name = newName;

    }

}

class OneMore extends Ford implements Car{

    @Override //Overriding

    public void printName() {

          System.out.println("Override Method Print " + super.getName());

         

    }

    //Overloading

    public void printName(String string) {

          System.out.println("Overloaded Method Print " + string);

    }

}

class Main {

    public static void main(String[] args) {

          OneMore object = new OneMore();

          object.setName("Eco Sport");

          object.printName();

          object.printName("Aspire");

    }

}

Output:

Overloading Print Eco Sport

Overloading Print Aspire

9. Write a program to find the length of the string without using string.length();

Note: There are multiple ways to write this program, we have shown one way.

Solution:

public class Main

{

    static int i,c,res;

    static void length(String s)

    {

        try

        {

            for(i=0,c=0;0<=i;i++,c++)

            s.charAt(i);

        }

        catch(StringIndexOutOfBoundsException e)

        {

          System.out.println("");

            System.out.print("The length of the string \""+s+"\" is " +c);

        }

    }

   

    public static void main (String args[])

    {

        String string = "Rahul Shetty Academy";

        length(string);

    }

}

Output:

The length of the string "Rahul Shetty Academy" is 20

Course Alert

If you are interested in landing a SDET or Sr. QA Automation Engineer role, check out our popular SDET course to learn the fundamental skills required an SDET needs to perform at work. Also, I have another popular course which covers Top 150+ Interview questions most commonly asked in SDET / Automation interviews.

A Quick Note

Please remember all these courses comes with 100% Lifetime access and free updates for Lifetime!!

With this we end the 5-part series of Sr.QA and SDET Interview Questions in Java. Please click on the link Top 30 API Testing Interview Questions and Answers – Part 1 to where we will cover Top API Interview questions.


Tags


You may also like

API Basics and Architecture

API Basics and Architecture
Leave a Reply

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

{"email":"Email address invalid","url":"Website address invalid","required":"Required field missing"}