Data structures Flashcards
Difference between String vs StringBuffer in Java
1.Immutability
The first and foremost difference between String and StringBuffer is that the former is Immutable while the latter is mutable. This means if you need to manipulate String data then wrap it inside a StringBuffer to avoid creating lots of small and temporary String objects and putting pressure on the Garbage collector.
- Thread Safety
Even though both StringBuffer and String are thread-safe, String achieves its thread-safety by using Immutability while StringBuffer achieves it by synchronizing methods that change the state e.g. append(), delete(), etc.
Difference between StringBuffer vs StringBuilder in Java
If you look at the code of StringBuilder.java class in JDK, you will realize that it’s just StringBuffer without synchronized keywords, even comments and descriptions of methods are the same. Anyway, let’s see some quick differences between StringBuffer and StringBuilder class in Java:
- Thread Safety
The most important difference between StringBuffer and StringBuilder is that the former is thread-safe and the latter is not. Why? because all key methods of StringBuffer are synchronized, which was later removed while creating the StringBuilder class. - Performance
Due to the above property, their performance is also different. StringBuilder is much faster than StringBuffer. Since they are mostly used as local variables to manipulate String and not really shared between multiple threads, it’s better to use StringBuilder in place of, StringBuffer.
When to use the String, StringBuffer, and StringBuilder in Java?
1) Use String if you need text data which is relatively constant e.g. names, config parameters, etc.
2) Use StringBuilder if are doing lots of String concatenation e.g. you are generating dynamic String by using programming logic.
3) Use StringBuffer when your String manipulation code is likely to be executed by multiple threads and you are sharing the instance of the same StringBuffer. It’s highly unlikely and if you are doing some just stop doing it and use StringBuilder in place.
Difference between Polymorphism and Inheritance in Java?
Inheritance allows code reuse and builds the relationship between classes, which is required by Polymorphism, which provides dynamic behavior.
In short here are the key difference between Polymorphism and Inheritance in Java;
- Inheritance defines the father-son relationship between two classes, While Polymorphism takes advantage of that relationship to add dynamic behavior in your code.
- Inheritance is meant for code reuse, the initial idea is to reuse what is written inside the Parent class and only write code for new functions or behavior in the Child class.
- Polymorphism helps tremendously during Maintenance. In fact, many object-oriented design principles are based on Polymorphism like programming for interface than implementation
- Java doesn’t allow multiple inheritances of classes but allows multiple inheritances of Interface, which is actually required to implement Polymorphism
Can we override the static method in Java?
No because overriding resolves at runtime while static method call is resolved at compile time
Difference between interface and abstract class in Java?
From Java 8, the difference is blurred, but still a Java class can implement multiple interfaces but can extend just one class.
What is IdentityHashMap in Java?
A Map that uses == equality operator to check equality instead of equals() method.
equal() vs == operator
The fundamental difference between IdentityHashMap and other Map implementations like HashMap, Hashtable, WeakHashMap, or EnumMap it uses an equality operator (==) to search and get the value back. If you know how to get the method of Map works the know that other Map implementation, which uses equals() method of the key object for that purpose.
Since == operator only returns true if the reference variables point to the same object, it’s not possible to get the value with a different object even if it appears equal in all fields. You must hold the reference of the key object outside the IdentityHashMap to get the value back.
Difference between Comparator and Comparable in Java?
Comparator defines custom ordering while Comparable defines the natural order of objects, e.g. the alphabetic order for String. If you are implementing a value object then you can consider implementing Comparable in Java. Also, you can define multiple Comparator for different kind of comparison and ordering requirements.
Difference between Error and Exception in Java?
The main difference between Error and Excpetion in Java is that Error is reserved for System related error like NoClassDefFoundError, OutOfMemoryError etc. This means you cannot recover from Errror, hence they are like RuntimeException, Java doesn’t check if you handle error or not. On the other hand, Exception is also an indication of unexpected condition but you can recover. There are two types of Exception, checked and unchecked. For checked exception, Java mandates to handle them.
”==” Operator
”==” is an operator in Java and hence it is can not be overridden.
It is generally used to compare two variables of primitive data types but can be used to compare objects as well.
It compares the data of the two variables, but in the case of objects, it compares the memory locations.
It takes O(1) time for comparison.
It throws a compile time error if the two variables are not of the same data type.
.equals() Method
equals() is a method in Java and hence it can be overridden.
It is used to compare objects. It can not compare primitive data types.
It compares the memory location of the objects. For the String objects, it compares them character by character as well if the memory location equality fails.
It takes O(1) time for normal objects and O(n) time for String objects.
It returns a “false” value if the objects are not of the same type.
Difference between ArrayList vs HashSet in Java
- First and most important difference between ArrayList and HashSet is that ArrayList implements List interface while HashSet implements Set interface in Java.
- Another difference between ArrayList and HashSet is that ArrayList allows duplicates while HashSet doesn’t allow duplicates. This is the side effect of first difference and property of implementing List and Set interface.
- The differences between ArrayList and HashSet is that ArrayList is an ordered collection and maintains insertion order of elements while HashSet is an unordered collection and doesn’t maintain any order.
- The difference between ArrayList and HashSet is that ArrayList is backed by an Array while HashSet is backed by a HashMap instance. See how HashSet internally works in Java for more details.
- Fifth difference between HashSet and ArrayList is that it’s index-based you can retrieve objects by calling get(index) or remove objects by calling remove(index) while HashSet is completely object-based. HashSet also doesn’t provide the get() method.
Difference between List and Set in Java Collection?
1) Fundamental difference between List and Set in Java is allowing duplicate elements. List in Java allows duplicates while Set doesn’t allow any duplicate. If you insert a duplicate in Set it will replace the older value. Any implementation of Set in Java will only contain unique elements.
2) Another significant difference between List and Set in Java is order. List is an Ordered Collection while Set is an unordered collection. List maintains insertion order of elements, means any element which is inserted before will go on lower index than any element which is inserted after. Set in Java doesn’t maintain any order. Though Set provide another alternative called SortedSet which can store Set elements in specific Sorting order defined by Comparable and Comparator methods of Objects stored in Set.
3) Set uses equals() method to check uniqueness of elements stored in Set, while SortedSet uses compareTo() method to implement natural sorting order of elements. In order for an element to behave properly in Set and SortedSet, equals and compareTo must be consistent to each other.
4) Popular implementation of List interface in Java includes ArrayList, Vector, and LinkedList. While popular implementation of the Set interface includes HashSet, TreeSet, and LinkedHashSet.
When to use ArrayList vs LinkedList in Java?
The main difference between ArrayList vs LinkedList is that the former is backed by an array while the latter is based upon the linked list data structure, which makes the performance of add(), remove(), contains(), and iterator() different for both ArrayList and LinkedList.