JAVA INTERVIEW QUESTIONS
2. SET - Interface (Set of unique things)
) A Set is a Collection that cannot contain duplicate elements. Classes implementing Set are HashSet, TreeSet, and LinkedHashSet
How many types of memories located in JVM
-Heap: Objects -Stack: Variables
1. LIST - Interface
A List is an ordered Collection (sometimes called a sequence). Lists may contain duplicate elements. Elements can be inserted or accessed by their position in the list, using a zero-based index. They are dynamic sized - resizable.
MAP Interface
A Map is an object that maps keys to values. A map cannot contain duplicate keys. Both key and value do not support primitives. There are three main implementations of Map interfaces: HashMap, TreeMap, and LinkedHashMap.
QUEUE - Interface
A Queue is designed in such a way so that the elements added to it are placed atthe end of Queue and removed from the beginning of Queue. The concept here is similar to the queue we see in our daily life, for example, when a new iPhone launches we stand in a queue outside the apple store, whoever is added to the queue has to stand at the end of it and persons are served on the basis of FIFO (FirstIn First Out), The one who gets the iPhone is removed from the beginning of the queue.
HAS-A Relationship
Composition(HAS-A) simply means the use of instance variables that are references to other objects. For example, Honda Civic has an Engine, or a House has a Bathroom.
Unboxing
Copying a value from inside a wrapper class object and storing it into a primitive data type variable -For example - conversion of Integer to int, Long to long, Double to double etc.
IS-A Relationship
In object-oriented programming, the concept of IS-A is totally based on Inheritance, which can be of two types: Class Inheritance or Interface Inheritance. It is just like saying "A is a B type of thing". For example, Apple is a Fruit, Car is a Vehicle etc. Inheritance is unidirectional. For example, House is a Building. But Building is not a House. Wherever you see an "extends" keyword or "implements" keyword in a class declaration, then this class is said to have IS-A relationship. It is a parent-child relationship.
What's Java Collection Framework (Data Structure)
Java provides Collection Framework which defines several classes and interfaces to represent a group of objects as a single unit. The Collection interface (java.util.Collection) and Map interface (java.util.Map) are the two main "root" interfaces of Java collection classes -java.util.Collection: This includes interfaces like List, Set, and Queue
Iterable(I)
extended by root interface collection we can apply Iterator(I) to the classes or interfaces that are sub type of Iterable
TreeSet - class
implementing SortedSet Interface ○ TreeSet is similar to HashSet except that it sorts the elements in the ascending order while HashSet doesn't maintain any order. ○ It is substantially slower than HashSet.
Autoboxing
the automatic conversion between a primitive value and a corresponding wrapper object -For example - conversion of int to Integer, long to Long, double to Double etc.
MAP Methods
○ .put(key, value): inserts key and value objects to the map ○ .get(key): retrieves the value of the given key. ○ .remove(key): removes the given key object and its value. ○ .size(): returns the size of the map. ○ .containsKey(key): verifies if the given Key exists in the map and returns boolean. ○ .containsValue(value): verifies if the given value exists in the map and returns boolean. ○ .keySet(): returns all the keys as Set Interface. ○ .clear(): removes everything in the map, size will become 0 after the execution.
What is Abstraction and how it it approached in your project
○ 1 of 4 OOP concepts ○ It is about hiding the implementation but showing the functionality only. ○ Abstraction helps you to focus on what the object does instead of how it does it. ○ Two ways to achieve abstraction in Java: Abstract classes (partial abstraction) and interface (full/pure abstraction). ○ In my project, BasePage class is abstract since it shouldn't be instantiated and we don't have a related page in our application.
What is Encapsulation and how it it approached in your project
○ 1 of 4 OOP concepts ○ It is hiding data by making the variables private and giving them public access with getters and setters. ○ In my project: I created multiple POJO/BEAN classes(Json to java (Gson, Jakson )) in order to manage test data and actual data. EX: I take JSON from API response and convert to object of my POJO class all variables are private with getters and setter. Also in order to store credentials or sensitive data in my framework I have used encapsulation, configuration reader also known as property file or excel sheet to hide data from the outside world to get access. I use Apache POI in the data store in Excel in order to extract/read and modify data..
What is Polymorphism and how it it approached in your project
○ 1 of 4 OOP concepts ○ It is performing one single action/method in different ways or forms. ○ In my project, WebDriver driver = new ChromeDriver(). I also use method overloading and method overriding which are considered as polymorphism. List<String> = new ArrayList();
What is Inheritance and how it it approached in your project
○ 1 of 4 OOP concepts ○ It is used to create a relationship between parent and child classes. ○ In my project, we have an abstract BasePage class. It is used as the parent/super class for all of the page classes since it's extended by all page classes. For example, it initializes PageFactory and contains common global web elements/methods. I have waitUntilLoaderScreenDisappear(), navigateToModule(String tab, String module), etc.
Checked exceptions
○ All exceptions other than Runtime Exceptions are known as Checked exceptions as the compiler checks them during compilation to see whether the programmer has handled them or not. ○ If these exceptions are not handled/declared in the program, you will get compilation error. For example, SQLException, IOException, ClassNotFoundException etc
HashSet - class
○ It doesn't maintain any order, the elements would be returned in any random order. ○ It doesn't allow duplicates. If you try to add a duplicate element in HashSet, the old value would be overwritten. (no duplicate value) ○ It allows null values however if you insert more than one null, it would still return only one null value.
HashMap: - class
○ It is NOT an ordered collection which means it does not return the keys and values in the same order in which they have been inserted into the HashMap. ○ It does NOT sort the stored keys and Values. ○ Accepts only one null key but any number of null values.
ArrayList - class
○ It is a class implements List interface and it is based on an Array data structure. It is widely used because of the functionality and flexibility it offers. ○ It is resizable unlike the Arrays. ArrayList can dynamically grow and shrink after addition and removal of elements ○ It has a fast iteration and is ordered by index. Preferably to use when searching for an element/object. ○ It is not sorted but can be sorted using Collections.sort() method.
TreeMap: - class implements SortedMap Interface
○ It is sorted in the ascending order of its keys.
HashTable: - class
○ It is synchronized. It ensures that no more than one thread can access the Hashtable at a given moment of time. ○ It doesn't allow null keys and null values. NO nulls at all.
LinkedHashSet - class
○ It maintains the insertion order. Elements get sorted in the same sequence in which they have been added to the Set. ○ It is basically an ordered version of HashSet so you can use it when you care about the insertion order
TreeSet - class
○ It maintains the insertion order. Elements get sorted in the same sequence in which they have been added to the Set. ○ It is basically an ordered version of HashSet so you can use it when you care about the insertion order
Iterator(I)
○ Iterator is used for iterating (looping) various collection classes such as HashMap, ArrayList, LinkedList etc. ○ Allows us to get access to each objects of the collection type ○ Allows us to remove objects from a collection type. The ONLY legit way to remove data elements from a collection-type. ○ .iterator() method: iterates the collection, and returns Iterator. ○ .hasNext() method: checks if there are enough elements that can be iterated and returns boolean expression. ○ .next() method: if hasNext() is true, it retrieves the current iteration from the collection type ○ .remove() method: removes current element of the iteration from the collection type
LinkedList - class
○ LinkedList is a linear data structure. ○ LinkedList elements are not stored in contiguous locations like arrays, they are linked with each other using pointers. Each element of the LinkedList has the reference(address/pointer) to the next element of the LinkedList. ○ It has slower iteration but faster addition and deletion. Preferably to use when adding and deleting an object/element.
Unchecked Exceptions
○ Runtime Exceptions are also known as Unchecked Exceptions. These exceptions are not checked at compile-time so the compiler does not check whether the programmer has handled them or not. ○ It's the responsibility of the programmer to handle these exceptions and provide a safe exit. For example, ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc.
Vector - class
○ Vector implements List Interface. ○ Like ArrayList it also maintains insertion order but it is rarely used in a non-thread environment as it is synchronized (thread-safe) and due to which it gives poor performance in searching, adding, deleting and updating of its elements. ○ Vector has a child class: Stack ■ Stack: synchronized (thread-safe) ■ pop(): LIFO ==> Last in First Out - removes the last object from the stack
LinkedHashMap: - class
○ maintains the insertion order as it is doubly linked. It has a faster iteration. ○ put() & remove() are faster than hashmap // modifying the data. ○ get() is slower than hashmap // retrieving the data.
What's System.gc()?
● A request to JVM to run Garbage collector to free up memory but it is not a command so it may not be executed. ● It is up to the garbage collector to honor this request.
Array vs ArrayList - Data Structure
● Array: ○ Fixed size, cannot be resized. ○ Can store primitive types and objects. ○ Can be multidimensional. ○ It is faster but in my project it does not matter that much. ○ We find the length of an Array with .length attribute. ● ArrayList: ○ Dynamic and can be resized. ○ Can store only wrappers and objects, ○ Cannot be multidimensional. ○ It is slower compared to Arrays. ○ We find the length of an ArrayList with .size() method.
Abstract Class and/vs Interface
● Both help us to achieve abstraction in Java and both cannot be instantiated. ● Abstract Class is a class and can be partially abstract since it can include concrete methods. ● Interface is pure abstraction since there is no concrete method in it and it is just like a blueprint for the class implementing it. Interface can have abstract methods, default methods, static methods, and public final static variables. ● We can extend only one Abstract class but when we want to use an interface, we may implement as many interfaces as we want.
What is a constructor in Java? Difference between constructor and method?
● Constructor: ○ It is a special method which instantiates/creates an object. ○ It needs to match with the class name. ○ There is always a constructor in a class event if you don't define one. You will have the default constructor in this case. ○ Abstract classes will not have constructor since you can't instantiate abstract classes. ○ We can have private constructor to prevent object creation. ○ We have a default and parameterized constructor. In my project: ● Driver Class: In my project I have a Driver class where I define the constructor private since I don't want anyone to create any object out of it.
What are Data Structures and Why do we need them?
● Data structures are a way of organizing data for efficient manipulation: insertion, searching, reading, and deletion of data. ● When there is more than one variable, it is data structure: Array, ArrayList, Maps, Set, HashMaps, LinkedLists, etc. ● Array: It is the simplest data structure. It is not resizable so it is static. ● In my project, I always use Java data structures for reading data and storing data from our application, database, or API.
Difference between equals method and "==" operator in Java?
● Double equals "==" checks if two reference variables are pointing to the same object. It is basically reference and address comparison. ● ".equals" checks if the content is the same. Even if two references are pointing to two different objects in the memory, .equals method will look if they have the same content. It is a content comparison.
Difference between error and exception
● Errors indicate that something severe enough has gone wrong, the application should crash rather than try to handle the error. ● Exceptions are events that occur in the code. A programmer can handle such conditions and take necessary corrective actions
Final vs finally vs finalize()
● Final: it is a keyword and used to apply restrictions on class, method, and variable. ○ Final Class = CAN't be inherited ○ Final Method = CAN't be overridden ○ Final Variable = CAN't be changed ● Finally: it is used for exception handling with try and catch block. ○ It is executed every time even if an exception happens or not. ○ Most of the time this block is used to close the resources like database connection, I/O resources, etc. ● Finalize(): this is a method coming from Object class inherited to every class. ○ Used by the garbage collector to perform some final operations or clean up operations on an object before it is removed from the memory.
Garbage
● Garbage collector automatically checks the heap memory and deletes the unused objects. ● You cannot force the garbage collector to delete the files. ● Types of Garbage Collector: Serial, Parallel, CSM (Concurrent Mark Sweep), G1 (Garbage First)
Difference between Hashtable and HashMap in Java?
● Hashtable is synchronized, whereas HashMap is not. This makes HashMap better for non-threaded applications, as unsynchronized Objects typically perform better than synchronized ones. ● Hashtable does not allow null keys or values. HashMap allows one null key and any number of null values. ● For example; one of HashMap's subclasses is LinkedHashMap, so in the event that you'd want predictable iteration order (which is insertion order by default), you could easily swap out the HashMap for a LinkedHashMap. This wouldn't be as easy if you were using Hashtable. Ifsynchronization is not an issue for me, I prefer using HashMap. If it becomes an issue, then I prefer Collections.synchronizedMap() or ConcurrentHashMap. ● Both Hashtable and HashMap implement Map interface and both are Key and Value. ● HashMap is not thread-safe while Hashtable is a thread-safe collection. ● Second important difference is performance since HashMap is not synchronized so HashMap performs better than Hashtable
Where did you use static in your framework?
● I create utilities classes in my project for better code reusability and reduce redundant codes. In the utilities classes, I use static methods so that I can reach/call by the class name and use anywhere in my project. ○ In my project: public static WebDriver getDriver (String browser) method public static void closeDriver () method Browser Utils: waitPlease(); verifyIsDisplayed() are static ConfigurationReader: public static getProperty(String key) ● I also have a DatabaseUtil class where I create static methods to connect and run queries and get data. Check this in the project.
Whatis the Iterator and difference between for-each loop?
● Iterator works with ArrayList, not with Array. It helps us to iterate through the elements. ● With an iterator you can make changes (remove item) to the list while iterating. ● With for-each loops, we can only iterate through lists but cannot make any changes to our lists.
Explain JVM, JRE, and JDK?
● JDK: Java Development Kit. It helps you write a java program and save it as source code (.java). When you compile the code, it is turned into a set of Byte Code and stored in a ".class; file. ● JRE: Java Runtime Environment: It has the minimum requirements to execute a Java application. It contains JVM and some libraries. ● JVM: Java Virtual Machine: It runs byte code (.class). JVM is included in both JDK and JRE. Whenever you run a Java program, JVM executes the program line by line so that is why it is called interpreter.
Difference between Java 7 and Java 8
● Java 8 New Features: ○ Lambda Expressions ○ Date and Time API ○ Pipeline and Streams
Can super() and this() keywords be in the same constructor?
● No, both of them need to be in the first line in the constructor. We need to pick one or the other. ● super() will call the super/parent class' constructor.. ● super. will let us access the parent/super class' variables, members, methods, etc. ● this() will call a constructor from another constructor within the same class. ● this. will access instance variables and methods.
Difference between overloading and overriding?
● Overriding: ○ Happens in the child class. It is called dynamic binding. ○ Same method name and same parameters (same method signature). ○ Must have the same or sub return type. ○ We cannot override static methods, we can only hide them. ○ Access modifiers can only be the same or more visible. ○ Private methods cannot be overridden since they are not inherited. ○ Final methods cannot be overridden since they are final, cannot be changed. ○ In my project: I override .toString(), .equals(), and .hashCode() methods. ● Overload: ○ Happens in the child class. It is called dynamic binding. ○ Same method name and same parameters (same method signature). ○ Must have the same or sub return type. ○ We cannot override static methods, we can only hide them. ○ Access modifiers can only be the same or more visible. ○ Private methods cannot be overridden since they are not inherited. ○ Final methods cannot be overridden since they are final, cannot be changed. ○ In my project: I override .toString(), .equals(), and .hashCode() methods.
What are primitives and wrapper classes? Implicit and explicit casting?
● Primitive: It is simply just a container to keep/store data. Boolean, byte, char, int, float, double, long, short. ● Wrapper Class: Every primitive has a wrapper class. A Wrapper class is a class whose object wraps or contains primitive data types. When we create an object to a wrapper class, it contains a field and in this field, we can store primitive data types. In other words, we can wrap a primitive value into a wrapper class object. ● Java Type Casting is classified into two types. ○ Widening Casting (Implicit) - Automatic Type Conversion ○ Narrowing Casting (Explicit) - Need Explicit Conversion
What are the access modifiers?
● Public: accessible from everywhere ● Protected: accessible within the same package or sub classes in different packages. It is a package private as long as it is not inherited. ● No modifier/default: accessible only within the same package. It's also called package private. ● Private: accessible only within the class. In my project: ● I use private access modifiers to achieve encapsulation to limit the outside access. I make the constructor private to avoid class instantiation as in the Driver class. All fields in POJO classes are private.
Difference between Set, List and Map in Java?
● Set, List and Map are 3 important interfaces of Java collection framework. ○ List provides ordered and indexed collection which may contain duplication. ○ Set provides an unordered collection of unique objects. There is NO duplication. Both List and Set implement the collection interface. ○ Map provides a data structure based on Key - Value. Key is always unique, Value can contain duplicate values.
What is Singleton class and how can we make a class Singleton?
● Singleton is a design pattern in OOP. ● How to make a class Singleton: ○ Create static instance ○ Make constructor private ○ Create a public static getInstance() method, which will return an instance. public class Singleton{private static WebDriver driver = new ChromeDriver(); // private static instance private Singleton(){ } // private constructorpublic static WebDriver getDriver(){ // public static getInstance() method returndriver; }} ● The purpose is to make sure that there is only one instance of the class and provide a global/public access point to it. In my project: I have a Driver class in our utilities package which is created in Singleton design pattern.
Difference between Static and Instance Variables/Block
● Static Variable: ○ It belongs to the class which means there is only one copy. ○ Static can be variables, method, block, inner class. ○ Static methods cannot call/refer non-static members. ● Static block will be executed first. Whenever you call the class, the static block will be called/executed before everything. It will be executed only once when the class is loaded. ● Instance Variable: It is the property of the object which means every object will have its own copy unlike static being only one class copy. ● Instance block: It will be called every time the object is created, even before the constructor. In my project: ● Singleton Driver: I have one Driver declared static because I don't want anyone to make a copy of it but use the same variable.
Whatis thread safe or synchronized?
● The Java synchronized keyword is an essential tool in concurrent (simultaneous) programming in Java. ● Its overall purpose is to only allow one thread at a time into a particular section of code thus allowing us to protect, for example, variables or data from being corrupted by simultaneous modifications from different threads. ● JAVA keyword synchronized is used to create synchronized code and internally it uses locks on Object or Class to make sure only one thread is executing the synchronized code. ● JVM guarantees that synchronized code will be executed by only one thread at a time. ● In my project, I created the "getDriver()" method in Driver class as thread safe because I don't want the Driver to be called simultaneously
What's a Static Keyword?
● The static keyword can be used with class level variables to make it global i.e all the objects will share the same variable. ● The static keyword can be used with methods also. A static method can access only static variables of class and invoke only static methods of the class.
TreeSet vs TreeMap
● TreeSet: can contain only unique values - is sorted in ascending order ● TreeMap: can contain only unique keys. - keys are sorted in ascending order
Exception Handling
● Try & Catch Block: to handle the exception try { System.out.println(new int[] {1,2,3}[100]); // out of bound exception occurs here } catch (Exception e){ System.out.println("Out of Bound Exception caught here"); } finally { System.out.println("Finally will be executed here regardless of any exception occurs or not"); } ● Throws keyword: to pass it to the caller's responsibility to handle it. "throws" keyword indicates that this method throws an exception. public static void method1 ()throws Exception{ Thread.sleep(2000); }
How can you prevent instantiation of a class?
● You can create the class with a private constructor or you can make the class abstract. ● The best way is with the private constructor since you can create a subclass of an abstract and instantiate it.
Difference between throw and throws in Java
● throw keyword is used to throw an exception explicitly ● throws keyword is used to declare an exception which means it works similar to the try--catch block ● throw new RuntimeException ("Invalid browser name!") - throws ArithmeticException; We throw RuntimeException in the Driver class. You need to pass the driver's name (chrome, firefox,etc.) if the text does not meet the available browser we want to throw an exception. public void deposit (double amount ) throws RemoteException { // Method implementation throw new RemoteException(); }