1. How can we achieve Pass by value and pass by reference in Java?

If we consider primitive types in a method, it is always pass by value.

For non-primitive types, it is always references (Object, Class)

Consider Non-Primitive Types we can explain how value changes.

Pass by Value like behavior can be achieved by assigning reference

Example Code Snippet : Pass by value like behavior

// Works like pass by value

class Test

{

    int x;

    Test(int i) { x = i; }

    Test()      { x = 0; }

}

public class Main

{

    public static void main(String[] args)

    {

          // t is a reference

          Test t = new Test(5);

          // Reference is passed and a copy of reference

          // is created in change()

          change(t);

          System.out.println(t.x);

    }

    public static void change(Test t)

    {

          t = new Test(); // Changes doesn't reflect, since assigning reference

          t.x = 10;

    }

}

//Output:5

Example Code Snippet : Pass by Reference behavior can be achieved if we don’t assign the reference

// Behaves like pass by reference

class Test

{

    int x;

    Test(int i) { x = i; }

    Test()      { x = 0; }

}

public class Main

{

    public static void main(String[] args)

    {

          // t is a reference

          Test t = new Test(5);

          // Reference is passed and a copy of reference

          // is created in change()

          change(t);

          System.out.println(t.x);

    }

    public static void change(Test t)

    {

          t.x = 10; //Changes reflects since we are not assigning t (refer first example)

    }

}

//Output: 10

2. Explain Different types of interfaces in the Collection framework

Note: The answer to this question is lengthy, Interviewer might ask few collections or all. To make it easier for you, we have given a short answer here with bullet points.


(You do not have to draw this diagram in the interview, this is for your easy understanding)

The Collection in Java is a framework that provides an architecture to store and manipulate a group of objects. Java collection makes easier perform operation like searching, sorting and manipulate data.

  • Java util package contains the collection related classes and interfaces

Collection Interfaces in Java.

Iterable Interface

The Iterable interface is the root interface for all the collection classes

Collection Interface

The Collection interface is the interface that is implemented by all the classes in the collection framework

List Interface

  • List interface is the subinterface of the Collection interface
  • ArrayList
  • The ArrayList class implements the List interface
  • The ArrayList Uses a dynamic array to store the duplicate element of different data types
  • The ArrayList maintains the insertion order
  • The ArrayList can be randomly accessed
  • The ArrayList is not synchronized
  • LinkedList
  • Uses doubly linked list internally to store the elements
  • It can store the duplicate elements
  • It maintains the insertion order
  • It is not synchronized
  • Vector
  • Similar to ArrayList but synchronized
  • Stack
  • Sub class of vector
  • It implements the last-in-first-out data structure

Queue Interface

Queue interface maintains the first-in-first-out order, it is an ordered list that is used to hold the elements which are about to be processed

  • PriorityQueue
  • PriorityQueue class implements the Queue interface
  • It holds the elements or objects which are to be processed by their priorities
  • It doesn't allow null values

Deque Interface

Deque interface extends the Queue interface, We can remove and add the elements from both the side, it helps us to perform the operations at both the ends.

  • ArrayDeque
  • ArrayDeque class implements the Deque interface
  • It facilitates us to use the Deque
  • We can add or delete the elements from both ends.

Set Interface

It extends the Collection interface, It represents the unordered set and it doesn't allow us to store the duplicate items. It allows only one null value.

  • HashSet
  • This class implements Set Interface
  • HashSet uses a hash table for storage
  • Hashing is used to store the elements in the HashSet
  • It contains unique items
  • LinkedHashSet
  • LinkedHashSet class represents the LinkedList implementation
  • It extends the HashSet class and implements the Set interface
  • Like HashSet, It also contains unique elements
  • It maintains the insertion order and permits null elements.

SortedSet Interface

SortedSet is the alternate of the Set interface that provides a total ordering on its elements, The elements of the SortedSet are arranged in the increasing order

  • TreeSet
  • TreeSet class implements the Set interface
  • Uses a tree for storage
  • TreeSet also contains unique elements
  • The elements in TreeSet are stored in ascending order

Map Interface

A map contains values based on the key, i.e. key and value pair, It takes the key, and the value pair is known as an entry. A Map is useful if you have to search, update or delete elements based on a key, A Map doesn't allow duplicate keys but allows duplicate values.

  • HashMap
  • HashMap is the implementation of Map
  • It doesn't maintain any order
  • LinkedHashMap
  • LinkedHashMap is the implementation of Map
  • It inherits the HashMap class
  • It maintains insertion order
  • TreeMap
  • TreeMap is the implementation of Map and SortedMap
  • It maintains ascending order.

