30 May
30May

This is a general blog where we post the most commonly asked Interview questions in the companies.

A Brief Introduction about Exception Handling in Java?
The Exception Handling in Java is one of the powerful mechanism to handle the runtime errors so that normal flow of the application can be maintained.

An exception is an unwanted or unexpected event, which occurs during the execution of a program i.e at run time, that disrupts the normal flow of the program’s instructions.

Error: An Error indicates serious problem that a reasonable application should not try to catch.
Exception: Exception indicates conditions that a reasonable application might try to catch.

Dictionary Meaning: Exception is an abnormal condition.

In Java, an exception is an event that disrupts the normal flow of the program. It is an object which is thrown at runtime.

The core advantage of exception handling is to maintain the normal flow of the application. An exception normally disrupts the normal flow of the application that is why we use exception handling.

The java.lang.Throwable class is the root class of Java Exception hierarchy which is inherited by two subclasses: Exception and Error. A hierarchy of Java Exception classes are given below


Types of Java Exceptions

There are mainly two types of exceptions: checked and unchecked. Here, an error is considered as the unchecked exception. According to Oracle, there are three types of exceptions:

  1. Checked Exception
  2. Unchecked Exception
  3. Error
Types of Java Exceptions

Difference between Checked and Unchecked Exceptions

1) Checked Exception

The classes which directly inherit Throwable class except RuntimeException and Error are known as checked exceptions e.g. IOException, SQLException etc. Checked exceptions are checked at compile-time.

2) Unchecked Exception

The classes which inherit RuntimeException are known as unchecked exceptions e.g. ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc. Unchecked exceptions are not checked at compile-time, but they are checked at runtime.

3) Error

Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.


There are 5 keywords which are used in handling exceptions in Java.

KeywordDescription
tryThe "try" keyword is used to specify a block where we should place exception code. The try block must be followed by either catch or finally. It means, we can't use try block alone.
catchThe "catch" block is used to handle the exception. It must be preceded by try block which means we can't use catch block alone. It can be followed by finally block later.
finallyThe "finally" block is used to execute the important code of the program. It is executed whether an exception is handled or not.
throwThe "throw" keyword is used to throw an exception.
throwsThe "throws" keyword is used to declare exceptions. It doesn't throw an exception. It specifies that there may occur an exception in the method. It is always used with method signature.



HTTP Request

The request sent by the computer to a web server, contains all sorts of potentially interesting information; it is known as HTTP requests. 

The HTTP client sends the request to the server in the form of request message which includes following information:

  • The Request-line
  • The analysis of source IP address, proxy and port
  • The analysis of destination IP address, protocol, port and host
  • The Requested URI (Uniform Resource Identifier)
  • The Request method and Content
  • The User-Agent header
  • The Connection control header
  • The Cache control header

The HTTP request method indicates the method to be performed on the resource identified by the  Requested URI (Uniform Resource Identifier). This method is case-sensitive and should be used in uppercase.

The HTTP request methods are:

HTTP RequestDescription
GETAsks to get the resource at the requested URL.
POSTAsks the server to accept the body info attached. It is like GET request with extra info sent with the request.
HEADAsks for only the header part of whatever a GET would return. Just like GET but with no body.
TRACEAsks for the loopback of the request message, for testing or troubleshooting.
PUTSays to put the enclosed info (the body) at the requested URL.
DELETESays to delete the resource at the requested URL.
OPTIONSAsks for a list of the HTTP methods to which the thing at the request URL can respond


There are many differences between the Get and Post request. Let's see these differences:

GETPOST
1) In case of Get request, only  limited amount of data  can be sent because data is sent in header.In case of post request,  large amount of data  can be sent because data is sent in body.
2) Get request is  not secured  because data is exposed in URL bar.Post request is  secured  because data is not exposed in URL bar.
3) Get request  can be bookmarked.Post request  cannot be bookmarked.
4) Get request is  idempotent . It means second request will be ignored until response of first request is deliveredPost request is  non-idempotent.
5) Get request is  more efficient  and used more than Post.Post request is  less efficient  and used less than get.


