Thursday, 21 May 2020

Latest Java Interview Questions- Part 1

Hello Readers, these are the questions from my Interview experience. I have framed these questions in such a way to make yourself prepared for any technical challenging interviews. Continue my other parts of the Interview questions.

All the VeryBest !!!!

1.Can we override static method?
No, you cannot override static method in Java, though you can declare method with same signature in sub class. It won't be overridden in exact sense, instead that is called method hiding.

2.Can you explain why we cannot override the static method?
It may be decided during the time of resolution, static binding, are bonded during compile time using Type of reference variable, and not Object.
 If you declare, another static method with same signature in derived class than static method of super class will be hidden, and any call to that static method in sub class will go to static method declared in that class itself.

3. Explain Method Hiding?
When the Super class and subclass has the same method with same arguments then the super class method is hidden by the subclass method this is called as the method hiding. Usually this happens when the methods are defined as static.

4. Can We Overload the Static method?
Yes, we can overload static methods in Java, there is nothing wrong declaring static methods with same name, but different arguments.

5. can we override final method?
Final methods cannot be overridden because the purpose of the "final" keyword is to prevent overriding.

6. What is this and super key words in Java can we use both same time.
· we use this() keyword in constructor chaining to access the constructor of the same class
· we use super() keyword when we want to access the constructor of immediate parent class in inheritance.
And there is a condition in both that they have to be declared in the first line of the constructor you are using. And that's the reason why we can't use both in a single constructor because you can write only one thing in your first line.

7. what is Static block, what is the use of it and explain with the program.
Java supports a special block, called static block (also called static clause) which can be used for static initializations of a class. This code inside static block is executed only once: the first time you make an object of that class or the first time you access a static member of that class (even if you never make an object of that class).
Also, static blocks are executed before constructors. For example, check output of following Java program

class Test {
    static int i;
    int j;
    // start of static block
    static {
        i = 10;
        System.out.println("static block called ");
    }
    // end of static block
}
class Main {
    public static void main(String args[]) {
        // Although we don't have an object of Test, static block is
        // called because i is being accessed in following statement.
        System.out.println(Test.i);
    }
}

8.Explain Java 7 Features.
Decorate Components with the JLayer Class:
The JLayer class is a flexible and powerful decorator for Swing components. The JLayer class in Java SE 7 is similar in spirit to the JxLayer project at java.net. The JLayer class was initially based on the JXLayer project, but its API evolved separately.
Strings in switch Statement:
In the JDK 7, we can use a String object in the expression of a switch statement. The Java compiler generates generally more efficient bytecode from switch statements that use String objects than from chained if-then-else statements.
Type Inference for Generic Instance:
We can replace the type arguments required to invoke the constructor of a generic class with an empty set of type parameters (<>) as long as the compiler can infer the type arguments from the context. This pair of angle brackets is informally called the diamond. Java SE 7 supports limited type inference for generic instance creation; you can only use type inference if the parameterized type of the constructor is obvious from the context. For example, the following example does not compile:
List<String> l = new ArrayList<>();
l.add("A");
l.addAll(new ArrayList<>());
In comparison, the following example compiles:
List<? extends String> list2 = new ArrayList<>();
l.addAll(list2);
Catching Multiple Exception Types and Rethrowing Exceptions with Improved Type Checking:
In Java SE 7 and later, a single catch block can handle more than one type of exception. This feature can reduce code duplication. Consider the following code, which contains duplicate code in each of the catch blocks:
catch (IOException e) {
  logger.log(e);
  throw e;
}
catch (SQLException e) {
  logger.log(e);
  throw e;
}
In releases prior to Java SE 7, it is difficult to create a common method to eliminate the duplicated code because the variable e has different types. The following example, which is valid in Java SE 7 and later, eliminates the duplicated code:
catch (IOException|SQLException e) {
  logger.log(e);
  throw e;
}
The catch clause specifies the types of exceptions that the block can handle, and each exception type is separated with a vertical bar (|).


The java.nio.file package
The java.nio.file package and its related package, java.nio.file.attribute, provide comprehensive support for file I/O and for accessing the file system. A zip file system provider is also available in JDK 7.

