Sunday, 28 May 2023

Java Generics: How to use in Test Automation ?

 



Java Interview Questions SET-01

Java Interview Questions Set-02 ARRAY

Java Interview Questions Set-03 MAP

Java Interview Question Set-04


What are Java Generics?


Java generics provide a way to create classes, interfaces, and methods that can work with different types of objects. Generics allow you to specify placeholder types, called type parameters, which are replaced with actual types when the code is used.
  • Java generics are like special boxes that can hold different types of things.

  • Just like you have different boxes for toys, books, and clothes, Java generics allow us to create boxes that can hold different types of data.

    1. Java generics provide type safety and enable code reusability by allowing classes, interfaces, and methods to work with different types of objects.
    2. Generics eliminate the need for type casting and ensure compile-time type checking.
    3. They are widely used in collections to enforce type constraints and provide compile-time type safety.
    4. Bounded type parameters in generics allow for restricting acceptable types, enhancing flexibility in type handling.
    5. Java generics enhance code readability and maintainability by promoting cleaner and more concise code.

Why do we use Java Generics?

  • Imagine you have a magic box that can hold any kind of toy: cars, dolls, or action figures.
  • Java generics work similarly. They allow us to create code that can work with different types of data without duplicating the code.

How to use Java Generics?

  • Let's say we want to create a box that can hold any kind of toy. We use the angle brackets "<>" to create a generic class or method. 

Example: Creating a generic class

\

public class ToyBox<T> {
    private T toy;

    public T getToy() {
        return toy;
    }

    public void setToy(T toy) {
        this.toy = toy;
    }
}


  • Here, "T" is a placeholder for any type of toy. It could be a Car, Doll, or any other toy.

Example: Using the generic class

ToyBox<Car> carBox = new ToyBox<>();
carBox.setToy(new Car());
Car car = carBox.getToy();