3. What is the difference between Array List and LinkedList? Which is better explain?

  • ArrayList Uses Dynamic Array to Store, LinkedList uses a doubly linked list to store elements.
  • ArrayList is better for storing and accessing data, LinkedList is better for manipulating data
  • The ArrayList class can act as a list only because it implements only List. LinkedList class can act as a list and queue both because it implements both List and Deque interfaces

Which is better ArrayList or LinkedList?

  • It depends on the purpose we are using,
  • ArrayList is good for accessing and sorting
  • LinkedList is good for manipulation
  • If you remove the element from an array, bit shifting is required at the memory level
  • LinkedList is a doubly-linked list so bit shifting is not needed

4. What is the difference between List and Set?

  • The List is an ordered sequence. The Set is an unordered sequence
  • The list allows duplicate elements. Set doesn’t allow duplicate elements
  • The list can hold multiple nulls. The set allows only one null
  • The list allows access items by index, Set doesn’t allow access by index
  • ArrayList, LinkedList, Vector, Stack are an example for List implementation. HashSet, LinkedHashSet, etc. are the implementation of Set.

5. What is the difference between HashSet and HashMap?

  • HashSet implements Set interface, HashMap implements Map interface
  • HashSet doesn’t allow duplicates. HashMap only duplicate values are allowed, keys are still unique
  • A single object can be added to HashSet, For HashMap adding an item requires at least a key-value pair so it will be two objects
  • HashSet allows single null value, HashMap allows Single null key and any number of null values.

6. Explain Collection and Collections in Java?

  • The collection is an interface, with the Collection interface we can group various objects into a single unit. Collections is simply a utility class that is found in java.util package
  • Collection can be considered as the root for major interfaces like Sets, Lists, Maps, Queue, Deque. Collections provide a method for developers to perform certain basic operations on elements.
  • Not all the methods inside Collection is static. Collections has all static method
  • Collection is used to store the list of objects in a single object. Collections is used to operate on a collection.

7. Explain the difference between Comparable and Comparator.

  • Comparable provides a single sorting sequence. The Comparator provides multiple sorting sequences
  • Comparable allows us to sort the collection on the basis of a single element such as id or name etc. Comparator allows us to sort the collection on the basis of multiple elements such as id and name etc
  • The actual class is modified with Comparable. Comparator doesn't modify the actual class
  • Comparable provides compareTo() method to sort elements. Comparator provides compare() method to sort elements.
  • Comparable is present in java.lang package. A Comparator is present in java.util package.
  • We can sort the list elements of Comparable type by Collections.sort(List) method. We can sort the list elements of Comparator type by Collections.sort(List, Comparator) method.

8. Are Array and Array List are the same? If Not, How do we convert them to each other?

Array and ArrayList are not the same. The array is a fixed-length data structure whereas ArrayList is a variable-length Collection class. We cannot change the length of the array once created in Java but ArrayList can be changed.

Example Code Snippet : Covert ArrayList into Array

import java.util.ArrayList;

import java.util.Arrays;

//Convert ArrayList into array

public class Main {

    public static void main(String[] args) {

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

          list.add("One");

          list.add("Two");

          list.add("Three");

          list.add("Four");

          System.out.println("Print elements inside List => " + list.toString());

          // Convert to array

          Object[] array = list.toArray();

          System.out.println("Print elements inside Array => " + Arrays.toString(array));

          // Iterate through one by one and convert them into string

          for (Object o : array) {

                String s = (String) o;

                System.out.println(s);

          }

    }

}

Output:

Print elements inside List => [One, Two, Three, Four]

Print elements inside Array => [One, Two, Three, Four]

One

Two

Three

Four

Example Code Snippet : Convert Array to List

import java.util.*;

//Convert array to List

class Main {

    public static void main(String[] args) {

          String[] stringArray = { "One", "Two", "Three", "Four" };

          System.out.println("Printing Array = > " + Arrays.toString(stringArray));

          // Convert array to List

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

          Collections.addAll(list, stringArray);

          System.out.println("Printing ArrayList = > " + list);

    }

}

Output:

Printing Array = > [One, Two, Three, Four]

Printing ArrayList = > [One, Two, Three, Four]

9. What is Generic Class? Could you explain with a small snippet?

A class that can refer to any type is known as a generic class. That means it has parametrized types. It can allow many types such as String, Integer, or User Defined Types parameter to Class

import java.util.*;

//Generic Class it accepts any type

class GenericClass<T> {

    T object;

    void add(T object) {

          this.object = object;

    }

    T get() {

          return this.object;

    }

}

class Main {

    public static void main(String[] args) {

          // Pass Integer to Generic Class

          GenericClass<Integer> integerObject = new GenericClass<Integer>();

          integerObject.add(5);

          System.out.println("The Added Integer is : " + integerObject.get());

          // Pass String to Generic Class

          GenericClass<String> stringObject = new GenericClass<String>();

          stringObject.add("RahulShetty Academy");

          System.out.println("The Added String is : " + stringObject.get());

    }

}