9. Explain Java 8 Features.
Lambda Expressions
Lambda expressions gives the ability to pass a functionality as a method argument. Lambda expression help us reduce the code clutter in using a single method class. For example, when we must associate an action button click to a functionality, then lambda expressions will make the code look neat and compact. Refer Java Lambda expression examples to learn more.
Pipelines and Streams
Pipelines and streams enrich the Java collections framework. Sequence of aggregate operations is a pipeline. Stream is used to propagate elements from a source through a pipeline. It is a sequence of elements. Pipeline and streams will make our task easier in accessing the elements from collections and applying operations on it.
Date and Time API
Pre Java 8, date and time related operations are little bit cumbersome. JSR 310: Date and Time API give us a brand new package java.time package. This is a well thought package. It contains a best list of utility methods used for regular operations. This will help in handling date and time operations in an easier way.
Default Methods
Default methods gives the ability to add default implementation for methods in an interface. This is a rocking feature of Java 8. When we implement an interface, if we did not provide implementation for a method, then the default method will be used in that place. This will help in maintaining backward compatibility in applications, we can add a method to an interface without breaking its implementations.
Type Annotations
Before Java 8 Java annotations can be applied to type declarations. From this Java 8 release onwards, annotations can be applied to type use. Annotations can be applied wherever a type is used like in new instance creates, exception throws clause etc. This will help to enforce stronger type checks and using this feature we can come up with a type checking framework itself.
Nashorn JavaScript Engine
Nashorn is a brand new JavaScript engine provided along with the Java 8 release. Using this we can develop standalone JavaScript applications in Java. Pre Java 8, we got JDK with a JavaScript engine based on Rhino. It is a developed from scratch. It will provide better compatibility with ECMA normalized JavaScript specification and better performance than Rhino. Already we have seen a tutorial to run Javascript in Java using the ScriptEngineManager.
Concurrent Accumulators
java.util.concurrent.atomic package is getting additional classes as part of Java 8 release. These will help to sum values from across multiple threads.
Parallel operations
Iterating over a collection can be done in parallel using the aggregate operations easily. Pre Java 8 Iterators are used to parse the elements of a collection one by on explicitly. Now that can be done in parallel internally with the use of streams and aggregate operations. We can create multiple substreams and those substreams can be processed internally in parallel and then the results be combined. For this to be effective, we need to have multiple cores and data volume.
PermGen Space Removed
The PermGen space is removed from Java 8 and instead we have MetaSpace introduced. One of the most dreaded error, “java.lang.OutOfMemoryError: PermGen error” will no longer be seen from Java 8. Nice thing is that the MetaSpace default is unlimited and that the system memory itself becomes the memory.
Metaspace capacity
By default class metadata allocation is limited by the amount of available native memory (capacity will of course depend if you use a 32-bit JVM vs. 64-bit along with OS virtual memory availability).
A new flag is available (MaxMetaspaceSize), allowing you to limit the amount of native memory used for class metadata. If you don’t specify this flag, the Metaspace will dynamically re-size depending of the application demand at runtime.
TLS SNI
Server Name Indentification (SNI) is an extension of the TLS protocol used for identifying the certificate to serve based on the hostname specified by the client. This enables a server to have virtual host over HTTPS. The same IP address can be used for multiple hosts and their respective different security certificates.
The above list of Java 8 features is just a highlight. I will be writing detailed tutorials about each of them in the coming days.
10. What is ConcurrencyHashMap and data structure of it
ConcurrentHashMap: It allows concurrent access to the map. Part of the map called Segment (internal data structure) is only getting locked while adding or updating the map. So ConcurrentHashMap allows concurrent threads to read the value without locking at all. This data structure was introduced to improve performance.
The point is to provide an implementation of HashMap that is threadsafe. Multiple threads can read from and write to it without the chance of receiving out-of-date or corrupted data. ConcurrentHashMapprovides its own synchronization, so you do not have to synchronize accesses to it explicitly.
ConcurrentHashMap allow concurrent access to the map. HashTables too offers synchronized access to map, but your entire map is locked to perform any operation.
The logic behind ConcurrentHashMap is that your entire table is not getting locked, but only the portion[segments]. Each segments manages its own HashTable. Locking is applied only for updates. In case of of retrievals, it allows full concurrency.

