Core Java
Why use abstract class?
An abstract class provides an appropriate superclass from which other classes can inherit and thus share a common design. (multiple classes can share a common behavior)
When to use an interface and when to use an abstract class?
An interface gives you the benefits of an abstract class and the benefits of an interface, so if it's possible to create your base class without any method definitions or member variables you should always prefer interfaces to abstract classes. In fact, if you know something is going to be a base class, your first choice should be to make it an interface, and only if you're forced to have method definitions or member variables should you change to an abstract class.
What is interface?
An interface is used to define the contract for the subclasses to implement
Why to use Encapsulation?
Assume you have an age property. The user can enter a value of -10, which although is a valid number, is an invalid age. A setter method could have logic which would allow you to catch such things. Hiding the complexities irrelevant to the users. Sometimes, some properties and methods are only for internal use and the user doesn't have to know about these. This makes is simple for the user to use the object. You can change, amend or even remove that method if that method is not encapsulated and it were public all your clients would have been affected.
What is Garbage Collection?
Garbage Collection is the process of looking at heap memory, identifying which objects are in use and which are not, and deleting the unused objects. In Java, process of deallocating memory is handled automatically by the garbage collector.
What is difference between HashMap and Hashtable?
HashMap allows null key and values whereas Hashtable doesn't allow null key and values. Hashtable is synchronized but HashMap is not synchronized. So HashMap is better for single threaded environment, Hashtable is suitable for multi-threaded environment. LinkedHashMap was introduced in Java 1.4 as a subclass of HashMap, so incase you want iteration order, you can easily switch from HashMap to LinkedHashMap but that is not the case with Hashtable whose iteration order is unpredictable. HashMap provides Set of keys to iterate and hence it's fail-fast but Hashtable provides Enumeration of keys that doesn't support this feature. Hashtable is considered to be legacy class and if you are looking for modifications of Map while iterating, you should use ConcurrentHashMap.
What will happen if two different keys of HashMap return same hashcode()?
If two keys of HashMap return same hash code then they will end up in the same bucket, hence collision will occur. They will be stored in a linked list together.
What will happen if you try to store a key which is already present in HashMap?
If you store an existing key in the HashMap then it will override the old value with the new value and put() will return the old value. There will not be any exception or error.
What is encapsulation?
In Java, this means making all object attributes private. Instead, object attributes are accessed through methods.
How do you remove a mapping while iterating over HashMap
Iterator itr = map.entrySet().iterator(); while(itr.hasNext()){ Map.Entry current = itr.next(); if(current.getKey().equals("matching"){ itr.remove(); // this will remove the current entry. } }
What is ternary operator in java?
Java ternary operator is the only conditional operator that takes three operands. It's a one liner replacement for if-then-else statement and used a lot in java programming.
What is LinkedHashMap?
LinkedHashMap is a subclass of HashMap. It maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is normally the order in which keys were inserted into the map
What is default constructor?
No argument constructor of a class is known as default constructor. When we don't define any constructor for the class, java compiler automatically creates the default no-args constructor for the class. If there are other constructors defined, then compiler won't create default constructor for us.
Can you store a duplicate key in HashMap?
No, you cannot insert duplicate keys in HashMap, it doesn't allow duplicate keys. If you try to insert an existing key with new or same value then it will override the old value but size of HashMap will not change i.e. it will remain same. This is one of the reason when you get all keys from the HashMap by calling keySet() it returns a Set, not a Collection because Set doesn't allow duplicates.
When to use Abstract and when to use Interface
One general rule of when to use abstract class and interface is to find out whether a certain class will form a IS-A hierarchy or CAN-DO-THIS hierarchy. If you know that you will be creating classes e.g. Circle, Square than it's better to create an abstract class Shape which can have area() and perimeter() as abstract method, rather than defining Shape as interface in Java. On the other hand if you are going to create classes which can do thinks like, can fly, you can use interface Flyable instead of abstract class. An interface generally defines capabilities. Flyable: Bird, Airplane, Balloon. It's better to use an interface Flyable because they are not related to each other.
Difference between String, StringBuffer and StringBuilder?
String is immutable and final in java, so whenever we do String manipulation, it creates a new String. String manipulations are resource consuming, so java provides two utility classes for String manipulations - StringBuffer and StringBuilder. StringBuffer and StringBuilder are mutable classes. StringBuffer operations are thread-safe and synchronized where StringBuilder operations are not thread-safe. So when multiple threads are working on same String, we should use StringBuffer but in single threaded environment we should use StringBuilder. StringBuilder performance is fast than StringBuffer because of no overhead of synchronization.
How does HashMap handle collisions in Java?
The java.util.HashMap uses chaining to handle collisions, which means new entries, an object which contains both key and values, are stored in a linked list along with existing value and then that linked list is stored in the bucket location
How does resizing happens in HashMap?
The resizing happens when map becomes full or when the size of map crosses the load factor. For example, if the load factor is 0.75 and when become more than 75% full then resizing trigger which involves array copy. First, the size of the bucket is doubled and then old entries are copied into a new bucket.
What is break and continue statement?
We can use break statement to terminate a loop. We can use break statement in switch statement to exit the switch case. The continue statement skips the current iteration a loop
What is Java ClassLoader?
We know that Java Program runs on Java Virtual Machine (JVM). When we compile a Java Class, it transforms it in the form of bytecode that is platform and machine independent compiled program and store it as a .class file. After that when we try to use a Class, Java ClassLoader loads that class into memory.
Why do we need wrapper classes?
We need wrapper classes when we need a type that will fit in the Object world programming like Collection classes. Wrapper classes can be used to achieve polymorphism. (ArrayList only accept Object type)
What is generics
A generic type is a class or interface that is parameterized over types. We use angle brackets (<>) to specify the type parameter. It provides compile-time type checking and removes risk of ClassCastException, so if you try to add any element of other type it throws compile time error.
What is load factor in HashMap?
A load factor is a number which controls the resizing of HashMap when a number of elements in the HashMap cross the load factor e.g. if the load factor is 0.75 and when becoming more than 75% full then resizing trigger which involves array copy.
When to use interface and when to use abstract class?
Actually most of the times, using Interfaces and abstract classes together is the best approach for designing a system. We should always start with an interface as base and define methods that every subclasses should implement and then if there are some methods that only certain subclass should implement, we can extend the base interface and create a new interface with those methods. The subclasses will have option to chose between the base interface or the child interface to implement according to its requirements. If the number of methods grows a lot, its not a bad idea to provide a skeletal abstract class implementing the child interface and providing flexibility to the subclasses to chose between interface and abstract class. For example in JDK java.util.List is an interface that contains a lot of methods, so there is an abstract class java.util.AbstractList that provides skeletal implementation for all the methods of List interface so that any subclass can extend this class and implement only required methods.
Why Map interface doesn't extend Collection interface?
Although Map interface and it's implementations are part of Collections Framework, Map are not collections and collections are not Map. Hence it doesn't make sense for Map to extend Collection or vice versa. If Map extends Collection interface, then where are the elements? Map contains key-value pairs and it provides methods to retrieve list of Keys or values as Collection but it doesn't fit into the "group of elements" paradigm.
What is difference between ArrayList and LinkedList?
ArrayList is an index based data structure backed by Array, so it provides random access to it's elements with performance as O(1) but LinkedList stores data as list of nodes where every node is linked to it's previous and next node. So even though there is a method to get the element using index, internally it traverse from start to reach at the index node and then return the element, so performance is O(n) that is slower than ArrayList. Insertion, addition or removal of an element is faster in LinkedList compared to ArrayList because there is no concept of resizing array or updating index when element is added in middle. LinkedList consumes more memory than ArrayList because every node in LinkedList stores reference of previous and next elements.
How HashMap works in Java?
HashMap works on hashing algorithm and uses hashCode() and equals() method in put and get methods. When we call put method by passing key-value pair, HashMap uses Key hashCode() with hashing to find out the index to store the key-value pair. The Entry is stored in the LinkedList, so if there are already existing entry, it uses equals() method to check if the passed key already exists, if yes it overwrites the value else it creates a new entry and store this key-value Entry. When we call get method by passing Key, again it uses the hashCode() to find the index in the array and then use equals() method to find the correct Entry and return it's value. Below image will explain these detail clearly.
Can an interface implement or extend another interface?
Interfaces don't implement another interface, they extend it. Since interfaces can't have method implementations, there is no issue of diamond problem. That's why we have multiple inheritance in interfaces i.e an interface can extend multiple interfaces. From Java 8 onwards, interfaces can have default method implementations. So to handle diamond problem when a common default method is present in multiple interfaces, it's mandatory to provide implementation of the method in the class implementing them.
How does put() method of HashMap works in Java?
It is responsible for storing an object into backend array. The hashcode() method is used in conjunction with a hash function to find the correct location for the object into the bucket. If a collision occurs then the entry object which contains both key and value is added to a linked list and that linked list is stored into the bucket location.
Why String class is made immutable?
Java designer knows that String is going to be most used data type in all kind of Java applications and they wanted to optimize from start. One of key step on that direction was idea of storing String literals in String pool. JVM looks in the String pool to find if any other String is stored with same value. If found, it just returns the reference to that String object else it creates a new String object with given value and stores it in the String pool. Since strings are immutable, multiple parties are able to share the same string without worrying about the string being modified. It increases security because any hacker can't change its value and it's used for storing sensitive information such as database username, password etc. Since String is immutable, it's safe to use in multi-threading and we don't need any synchronization.
List, Set and Map
List in Java provides ordered and indexed collection which may contain duplicates. The Set interface provides an unordered collection of unique objects, i.e. Set doesn't allow duplicates, while Map provides a data structure based on key-value pair and hashing. The main difference between List and Set interface in Java is that List allows duplicates while Set doesn't allow duplicates. All implementation of Set honor this contract. While a Map holds two objects per Entry e.g. a key and a value and It may contain duplicate values but keys are always unique. Another key difference between List and Set is that List is an ordered collection, List's contract maintains insertion order or element. Set is an unordered collection, you get no guarantee on which order element will be stored. The list allows null elements and you can have many null objects in a List because it also allowed duplicates. Set just allow one null element as there is no duplicate permitted while in Map you can have null values and at most one null key. Worth noting is that Hashtable doesn't allow null key or values but HashMap allows null values and one null key.
What's the difference between "a == b" and "a.equals(b)"?
The a = b does object reference matching if both a and b are an object and only return true if both are pointing to the same object in the heap space, on the other hand, a.equals(b) is used for logical mapping. It checks if the values are the same regardless their references.
What is the difference between capacity and size of HashMap in Java?
The capacity denotes how many entries HashMap can store and size denotes how many mappings or key/value pair is currently present.
Difference between final, finalize and finally?
The final is a modifier which you can apply to variable, methods and classes. If you make a variable final it means its value cannot be changed once initialized. If you make a method final in Java, you can not override it in subclass. If you make a class final means it can not be sub classed. Making a class final automatically makes all its method final. finalize is a method, which is called just before an object is a garbage collected, giving it last chance to resurrect itself, but the call to finalize is not guaranteed. finally is a keyword which is used in exception handling along with try and catch. the finally block is always executed irrespective of whether an exception is thrown from try block or not.
How many entries you can store in HashMap? What is the maximum limit?
There is no maximum limit for HashMap, you can store as many entries as you want because when you run out of the bucket, entries will be added to a linked list which can support an infinite number of entries, of course until you exhaust all the memory you have.
What is Serialization and Deserialization?
We can convert a Java object to an Stream that is called Serialization. Once an object is converted to Stream, it can be saved to file or send over the network. The object should implement Serializable interface and we can use java.io.ObjectOutputStream to write object to file or to any OutputStream object.
Wrapper class in Java
Wrapper class in java are the Object representation of eight primitive types in java. All the wrapper classes in java are immutable and final. Java 5 autoboxing and unboxing allows easy conversion between primitive types and their corresponding wrapper classes in java programs.
Can we use String in the switch case?
Yes from Java 7 onward we can use String in switch case. Internally string hash code is used for the switch.
Can you store a null key in Java HashMap?
Yes, HashMap allows one null key which is stored at the first location of bucket array e.g. bucket[0] = value. The HashMap doesn't call hashCode() on null key because it will throw NullPointerException, hence when a user call get() method with null then the value of the first index is returned.
Is it possible for two unequal objects to have the same hashcode?
Yes, two unequal objects can have same hashcode that's why collision happen in a hashmap.
Can you store the duplicate value in Java HashMap?
Yes, you can put duplicate values in HashMap of Java. It allows duplicate values, that's why when you retrieve all values from the Hashmap by calling values() method it returns a Collection and not Set.
What is a.hashCode() used for? How is it related to a.equals(b)?
hashCode() method returns an int hash value corresponding to an object. It's very tightly related to equals() method. According to Java specification, two objects which are equal to each other using equals() method must have same hash code.
What does super keyword do?
super keyword can be used to access super class method when you have overridden the method in the child class.
What is this keyword?
this keyword provides reference to the current object and it's mostly used to make sure that object variables are used, not the local variables having same name.