Output:

The Added Integer is : 5

The Added String is : RahulShetty Academy

10. How Sub Class is different from Inner Class?

  • Sub class is a class that extends or inherit another class (Inheritance Concept). Inner Class is a class that is nested within another class
  • Sub class can be accessed directly. Inner class can only be accessed using reference of outer class. Sub class is accessed directly

Example Code Snippet : Inner Class Demo

//Inner class Demo

class Main {

    class InnerClass{

          void print() {

                System.out.println("Inside Inner Class");

          }

    }

    public static void main(String[] args) {

          //Create Object for Outer Class

          Main main = new Main();

          //Create Object for Inner Class

          Main.InnerClass inner = main.new InnerClass();

          inner.print();

    }

}

Output:

Inside Inner Class

Example Code Snippet : Sub Class Demo

//Sub Class Demo

class SuperClass{

    void print() {

          System.out.println("Super Class");

    }

}

class SubClass extends SuperClass {

    void print() {

          System.out.println("Sub Class");

    }

}

public class Main{

          public static void main(String[] args) {

                SubClass sub = new SubClass();

                sub.print();

    }

}

Output:

Sub Class

11. What is a singleton class? Explain with a small code snippet

A singleton class is a class that can have only one object (an instance of the class) at any point in time.

After the first time Creation of an object, if we try to create the object for the Singleton class, the new object also points to the first instance created.

Example Code Snippet

class SingletonDemo {

    private static SingletonDemo single_instance = null;

    public int i;

    // Private constrcutor;

    private SingletonDemo() {

          i = 10;

    }

    // Static method to create instance of Singleton class

    public static SingletonDemo getInstance() {

          if (single_instance == null)

                single_instance = new SingletonDemo();

          return single_instance;

    }

}

class Main {

    public static void main(String args[]) {

          SingletonDemo one = SingletonDemo.getInstance();

          one.i = 50;

          SingletonDemo two = SingletonDemo.getInstance();

          two.i = 100;

          System.out.println("Print Value of i using object one :" + one.i);

          System.out.println("Print Value of i using object two :" + two.i);

          if (one == two) {

                System.out.println("one and two both objects are same");

          }

    }

}

Output:

Print Value of i using object one :100

Print Value of i using object two :100

one and two both objects are same

12. Explain Thread life cycle briefly? What are some commonly used methods?

Threads are light-weight processes within a process

Life Cycle of Thread

The thread can be in one of the states at a given point in time

NEW: A thread that has not yet started is in this state.

RUNNABLE: A thread executing in the Java virtual machine is in this state.

BLOCKED: A thread that is blocked waiting for a monitor lock is in this state.

WAITING: A thread that is waiting indefinitely for another thread to perform a particular action is in this state.

TIMED_WAITING: A thread that is waiting for another thread to perform an action for up to a specified waiting time is in this state.

TERMINATED: A thread that has exited is in this state.

Commonly Used Methods in Java Thread.

start(): Starts the thread.

getState(): It returns the state of the thread.

getName(): It returns the name of the thread.

getPriority(): It returns the priority of the thread.

sleep(): Stops the thread for the specified time.

Join(): Stops the current thread until the called thread gets terminated.

isAlive() : Checks if the thread is alive.

Example Code Snippet: Simplest possible Thread example in Java

class Main extends Thread{

 public void run() {

     System.out.println("Thread is running");

 }

    public static void main(String args[]) {

          new Main().start();

    }

}

Output:

Thread is running

13. What is garbage collection? How to force Garbage Collection?

Garbage collection is the process by which Java programs perform automatic memory management. The garbage collector finds these unused objects and deletes them to free up memory.

How to force Garbage Collection?

Using System.gc()

If you call System.gc() anywhere in their code to instruct the JVM to prioritize garbage collection


Using Runtime.getRuntime().gc()

Internally it calls System.gc(), however, this method can also be used for forcing the garbage collection in java

Note: When an object is set to null, Java automatically prioritizes that to eligible for  Garbage Collection

Example Code Snippet : System.gc() and Runtime.getRuntime().gc()

class Main {

    public void finalize() {

          System.out.println("Object is Garbage Collected  " + this);

    }

    public static void main(String args[]) {

          Main m1 = new Main();

          Main m2 = new Main();

         

          m1 = null;

          System.gc();

         

          m2=null;

          Runtime.getRuntime().gc();

    }

}

Output:

Object is Garbage Collected  Main@17f18626

Object is Garbage Collected  Main@19366aa8

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!!

Please click on the link Sr.QA and SDET Interview Questions in Java – Part 4 to continue to part-4 series of this article.


Tags


You may also like

Groups attribute in TestNG 

Groups attribute in TestNG 
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"}