11.What is CopyOnWriteArrayList?
As the name indicates, CopyOnWriteArrayList creates a Cloned copy of underlying ArrayList, for every update operation at certain point both will be synchronized automatically, which is taken care by JVM. Therefore, there is no effect for threads which are performing read operation.
It is costly to use because for every update operation a cloned copy will be created. Hence CopyOnWriteArrayList is the best choice if our frequent operation is read operation.
It extends object and implements Serializable, Cloneable, Iterable<E>, Collection<E>, List<E> and RandomAccess
The underlined data structure is grow-able array.
It is thread-safe version of ArrayList.
Insertion is preserved, duplicates are allowed, and heterogeneous Objects are allowed.
The main important point about CopyOnWriteArrayList is Iterator of CopyOnWriteArrayList cannot perform remove operation otherwise we get Run-time exception saying UnsupportedOperationException.

12. Difference between SYNCHRONIZEDLIST and COPYONWRITEARRAYLIST
SYNCHRONIZEDLIST
COPYONWRITEARRAYLIST
It locks the whole list for thread-safety during both read or write operation.
It locks the list during write operation only, so no lock during read operation therefore, multiple threads executing read operations concurrently.
It is a fail-fast iterator.
It is a fail-safe iterator.
It is Introduced in Java 1.2 version.
It is Introduced in Java 1.5 version.
Iteration of list should be inside synchronized block otherwise it will face non-deterministic behaviour.
It can safely iterate outside the synchronized block.
If any other thread tries to modify the list while one thread iterating that list, then it will throw ConcurrentModificationException.
It doesn’t allow modifying the list while traversing, and it will not throw ConcurrentModificationException if the list is being modified by other thread during the traversal.
It is best to use when arraylist is large and write operation are greater than read operation in list.
It is best to use when ArrayList is small or read operation are greater than write operation.

13.Difference between ArrayList and LinkedList.
ArrayList
LinkedList
1) ArrayList internally uses a dynamic array to store the elements.
LinkedList internally uses a doubly linked list to store the elements.
2) Manipulation with ArrayList is slow because it internally uses an array. If any element is removed from the array, all the bits are shifted in memory.
Manipulation with LinkedList is faster than ArrayList because it uses a doubly linked list, so no bit shifting is required in memory.
3) An ArrayList class can act as a list only because it implements List only.
LinkedList class can act as a list and queue both because it implements List and Deque interfaces.
4) ArrayList is better for storing and accessing data.
LinkedList is better for manipulating data.

14. Difference between SinglyLinked list and DoublyLinked list, and when to use them.
Singly linked list
Doubly linked list
A singly linked list is a linked list where the node contains some data and a pointer to the next node in the list
A doubly linked list is complex type of linked list where the node contains some data and a pointer to the next as well as the previous node in the list
It allows traversal only in one way
It allows a two way traversal
It uses less memory per node (single pointer)
It uses more memory per node(two pointers)
Complexity of insertion and deletion at a known position is O(n)
Complexity of insertion and deletion at a known position is O(1)
If we need to save memory and searching is not required, we use singly linked list
If we need better performance while searching and memory is not a limitation, we go for doubly linked list
If we know that an element is located towards the end section, eg. ‘zebra’ still we need to begin from start and traverse the whole list
If we know that an element is located towards the end section e.g. ’zebra’ we can start searching from the Back.
Singly linked list can mostly be used for stacks
They can be used to implement stacks, heaps, binary trees.

15. what is equals and hashCode methods in Java and how they are related.
Java equals() and hashCode() methods are present in Object class. So every java class gets the default implementation of equals() and hashCode(). In this post we will look into java equals() and hashCode() methods in detail.
Object class defined equals() method like this:
According to java documentation of equals() method, any implementation should adhere to following principles.
· For any object x, x.equals(x) should return true.
· For any two object x and y, x.equals(y) should return true if and only if y.equals(x)returns true.
· For multiple objects x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true.
· Multiple invocations of x.equals(y) should return same result, unless any of the object properties is modified that is being used in the equals() method implementation.
· Object class equals() method implementation returns true only when both the references are pointing to same object.
Java hashCode()
Java Object hashCode() is a native method and returns the integer hash code value of the object. The general contract of hashCode() method is:
· Multiple invocations of hashCode() should return the same integer value, unless the object property is modified that is being used in the equals() method.
· An object hash code value can change in multiple executions of the same application.
· If two objects are equal according to equals() method, then their hash code must be same.
· If two objects are unequal according to equals() method, their hash code are not required to be different. Their hash code value may or may-not be equal.
Importance of equals() and hashCode() method
Java hashCode() and equals() method are used in Hash table based implementations in java for storing and retrieving data.
The implementation of equals() and hashCode() should follow these rules.
· If o1.equals(o2), then o1.hashCode() == o2.hashCode() should always be true.
· If o1.hashCode() == o2.hashCode is true, it doesn’t mean that o1.equals(o2) will be true.
1.By implementing the Runnable interface.
class MyThread implements Runnable {
    public void run() {
        System.out.println("concurrent thread started running..");
    }
}

