-
Notifications
You must be signed in to change notification settings - Fork 1
Interview Concepts
Object as a Superclass
The Object class, in the java.lang package, sits at the top of the class hierarchy tree. Every class is a descendant, direct or indirect, of the Object class.
protected Object clone() throws CloneNotSupportedException
public boolean equals(Object obj)
protected void finalize() throws Throwable
public final Class getClass()
public int hashCode()
public String toString()
public final void notify()
public final void notifyAll()
public final void wait()
public final void wait(long timeout)
public final void wait(long timeout, int nanos)
Collection Framework is a combination of classes and interface, which is used to store and manipulate the data in the form of objects. interface Collection<E>extends Iterable
Iterator is a fail-fast in nature. i.e it throws ConcurrentModificationException if a collection is modified while iterating other than it’s own remove() method. Where as Enumeration is fail-safe in nature. It doesn’t throw any exceptions if a collection is modified while iterating.
Fail-fast iterators (those returned by HashMap, ArrayList, and other non-thread-safe collections) iterate over the collection’s internal data structure, and they throw ConcurrentModificationException as soon as they detect a concurrent modification.
Fail-safe iterators (returned by thread-safe collections such as ConcurrentHashMap) create a copy of the structure they iterate upon. They guarantee safety from concurrent modifications. Their drawbacks include excessive memory consumption and iteration over possibly out-of-date data in case the collection was modified. java.util.concurrent packages are fail-safe and we can modify the collection while iterating. Some of these classes are CopyOnWriteArrayList, ConcurrentHashMap, CopyOnWriteArraySet.
Hashtable is a legacy class introduced in JDK1.0, which is a subclass of Dictionary class. From JDK1.2 Hashtable is re-engineered to implement the Map interface to make a member of collection framework.
In order to synchronize it we are using Collections.synchronizedMap(hashmap) it returns a thread-safe map backed up by the specified HashMap.
UnsupportedOperationException« Map<String, String> unmodifiableMap = Collections.unmodifiableMap( map );
In Java 5 introduced ConcurrentMap Interface: ConcurrentHashMap - a highly concurrent, high-performance ConcurrentMap implementation backed by a hash table. This implementation never blocks when performing retrievals and allows the client to select the concurrency level for updates. It is intended as a drop-in replacement for Hashtable: in addition to implementing ConcurrentMap, it supports all of the "legacy" methods peculiar to Hashtable.
- Each HashMapEntrys value is volatile thereby ensuring fine grain consistency for contended modifications and subsequent reads; each read reflects the most recently completed update.
- Iterators and Enumerations are Fail Safe - reflecting the state at some point since the creation of iterator/enumeration; this allows for simultaneous reads and modifications at the cost of reduced consistency. They do not throw
ConcurrentModificationException. However, iterators are designed to be used by only one thread at a time.
Comparable and Comparator interfaces to sort collections
java.lang.Comparable: int compareTo(Object o1) « A comparable object is capable of comparing itself with another object. The class itself must implements the java.lang.Comparable interface in order to be able to compare its instances.
- Capable of comparing current object with the provided object.
- By using this we can implement
only one sort sequencebased on the instances properties. EX:Person.id - Some of the Predefined Classes like String, Wrapper classes, Date, Calendar has implemented Comparable interface.
java.util.Comparator: int compare(Object o1, Object o2) « A comparator object is capable of comparing two different objects. The class is not comparing its instances, but some other class’s instances. This comparator class must implement the java.util.Comparator interface.
- Capable of comparing any two Objects of Same Type.
- By using this we can implement
many sort sequenceand name each, based on the instances properties. EX:Person.id, Person.name, Person.age - We can implement Comparator interface to our Pre-defined classes for Customized sorting.
java.util.Collections is a utility class consists exclusively of static methods that operate on or return collections.
If we need to sort an array of Objects, we can use Arrays.sort(). If we need to sort a list of objects, we can use Collections.sort(). Both these classes have overloaded sort() methods for natural sorting (using Comparable) or sorting based on criteria (using Comparator).
List<Integer> list1 = Arrays.asList(5, 2, 3, 4, 1);
Collections.sort(list1);
System.out.println("Ascending Order: "+ list1 ); // [1, 2, 3, 4, 5]
List<Integer> list2 = Arrays.asList(5, 2, 3, 4, 1);
Collections.sort(list2, (a, b) -> b - a);
System.out.println("Descending Order:"+ list2 ); // [5, 4, 3, 2, 1]LinkedList is a doubly-linked list: single elements are put into Node objects that have references to previous and next Node. Insertion of a node objects are very fast.
ArrayList is an implementation of the List interface that is based on an array. ArrayList internally handles resizing of this array when the elements are added or removed. You can access its elements in constant time by their index in the array. However, inserting or removing an element infers shifting all consequent elements System.arraycopy() which may be slow if the array is huge and the inserted or removed element is close to the beginning of the list.
-
ArrayList is not synchronized. It uses Iterator interface to traverse the elements.
-
Vector is a legacy class and synchronized. Vector uses Enumeration interface to traverse the elements. But it can use Iterator also.
-
Stack class is the child class of Vector. It follows LIFO (Last in first out) mechanism.
List<String> al = new ArrayList<String>();//creating arraylist al.add("Sonoo");//adding object in arraylist Vector<String> v = new Vector<String>();//creating vector v.add("umesh");//method of Collection v.addElement("irfan");//method of Vector Stack st = new Stack(); // push(Object item), pop(), peek(), empty(), search(Object o) st.push("java");
In a class-based object-oriented language, in general, state is carried by instances, methods are carried by classes, and inheritance is only of structure and behavior. Basic, Refactoring Techniques
Method signature: It consists of method name and parameter list (number/type/order of the parameters). methodName(parametersList y). An instance method in a subclass with the same signature and return type as an instance method in the super-class overrides the super-class's method.
Java OOP concepts
Class - Collection of a common features of a group of object [static/instance Fields, blocks and Methods]
Object - Instance of a class (instance fields)
Abstraction - Process of hiding complex info and providing required info like API, Marker Interfaces ...
Encapsulation(Security) - Class Binding up with data members(fields) and member functions.
Inheritance (Reusability by placing common code in single class)
1. Multilevel - {A -> B -> C} 2. Multiple - Diamond problem {A <- (B) -> C} [Java not supports] 3. Cyclic {A <-> B} [Java not supports]
* Is-A Relation - Class A extends B
* Hash-A Relation - Class A { B obj = new B(); } - (Composition/Aggregation)
Polymorphism (Flexibility) 1. Compile-Time Overloading 2. Runtime Overriding [Greek - "many forms"]
int[] arr = {1,2,3}; int arrLength = arr.length; // Fixed length of sequential blocks to hold same data type
String str = "Yash"; int strLength = str.length(); // Immutable Object value can't be changed.
List<?> collections = new ArrayList<String>(); int collectionGroupSize = collections.size();
Map<?, ?> mapEntry = new HashMap<String, String>();
Set<?> keySet = mapEntry.keySet(); // Set of Key's
Set<?> entrySet = mapEntry.entrySet(); // Set of Entries [Key, Value]
// Immutable Objects once created they can't be modified. final class Integer/String/Employee
Integer val = Integer.valueOf("100"); String str2 = String.valueOf(100); // Immutable classes
final class Employee { // All Wrapper classes, java.util.UUID, java.io.File ...
private final String empName; // Field as Final(values can be assigned only once) Only getter functions.
public Employee(String name) { this.empName = name; }
} Native Java Code for Hashtable.h, Hashtable.cpp
SQL API.
You can check your current JDK and JRE versions on your command prompt respectively,
- JDK
javac -version [C:\Program Files\Java\jdk1.8.0_121\bin]o/p:javac 1.8.0_121 - JRE
java -version[C:\Program Files\Java\jdk1.8.0_121\bin]o/P:java version "1.8.0_102"
JAVA_HOME - Must be set to JDK otherwise maven projects leads to compilation error. [ERROR] No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK? C:\Softwares\OpenJDK\, 7-zip
Fatal error compiling: invalid target release: JRE and JDK must be of same version
1.8.0.XXX
Disable TLS 1.0 and 1.1
security-libs/javax.net.ssl: TLS 1.0 and 1.1 are versions of the TLS protocol that are no longer considered secure and have been superseded by more secure and modern versions (TLS 1.2 and 1.3).
Core Java
-
Java Programming Language Basics
- Object, Class, Encapsulation, Interface, Inheritance, Polymorphism (Method Overloading, Overriding)
- JVM Architecture, Memory Areas
- JVM Class Loader SubSystem
- Core Java Interview Questions & Programs
- Interview Concepts
Stack Posts
- Comparable vs Comparator
- Collections and Arrays
-
String, StringBuffer, and StringBuilder
- String reverse
- Remove single char
- File data to String
- Unicode equality check Spacing entities
- split(String regex, int limit)
- Longest String of an array
-
Object Serialization
- Interface's Serializable vs Externalizable
- Transient Keyword
-
implements Runnablevsextends Thread - JSON
- Files,
Logging API- Append text to Existing file
- Counting number of words in a file
- Properties
- Properties with reference key