ToyBox<Doll> dollBox = new ToyBox<>();
dollBox.setToy(new Doll());
Doll doll = dollBox.getToy();

  • We can create different toy boxes, such as a car box or a doll box, and put specific types of toys in them.


  • Benefits of Java Generics:

    • Code reusability:
      We can write generic code that can work with different types of data without duplicating the code.

    • Type safety:
      Generics provide compile-time checks to ensure that we are using the correct types, reducing errors and bugs.



    Array vs List vs MAP  <- refer the link here


    Key points:

    • Java generics are like special boxes that can hold different types of things.
    • Generics help us write code that can work with different types of data without duplicating code.
    • We use angle brackets "<>" to create generic classes or methods.
    • Generics provide code reusability and type safety.




    Java Generics in Test Automation


    Here's an example of how you can use generics to create a generic assertion method for comparing two lists of any type:

    import java.util.List;

    public class AssertionUtils {
        public static <T> void assertListsEqual(List<T> expected, List<T> actual) {
            if (expected.size() != actual.size()) {
                throw new AssertionError("Lists are not of the same size");
            }

            for (int i = 0; i < expected.size(); i++) {
                if (!expected.get(i).equals(actual.get(i))) {
                    throw new AssertionError("Lists differ at index " + i +
                            "\nExpected: " + expected.get(i) +
                            "\nActual: " + actual.get(i));
                }
            }
        }
    }


    In this example, we have a class called AssertionUtils that contains a generic method called assertListsEqual(). This method takes two parameters: expected and actual, which are both lists of type T.

    The <T> before the return type void represents the generic type parameter. It allows the method to work with any type of list.

    Inside the method, we first check if the sizes of the expected and actual lists are equal. If they are not, we throw an AssertionError indicating that the lists are not of the same size.

    Then, we iterate over the elements of both lists and compare them using the equals() method. If any pair of elements differs, we throw an AssertionError indicating the index at which the lists differ, along with the expected and actual values.


    How to use Java ENUM in Test Automation Framework


    Here's an example usage of the assertListsEqual() method:


    import java.util.Arrays;
    import java.util.List;
    public class TestAssertions {
        public static void main(String[] args) {
            List<String> expected = Arrays.asList("apple", "banana", "orange");
            List<String> actual = Arrays.asList("apple", "grape", "orange");
            AssertionUtils.assertListsEqual(expected, actual);
        }
    }


    In this example, we have two lists: expected and actual. We call the assertListsEqual() method from AssertionUtils and pass the lists as arguments. If the lists are not equal, an AssertionError will be thrown with the appropriate message indicating the index and the expected/actual values.

    By using generics in this way, you can create a single generic assertion method that can compare two lists of any type, making your test assertions more reusable and flexible.





    *******************************************************************
    For any doubts or career guidance from me, reach out here: https://topmate.io/sidharth_shukla

    ********************************************************************

    Do remember that knowing Linux is one of the most important aspect to work as an SDET.

    Basic Linux Commands for Automation QA


    ****************************************

    TOP 15 BDD - CUCUMBER Interview Q&A


    ************************************************

    ✍️AUTHORLinkedIn Profile

    ************************************************

    Learn (API-Microservice)Testing+ Selenium UI Automation-SDET with Self Paced Videos prepared by FAANG employees and LIVE Doubt Session 

    SDET TRANING VIDEOS AVAILABLE with Live Doubt Session(course-1 below,API TRaining Videos With Class Notes and Coding Set) and (API++Mobile+UI, course-1 & 2 below) Check Training Page for Course Content or reach out @whatsapp +91-9619094122. 
    This includes classnotes, 300+ interview questions, 3 projects, Java Coding question set for product companies along with career guidance from FAANG employees for Automation and SDET.

    For more details whatsapp : https://lnkd.in/dnBWDM33

    *************************************************



    SeleniumWebdriver Automation Testing Interview Questions:

    https://automationreinvented.blogspot.com/search/label/SeleniumWebdriver

    API Testing Interview Question Set:

    https://automationreinvented.blogspot.com/2022/03/top-80-api-testing-interview-questions.html

    DevOps Interview Q&A:

    https://automationreinvented.blogspot.com/2021/11/top-11-devops-interview-questions-and.html 

    Kubernetes Interview Question Set

    https://automationreinvented.blogspot.com/search/label/Kubernetes

    Docker Interview Question Set

    https://automationreinvented.blogspot.com/Docker

    Linux Interview question Set

    https://automationreinvented.blogspot.com/search/label/Linux

    Automation Testing/SDET Framework Design

    https://automationreinvented.blogspot.com/search/label/FrameworkDesign

    Java Related Interview Question Set

    https://automationreinvented.blogspot.com/search/label/Java

    GIT Interview Question Set:

    https://automationreinvented.blogspot.com/2021/09/top-40-git-interview-questions-and.html

    Coding Interview Question Set:

    https://automationreinvented.blogspot.com/search/label/Coding%20Questions

    Mobile Testing Interview Question Set:

    https://automationreinvented.blogspot.com/search/label/Mobile%20Testing

    Python Interview Question Set for QAE - SDET - SDE:

    https://automationreinvented.blogspot.com/search/label/Python

    Friday, 12 May 2023

    Interview questions on Array , List and Map

     


    Java Interview Questions SET-01

    Java Interview Questions Set-02 ARRAY

    Java Interview Questions Set-03 MAP

    Java Interview Question Set-04


    Explain Array, List and Map with Examples?

    1. Array: Imagine you have a collection of toys that you want to keep in a row. An array is like a long shelf with compartments. Each compartment can hold one toy. You can count the toys by looking at how many compartments are filled. You can also take out a specific toy by knowing its position on the shelf.

    2. List: Now, think of a list as a collection of toys that you can put in any order. It's like having a bag where you can put in or take out toys whenever you want. With a list, you don't have to worry about a specific order. You can add more toys to the list or remove them as you like.

    3. Map: Imagine you have a box full of different colored balls, and each ball has a name written on it. A map is like a magical box that helps you find a ball by its name. You can ask the box to give you a ball with a specific name, and it will find it for you. In a map, you can store pairs of names and balls, and easily find the ball you need by looking up its name.

    Remember, an array is like a shelf, a list is like a bag, and a map is like a magical box to help you find things. Each one is useful in different situations, depending on how you want to organize or find your toys or objects in Java programming.

    • What are the most important necessary libraries? [Knowledge]


    import java.util.ArrayList; 

    import java.util.HashMap; 

    import java.util.List; 

    import java.util.Map;



    • How to Declaring and initializing an array[Knowledge]


    String[] myArray = {"element1", "element2", "element3"};






    • How to Declaring and initializing a list:


    List<String> myList = new ArrayList<>();
    myList.add("element1");
    myList.add("element2");
    myList.add("element3");



    • How to add/join/combine two ArrayList ?


    : Refer to the link HERE for answers with the code.


    • How to Declaring and initializing a map:


    Map<String, Integer> myMap = new HashMap<>();
    myMap.put("key1", 1);
    myMap.put("key2", 2);
    myMap.put("key3", 3);



    • How to Sort a Hashmap in Java?

    Ans: Refer to the link HERE for answer with code.


    • How to Access elements in an array:


    String firstElement = myArray[0]; 

    String secondElement = myArray[1];


    • How to Access elements from the list:


    String firstElement = myList.get(0); 

    String secondElement = myList.get(1);



    • How do I find duplicate elements and count the same using Map in Java?

    Refer to the link HERE for answers with code

    • How to Access elements in a map?


    int valueForKey1 = myMap.get("key1");

     int valueForKey2 = myMap.get("key2");




    • How do you iterate over an array?


    for (String element : myArray)

    {

    System.out.println(element);

    }


    • How do you iterate over the list?

    for (String element : myList)

    {

    System.out.println(element);

    }




    Learn about Strings with Multiple Choice Q&A   <- Must Know


    • How do you iterate over a map?


    for (Map.Entry<String, Integer> entry : myMap.entrySet()) 

    String key = entry.getKey(); 

    int value = entry.getValue(); 

    System.out.println("Key: " + key + ", Value: " + value); 

    }

    What are the main performance differences between Array and List?

    In Java, there are performance differences between arrays and lists due to their underlying implementations.

    1. Memory Allocation: Arrays have a fixed size that is determined at the time of creation. This allows for efficient memory allocation as the required memory for all elements is allocated in a contiguous block. On the other hand, lists such as ArrayList dynamically resize themselves as elements are added or removed. This resizing process may involve creating a new array and copying elements, resulting in potential memory overhead.

    2. Random Access: Arrays provide fast random access to elements by index. Since arrays have a fixed size and a known memory layout, accessing an element at a specific index is a constant-time operation (O(1)). In contrast, lists implemented as linked structures, such as LinkedList, require traversing the list from the beginning to reach a specific index, resulting in a linear-time operation (O(n)).

    3. Insertion and Deletion: Arrays are efficient for adding or removing elements at the ends, as it involves shifting or resizing the underlying array. Adding or removing elements at the beginning or in the middle of an array requires shifting the subsequent elements, resulting in a time complexity of O(n). Lists, especially LinkedList, are more efficient for frequent insertion and deletion operations as they only require updating references between nodes.

    4. Iteration: Iterating over an array using a simple for loop is generally faster compared to iterating over a list using an iterator or enhanced for loop. This is because arrays provide direct memory access to elements, while lists may involve traversing internal structures.

    Overall, arrays tend to have better performance for random access and predictable-sized collections, while lists offer more flexibility for dynamic resizing, insertion, and deletion. The choice between them depends on the specific use case and the operations required in your application.



    *******************************************************************
    For any doubts or career guidance from me, reach out here: https://topmate.io/sidharth_shukla

    ********************************************************************

    Do remember that knowing Linux is one of the most important aspect to work as an SDET.

    Basic Linux Commands for Automation QA


    ****************************************

    TOP 15 BDD - CUCUMBER Interview Q&A


    ************************************************

    ✍️AUTHORLinkedIn Profile

    ************************************************

    Learn (API-Microservice)Testing+ Selenium UI Automation-SDET with Self Paced Videos prepared by FAANG employees and LIVE Doubt Session 

    SDET TRANING VIDEOS AVAILABLE with Live Doubt Session(course-1 below,API TRaining Videos With Class Notes and Coding Set) and (API++Mobile+UI, course-1 & 2 below) Check Training Page for Course Content or reach out @whatsapp +91-9619094122. 
    This includes classnotes, 300+ interview questions, 3 projects, Java Coding question set for product companies along with career guidance from FAANG employees for Automation and SDET.

    For more details whatsapp : https://lnkd.in/dnBWDM33

    *************************************************



    SeleniumWebdriver Automation Testing Interview Questions:

    https://automationreinvented.blogspot.com/search/label/SeleniumWebdriver

    API Testing Interview Question Set:

    https://automationreinvented.blogspot.com/2022/03/top-80-api-testing-interview-questions.html

    DevOps Interview Q&A:

    https://automationreinvented.blogspot.com/2021/11/top-11-devops-interview-questions-and.html 

    Kubernetes Interview Question Set

    https://automationreinvented.blogspot.com/search/label/Kubernetes

    Docker Interview Question Set

    https://automationreinvented.blogspot.com/Docker

    Linux Interview question Set

    https://automationreinvented.blogspot.com/search/label/Linux

    Automation Testing/SDET Framework Design

    https://automationreinvented.blogspot.com/search/label/FrameworkDesign

    Java Related Interview Question Set

    https://automationreinvented.blogspot.com/search/label/Java

    GIT Interview Question Set:

    https://automationreinvented.blogspot.com/2021/09/top-40-git-interview-questions-and.html

    Coding Interview Question Set:

    https://automationreinvented.blogspot.com/search/label/Coding%20Questions

    Mobile Testing Interview Question Set:

    https://automationreinvented.blogspot.com/search/label/Mobile%20Testing

    Python Interview Question Set for QAE - SDET - SDE:

    https://automationreinvented.blogspot.com/search/label/Python

    All Time Popular Posts

    Most Featured Post

    Introduction to Web Testing with Playwright

      Introduction to Web Testing with Playwright 📌  Telegram Group:  https://t.me/+FTf_NPb--GQ2ODhl 📌  YouTube channel:  https://lnkd.in/gGUG...