class MyThreadDemo {
    public static void main(String args[]) {
        MyThread mt = new MyThread();
        Thread t = new Thread(mt);
        t.start();
    }
}
2.By extending the Thread class.
class MyThread extends Thread {
    public void run() {
        System.out.println("concurrent thread started running..");
    }
}

classMyThreadDemo {
    public static void main(String args[]) {
        MyThread mt = new MyThread();
        mt.start();
    }
}

16.what is run () method is used for.
The run() method of thread class is called if the thread was constructed using a separate Runnable object otherwise this method does nothing and returns. When the run() method calls, the code specified in the run() method is executed. You can call the run() method multiple times.
The run() method can be called using the start() method or by calling the run() method itself. But when you use run() method for calling itself, it creates problems.
If you directly call run() method its body is executed in context of current thread. When you invoke start() method a new thread is created and run() method is executed in this new thread.

17. How HashMap works internally?
HashMap works on the principle of hashing. Hashing can be defined as assigning the code to the object by applying the algorithm.

In Hashmap the objects are stored in the buckets by converting the hashcode for the key and the bucket is found and saved there and again if the object is got using the key, then the hashcode is applied and read from that location. The Hashmap works in this principle of hashing. The hashcode should be same during the saving and retrieving (it's mandatory for it to do so to retrieve the object and that's why HashMap keys are immutable e.g. String) hence we will not lose the objects stored. HashMap internally stores mapping in the form of Map.Entry object which contains both key and value object.

This will go smoother when we have only one object stored for the location, Sometimes the collision may happen. Since the HashMap internally stores in array, this is of fixed size, and if you keep storing objects, at some point of time hash function will return same bucket location for two different keys, this is called collision in HashMap. In this case, a linked list is formed at that bucket location and a new entry is stored as next node.

If we try to retrieve an object from this linked list, we need an extra check to search correct value, this is done by equals() method. Since each node contains an entry, HashMap keeps comparing entry's key object with the passed key using equals() and when it return true, Map returns the corresponding value.


From Java8 the Linkedlist is replaced with the tree for the searching.

18. Which one is used for faster search, HashMap or TreeMap and why.
a HashMap is O(1) average, so it is supposed to be faster, and for large maps will probably have better throughput.
However, a HashMap requires rehashing when Load Balance become too high. rehashing is O(n), so at any time of the program's life, you may suffer unexpectedly performance loss due to rehash, which might be critical in some apps [high latency]. So think twice before using HashMap if
latency is an issue!
However, if you would often need to process your dictionary in alphabetical order, you would be better off with the TreeMap since you would otherwise need to sort all your words every time you need to process them in alphabetical order.
       We should use a TreeMap if we want to keep our entries sorted
       We should use a HashMap if we prioritize performance over memory consumption
       Since a TreeMap has a more significant locality, we might consider it if we want to access objects that are relatively close to each other according to their natural ordering
       HashMap can be tuned using the initialCapacity and loadFactor, which isn’t possible for the TreeMap
       We can use the LinkedHashMap if we want to preserve insertion order while benefiting from constant time access

19. What will happen if i call thread.start()?
No. After starting a thread, it can never be started again. If you do so, an IllegalThreadStateException is thrown. In such case, thread will run once but for second time, it will throw exception. Running Exception in thread "main" java.lang.IllegalThreadStateException

20.Difference between ArrayList and LinkedList
ArrayList
LinkedList
1) ArrayList internally uses a dynamic array to store the elements.
LinkedList internally uses a doubly linked list to store the elements.
2) Manipulation with ArrayList is slow because it internally uses an array. If any element is removed from the array, all the bits are shifted in memory.
Manipulation with LinkedList is faster than ArrayList because it uses a doubly linked list, so no bit shifting is required in memory.
3) An ArrayList class can act as a list only because it implements List only.
LinkedList class can act as a list and queue both because it implements List and Deque interfaces.
4) ArrayList is better for storing and accessing data.
LinkedList is better for manipulating data.

No comments:
Write comments