Some other features of GET requests are:

  • It remains in the browser history
  • It can be bookmarked
  • It can be cached
  • It have length restrictions
  • It should never be used when dealing with sensitive data
  • It should only be used for retrieving the data

Some other features of POST requests are:

  • This requests cannot be bookmarked
  • This requests have no restrictions on length of data
  • This requests are never cached
  • This requests do not retain in the browser history


Why String is immutable in Java?
String is immutable in java. An immutable class is simply  a class whose instances cannot be modified. All information in an instance is initialized when the instance is created and the information cannot be modified.

Following are the advantages of String being immutable:
  • If a String is mutable then changing the string with one reference will lead to the wrong values for the other references.
  • Another reason of Why String is immutable in Java is to allow String to cache its hashcode, being immutable String in Java caches its hashcode, and do not calculate every time we call hashcode method of String, which makes it very fast as hashmap key to be used in hashmap in Java.
  • In short because String is immutable, no one can change its contents once created which guarantees hashCode of String to be same on multiple invocations.
  • Since String is immutable it can safely share between many threads which is very important for multithreaded programming and to avoid any synchronization issues in
  • Java, Immutability also makes String instance thread-safe in Java, means you don't need to synchronize String operation externally.if String is not immutable, this would lead serious security threat, I mean someone can access to any file for which he has authorization, and then can change the file name either deliberately or accidentally and gain access to that file. Because of immutability, you don't need to worry about that kind of threats. This reason also gels with, Why String is final in Java, by making java.lang.String final, Java designer ensured that no one overrides any behavior of String class.


When Collision occurs in Hashmap and what are the resolution techniques?
A collision will occur on Hashtable or HashMap when hashCode() method of two different key objects will return same values. That's all about how HashMap in Java handles collisions. In general, this method is called chaining because all objects stored in the same bucket are chained as linked list

Prior to Java 8, HashMap and all other hash table based Map implementation classes in Java handle collision by chaining, i.e. they use linked list to store map entries which ended in the same bucket due to a collision. If a key end up in same bucket location where an entry is already stored then this entry is just added at the head of the linked list there. In the worst case this degrades the performance of the get() method of HashMap to O(n) from O(1). In order to address this issue in the case of frequent HashMap collisions, Java8 has started using a balanced tree instead of linked list for storing collided entries. This also means that in the worst case you will get a performance boost from O(n) to O(log n).

The threshold of switching to the balanced tree is defined as TREEIFY_THRESHOLD constant in java.util.HashMap JDK 8 code. Currently, it's value is 8, which means if there are more than 8 elements in the same bucket than HashMap will use a tree instead of linked list to hold them in the same bucket.
This feature will not available to all hash table based classes in Java e.g. Hashtable will not have this feature because of its legacy nature and given that this feature can change the traditional legacy iteration order of Hashtable. Similarly, WeakHashMap will also not include this feature.


1) HashMap handles collision by using linked list to store map entries ended up in same array location or bucket location.

2) From Java 8 onwards, HashMap, ConcurrentHashMap, and LinkedHashMap will use the balanced tree in place of linked list to handle frequently hash collisions. The idea is to switch to the balanced tree once the number of items in a hash bucket grows beyond a certain threshold. This will improve the worst case get() method performance from O(n) to O(log n).

3) By switching from linked list to balanced tree for handling collision, the iteration order of HashMap will change. This is Ok because HashMap doesn't provide any guarantee on iteration order and any code which depends upon that are likely to break.

4) Legacy class Hashtable which exists in JDK from Java 1 will not use the balanced binary tree to handle frequent hash collision to keep its iteration order intact. This was decided to avoid breaking many legacy Java application which depends upon iteration order of Hashtable.

5) Apart from Hashtable, WeakHashMap and IdentityHashMap will also continue to use the linked list for handling collision even in the case of frequent collisions.

6) Collision in HashMap is possible because hash function uses hashCode() of key object and equals() and hashCode() contract doesn't guarantee different hashCode for different objects. Remember, they guarantee same hash code for the equal object but not the vice-versa.

7) A collision will occur on Hashtable or HashMap when hashCode() method of two different key objects will return same values.



Comments
* The email will not be published on the website.
I BUILT MY SITE FOR FREE USING