## Factorial of Number using Recursion in Java

### Find Factorial of Number. ORJava Program to Find Factorial of Number. ORRecursive Program to find Factorial of Number.

A factorial is a function that multiplies a number by every number below it.

Factorial of 5
5! = 5 * 4 * 3 * 2 * 1 = 120.

Factorial of 3
3! = 3 * 2 * 1 = 120.

Note: The value of 0! is 1

Below you can get Factorial of number till 20.

## Print Matrix Diagonally OR Diagonal order of Matrix.

### Print Matrix Diagonally. ORLoop diagonally through two dimensional array. ORTraverse an array diagonally. ORPrint elements of Matrix in Diagonal order.

Given a Matrix / 2D array, Print all elements of Matrix in Diagonal order. Lets understand Diagonal order of Matrix graphically.

## Find a Saddle point in Matrix

### Find Saddle point in a matrix

Given a matrix of n x n size, Find saddle point of matrix.

What is Saddle point of Matrix?

Element is said to be Saddle point of Matrix if it is both a minimum of its row and a maximum of its column or vice versa.

A matrix may have 1 or 2 saddle points or may not have a saddle point.
Lets understand what will be input and expected output with the help of an example.

## Print nodes at K distance from Leaf node in Binary tree.

### Print nodes at K distance from Leaf in binary tree. ORPrint all nodes that are at distance k from a leaf node.

Given a Binary Tree, Print all Nodes that are at K distance from leaf node in Binary Tree. Lets understand what will be input and expected output with the help of an example.

If k = 1. It means we need to print all nodes that are at distance 1 from Leaf node.

In Case 2, we have 4 leaf nodes (Node 1, Node 10, Node 5, Node7).
Node at distance K that is Node at distance 1 from leaf Node 1 is Node 2 (Print 2)
Node at distance K that is Node at distance 1 from leaf Node 10 is Node 9 (Print 9)
Node at distance K that is Node at distance 1 from leaf Node 5 is Node 6 (Print 6)
Node at distance K that is Node at distance 1 from leaf Node 7 is Node 6 (6 already printed, ignore)

## Print Nodes at K distance from Root in Binary Tree

### Print nodes at K distance from root in binary tree. ORPrint nodes at Level K.

Given a Binary Tree, Print all Nodes that are at K distance from root node in Binary Tree. We can also think of this question as Print all nodes that belong to Level K.

Lets understand what will be input and expected output with the help of an example.

If k = 2. It means we need to print all nodes that are at distance 2 from Root node.
It also means we need to print all nodes at Level 2, because all Nodes of Level 2 will be at same distance from Root Node.

## Rotate matrix by 90 degree

Rotate matrix by 90 degree OR
Turn an 2D array by 90 degree OR

Rotate a two dimensional array OR
Given N*M matrix, rotate it by 90 degree to left and right.

Given N*M Matrix, Rotate it by 90 degrees.

Lets understand the problem statement graphically and it will be more clear,

## Rotate Matrix by 90 degrees clockwise Inplace

Rotate square matrix by 90 degrees Inplace OR
Turn an 2D array by 90 degree OR

Rotate a two dimensional array OR
Given N*N matrix, rotate it by 90 degree to left and right without extra memory

Rotate square matrix by 90 degrees Inplace.
Lets understand the problem statement graphically and it will be more clear,

## Print Matrix in Spiral order using Recursion.

Print Matrix in Spiral order OR
Given m*n matrix(m rows, n columns), print all elements of the matrix in spiral order OR

Print two-dimensional array in spiral order OR
How to print elements of Matrix in Spiral Format?

Given a Matrix(2D array), print it in spiral form. Lets understand the problem statement graphically and it will be more clear,

## Print Matrix in Spiral form

Print Matrix in Spiral order OR
Given m*n matrix(m rows, n columns), print all elements of the matrix in spiral order OR

Print two-dimensional array in spiral order OR
How to print elements of Matrix in Spiral Format?

Given a Matrix(2D array), print it in spiral form. Lets understand the problem statement graphically and it will be more clear,

## Transpose of Matrix Inplace

Transpose of Matrix In-place

You are given a M * N matrix, find Transpose of Matrix in-place. Transpose of matrix is obtained by interchanging rows and columns of a matrix that is by changing rows to columns and columns to rows.

Lets understand the problem statement graphically and it will be more clear,

## Transpose of Matrix in Java

Transpose of Matrix in Java

You are given a M * N matrix, find Transpose of Matrix. Transpose of matrix is obtained by interchanging rows and columns of a matrix that is by changing rows to columns and columns to rows.

Lets understand the problem statement graphically and it will be more clear,

## Implement Queue using One Stack in Java (Recursive Implementation)

Implement Queue using One Stack in Java

You are given a Stack data structure that supports standard push and pop operations. You need to implement Queue data structure using one Stack instances.

Lets understand the problem statement graphically and it will be more clear,

## Implement Queue using Stack

Implement Queue using Stack in Java

You are given a Stack data structure that supports standard push and pop operations. You need to implement Queue data structure using Stack instances.

Lets understand the problem statement graphically and it will be more clear,

Many a times we need to download file via POST request, because the request contains extra parameters to pass and GET request is not suitable. Lets see example of downloading ZIP file via POST request.

Once I have faced requirement of downloading binary zip file using AngularJS + REST service and thought of sharing the code, It may help to someone facing similar requirement.

## Burning Rope Puzzle - Measure 45 Minutes

The Burning Rope Puzzle

You have 2 ropes. Each takes exactly 60 minutes to burn. They are made of different material so even though they take the same amount of time to burn, they burn at separate rates.
In addition, each rope burns inconsistently. How do you measure out exactly 45 minutes?

Both ropes burn at different rate , So how to calculate 45 minutes?

Lets understand the problem statement graphically and it will be more clear,

## Implement Stack using One Queue

Implement Stack using Single Queue in Java

You are given a Queue data structure that supports standard enQueue and deQueue operations.  You need to implement Stack data structure using Single Queue.

Lets understand the problem statement graphically and it will be more clear,

## Implement Stack using Queue

Implement Stack using Queue in Java

You are given a Queue data structure that supports standard enQueue and deQueue operations.
You need to implement Stack data structure using Queue instances.

Lets understand the problem statement graphically and it will be more clear,

## Find Smallest and Second smallest element in array.

Find Smallest and Second smallest number in array.

Given a integer array, find smallest and second smallest number in array. Lets understand the problem statement graphically and it will be more clear,

## Find Largest and Second Largest number in array

Find Largest and Second Largest number in array

Given a integer array, find largest and second largest number in array. Lets understand the problem statement graphically and it will be more clear,

## Find Largest and Second Largest number in array and Find Smallest and Second Smallest number in array

Find Largest and Second Largest number in array OR Find the smallest and second smallest element in array.

Given a integer array, find largest and second largest number in array. Lets understand the problem statement graphically and it will be more clear,

## Find Largest and Smallest number in Array

Find minimum and maximum number in array

Given a integer array, find minimum and maximum number in array. Lets understand the problem statement graphically and it will be more clear,

## Count zeros in a row wise and column wise sorted matrix

Count zeros in sorted matrix

Count zeros in a row wise and column wise sorted matrix Lets understand the problem statement graphically and it will be more clear,

## Search in a row wise and column wise sorted matrix

Find number in sorted matrix

Given an n x n matrix, where every row and column is sorted in increasing order.  Given a number k, how to decide whether this k is in the matrix. OR Search number in a row wise and column wise sorted matrix.

Lets understand the problem statement graphically and it will be more clear,

## Find middle element of a linked list

Find middle element of a linked list in Java

Lets understand the problem statement graphically and it will be more clear,

## Convert Sorted Linked List to balanced BST

Convert Sorted Linked list to balanced Binary Search Tree

Convert sorted list to binary search tree

Lets simplify the question statement, Given a singly Linked List where elements are sorted inascending orderconvert it to a height balanced BST.

A Binary Search Tree is called balanced if the height of left subtree and height of right subtree of Root differ by at most 1.

Lets understand the problem statement graphically and it will be more clear,

## Sorted Array to Balanced Binary Search Tree (BST)

Convert Sorted Array to Balanced Binary Search Tree

Given a sorted array, create a Balanced Binary Search Tree using array elements. A Binary Search Tree is called Balanced if, the height of left subtree and height of right subtree of Root differ by at most 1.

Lets understand the problem statement graphically and it will be more clear,

## Union and Intersection of Two Sorted Arrays

Union and Intersection of Two Sorted arrays

Given two sorted arrays of any length, Find Union and Intersection of given arrays.

Lets understand the problem statement graphically and it will be more clear,

## Merge two sorted arrays in Java

Merge two sorted arrays Java

Merge two sorted arrays in java.
Lets simplify problem statement, given two sorted arrays, you need to merge it in one array such that merged array should also be sorted.

Lets understand the problem statement graphically and it will be more clear,

## Clone linked list with next and random pointer

Clone linked list with next and random pointer

You are given a Doubly Link List with one pointer of each node pointing to the next node just like in a singly link list.The second pointer however can point to any node in the list and not just the previous node.

Lets understand the problem statement graphically and it will be more clear,

## Clone Linked list in Java

Lets understand the problem statement graphically and it will be more clear,

## Serialize and Deserialize a Binary Tree

Serialize and Deserialize a Binary Tree

Design an algorithm to serialize and deserialize given Binary Tree.  Serialization is to store tree in a File/String, so that it can be later restored.
Deserialization is reading tree back from file.

Lets understand the problem statement graphically and it will be more clear,

We need to Serialize given Binary Tree into String(So that we can write it to File or transfer it).
Also, we need to read the Serialized String and Deserialize it back to original Binary Tree.

## Trapping Rain Water between Towers

How Much Water Can A Bar Graph Hold

Given an bar graph, encoded as an array of non-negative integers, calculate the units of water that this bar graph can hold.

Let us put in technical terms,
Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining. Lets understand the problem statement graphically and it will be more clear,

Case 1:
Input     = [2, 0, 2]
Output  = 2

Case 2:
Input     = [3, 0, 0, 2, 0, 4]
Output  = 10

Case 3:

Input     = [0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1]
Output  =  6

## How ConcurrentHashMap works and ConcurrentHashMap interview questions.

ConcurrentHashMap Interview Questions In Java.

### Question 1. What is the need of ConcurrentHashMap when there is HashMap and Hashtable already present?

Performance and Thread safety are 2 parameter on which ConcurrentHashMap is focused. Imagine a scenario where we have frequent reads(get) and less writes(put) and need thread safety,

Can we use Hashtable in this scenario?
No. Hashtable is thread safe but give poor performance in case of multiple thread reading from hashtable because all methods of Hashtable including get() method is synchronized and due to which invokation to any method has to wait until any other thread working on hashtable complete its operation(get, put etc).

Can we use HashMap in this scenario?
But Hashmap is not thread safe, so what will happen if one thread tries to put data and requires Rehashing and at same time other thread tries to read data from hashmap, It will go in infinite loop.

Infinite loop problem discussed in detail: Infinite loop in HashMap

ConcurrentHashMap combines good features of hashmap and hashtable and solves performance and thread safety problem nicely.

### Question 2. HashMap and Hashtable uses Array and Linkedlist as datastructure to store data, How is it different in ConcurrentHashMap?

If you are not familiar with HashMap and Hashtable, Please go through it first:
How HashMap works

Below diagram shows how hashtable/hashmap look like,

ConcurrentHashMap added one Array on top of it and each index of this additional array represents complete HashMap. Additional array is called Segment in ConcurrentHashMap.

Architecture of ConcurrentHashMap looks like below,

Putting key-value pair:

1. Putting key-value pair in ConcurrentHashMap requires first identifying exact index in
Segment array.
(Once Segment array index is identified, Now flow will be exactly same as putting the data in
hashmap/hashtable.)
2. After identifying index in Segment array, next task is to identify index of internal bucket/array
present in internal hashmap as shown in figure above.
3. After identying bucket(internal array index), iterate key-value pairs and check each key with key
to store, wherever match is found replace stored value with value to store.
If there is no match, store key-value pair at the last of list.

Getting key-value pair:

1. Getting key-value pair in ConcurrentHashMap requires first identifying exact index in
Segment array.
(Once Segment array index is identified, Now flow will be exactly same as getting the data from
hashmap/hashtable.)
2. After identifying index in Segment array, next task is to identify index of internal bucket/array
present in internal hashmap as shown in figure above.
3. After identying bucket(internal array index), iterate key-value pairs and match each key with
given key, wherever match is found return value stored against key.
If there is no match, return null.

### Question 3. How ConcurrentHashMap is efficient in terms of Performance and Thread safety?

ConcurrentHashMap provides better Performance by replacing the Hashtable's map wide lock to Segment level lock.

Hashtable is not efficient beacause it uses map wide lock, it means lock is applied on map object itself,

So if 2 threads tries to call hashtable.get(key),
Thread T1 calls to get() method will acquire a lock on hashtable object and then execute get() method. (Lock is on complete 'hashtable object')

Now if Thread T2 calls hashtable.get(key) method, then it will also try to acquire lock on hashtable object, but T2 will not able to acquire lock as lock on 'hashtable' is currently held by T1,

So T2 waits until T1 finishes get() operation and release lock on hashtable object.

ConcurrentHashMap works bit different here and instead of locking complete map object it Locks per Segment.
It means instead of single map wide lock, it has multiple Segment level lock.

So 2 Threads can execute put operation simultaneously by acquiring lock on different Segments.

Thread T1 calls concurrentHashMap.put(key, value), It acquires lock on say Segment 1 and invokes put method.
Thread T2 calls concurrentHashMap.put(key, value), It acquires lock on say Segment 4 and invokes put method.

Both threads doesn't interfere with each other and both can proceed simultaneously as they are working on separate Segment locks.

This is how ConcurrentHashMap improves Performance and provide Thread safety as well.

### Question 4. Can multiple threads read and write from same or different Segments of ConcurrentHashMap simultaneously?

Same Segment/Different Segment : Yes.
Two threads T1 and T2 both can simultaneously read data from same Segment or different Segment of CHM simultaneously without blocking each other.

Write Operation: put(key, value)
Different Segment :Yes
Multiple threads can write data to different Segment of CHM simultaneously without blocking each other.
Same Segment : No
Multiple threads CANNOT write data to same Segment of CHM simultaneously and need to wait for one thread to come write operation and then only other write operation can be proceed.

Say T1 is writing data in Segment 1 and T2 is reading data from same Segment 1, can read be allowed while writing operation is going on?
YES.
Both operation that is T1 writing and T2 reading can be done parallely

What data will T2 read if T1 is updating same data?
Retrieval operations (including get) generally do not block, so may overlap with update operations (including put and remove).
Latest updated value present will be returned by get operation that is value updated by most recently completed update operationswill be returned.

Note: Get operations are lock free and can be performed simulateneously irrespective of other thread writing data on same or different Segment of CHM.

### Question 5. What is the default size of Segment array? how it is tuned? What is ConcurrenyLevel in case of CHM?

Default size of Segment array is 16.

ConcurrentHashMap differes from Hashtable in terms of Performance by introducing Segment array.
Each index of Segment array is guarded by a lock for put operation.

Threads working on separate Segments index doesn't affect each other.
By default Segments array size is 16, So maximum 16 threads can simultaneously put data in map considering each thread is working on separate Segment array index.

### How Segment array size is tuned?

Segment size decides the number of Threads that can paralley write to a map.
Segment array size is configured using ConcurrencyLevel parameter as shown below,
`ConcurrentHashMap m = new ConcurrentHashMap(initialCapacity, loadFactor, concurrencyLevel)`

It takes 3 parameters,

Example:
`ConcurrentHashMap m = new ConcurrentHashMap(200 , 0.75f, 10);`
Initial capacity is 200, it means CHM make sure it has space for adding 200 key-value pairs after creation.

Load factor is 0.75, it means when average number of elements per map exceeds 150 (intital capacity * load factor = 200 * 0.75 = 150) at that time map size will be increased and existing items in map are rehashed to put in new larger size map.

Concurrency level is 10, it means at any given point of time Segment array size will be 10 or greater than 10, so that 10 threads can able to parallely write to a map.

### Question 6. What will happen if the size of Segment array is too small or too large?

Choosing correct ConcurrencyLevel is very important because ConcurrencyLevel decides what will be the size of Segment array.

Segment array size will decide how many parallel Threads will be able to execute put operation on map parallely.

So Segment array size should not be too big or should not be too small because,
Using a significantly higher value than we will waste space and time, and a significantly lower value can lead to thread competition.

### Question 6. If we choose ConcurrenyLevel as 10 then what will be size of Segment array? Is Segment array size exactly same as concurrenyLevel? If No, then how is the Segment array size calculated?

Segment array size is calculated based on concurrenyLevel specified but it doesn't mean it will be exactly same as concurrenyLevel.

If concurrenyLevel is 10 then Segment array size will be 16.

Segment array size = 2 to the power x, where result should be >= concurrenyLevel(in our case it is 10)
Segment array size = 2 to the power x >= 10

Segment array size = 2 ^ 1 = 2   >= 10 (False)
Segment array size = 2 ^ 2 = 4   >= 10 (False)
Segment array size = 2 ^ 3 = 8   >= 10 (False)
Segment array size = 2 ^ 4 = 16 >= 10 (True)

Segment array size is 16.

Example: 2
concurrenyLevel = 8 then Segment array size = ?
Find 2 ^ x >= 8

2 ^ 1 >= 2
2 ^ 2 >= 4
2 ^ 3 >= 8
Segment array size will be 8.

### Question 7. What is HashEntry array and how is the size of HashEntry decided?

Default initial capacity of CHM is 16. It means CHM make sure there is sufficient space to accomodate 16 key-value pairs after CHM is created.

What is HashEntry[]?

We saw that each index of Segment array itself is complete HashMap,

In HashMap the bucket/array is of class Entry[] and in CHM the array is of class HashEntry[].

```static final class Segment<K,V> extends ReentrantLock implements Serializable {
transient volatile HashEntry<K,V>[] table;
}

static final class HashEntry<K,V> {
final int hash;
final K key;
volatile V value;
volatile HashEntry<K,V> next;
}

```

Lets see how internal architecture of CHM looks like,

How HashEntry[] array size will is calculated?
`ConcurrentHashMap m = new ConcurrentHashMap(initialCapacity, loadFactor, concurrencyLevel)`

HashEntry[] array size  =   2 ^ x   >=  (initialCapacity / concurrenyLevel)

Eg: ConcurrentHashMap(32,   0.75f,   4);
HashEntry[] array size  =  2 ^ 1 = 2   >=  8(32/4) (False)
HashEntry[] array size  =  2 ^ 2 = 4   >=  8 (False)
HashEntry[] array size  =  2 ^ 3 = 8   >=  8 (True)

HashEntry[] array size = 8
It means there will always be capacity of 8 key-value pairs that can be put in CHM after its creation.

### Question 8. How does ConcurrentHashMap handle rehashing while another thread is still writing on another segment/partition?

Load Factor is a measure, which decides when exactly to increase the HashMap/CHM capacity(buckets) to maintain get and put operation complexity of O(1).

Default load factor of Hashmap/CHM is 0.75f (i.e 75% of current map size).

In CHM, Every segment is separately rehashed so there is no collision between Thread 1 writing to Segment index 2 and Thread 2 writing to Segment index 5.

Example: If say Thread 1 which is putting data in Segment[] array index 2 finds that HashEntry[] array needs to be rehashed due to exceed Load factor capacity then it will rehash HashEntry[] array present at Segment[] array index 2 only.
HashEntry[] array at other Segment indexes will still be intact, unaffected and continue to serve put and get request parallely.

MORE QUESTIONS COMING SOON...

### You may also like to see

#### How is ambiguous overloaded method call resolved in java

Enjoy !!!!

If you find any issue in post or face any error while implementing, Please comment.

## Java Interface interview questions and answers

### Question 1. Super class of all classes is java.lang.Object class, does this applies to Interface as well? What is super class of all Interface in Java?

java.lang.Object class is the super class of all Java classes. All non-primitive types (including arrays) inherit either directly or indirectly from Object class.
For Interface that is not the case, Super class of Interface is null.

From below program that will be clear.

```interface ITest{}
class CTest{}

class Test{
public static void main(String[] args) {
System.out.println(CTest.class.getSuperclass()); // class java.lang.Object
System.out.println(int[].class.getSuperclass()); // class java.lang.Object
System.out.println(ITest.class.getSuperclass()); // null
System.out.println(int.class.getSuperclass());   // null
}
}
```
Output:
class java.lang.Object
class java.lang.Object
null
null

## The Knapsack Problem

### 0/1 Knapsack Problem solved using Iterative and Dynamic Programming

Given weights and values(profits) of N items, put these items in a knapsack of max capacity W to get the maximum total value(profit) in the knapsack.

### Question 1. What is the use of Threads in Java? why Thread is required? What are Threads in Java?

Lets try to understand this with simple scenario and it will be more clear:

Scenario:
Suppose you want to count the population of a India, how will you approach?
Note: There are 29 states in India.

Approach 1:
First approach is, you start with first state and count population of that state then you will start second state and so on for all 29 states.
Once you have population of all the states, just sum the population count of all States.

Imagine the time it will take for you to do this as you are alone and you have to count population state by state.

Approach 2:
Second approach is, you called 29 people to help you out and you distributed the task of population count to 29 person, each person taking care of individual state.
So, person 1 will take care of population count for State 1.
Person 2 will take care of population count for State 2 and so on.

Once you have population count of all the states, just sum the population count received from all 29 person.

Imagine the time it will take for you to do this as compared to Approach 1, surely it will be much less.

So that is what Thread does. In above scenario, you can consider 29 persons as 29 Threads who are doing their respective task of population count.
It is possible that Person 1 may finish population count for State 1 assigned to it much early than Person 2 doing population count for State 2 because State 1 was small.
Person 2 will continue doing his task even after Person 1 finished early.

In the similar way, Say If you have 2 Threads say Thread 1 and Thread 2. Thread 1 may complete its job early and Thread 2 will continue doing its job even after Thread 1 is done and they both execute separately.

Now to relate it with Threads:
When you have task like above that needs to be run in parallel for faster processing at that time Threading will come in picture.
You can say, Java Threads helps creating multiple independent path of execution within a program which can run parallely.
Application Example:
In Java, when a program requires more than one task to execute in parallel, say for example,
1. Reading a data from a local file.
2. Reading a data from remote connection.
When both of above task need to be executed in parallel at that time Threading will come in picture.
So Java Threads helps creating multiple independent path of execution within a program which can run in parallel.

## Method Overriding Rules In Java

### What is Method Overriding?

In case of Inheritance, where Parent-child relationship exist,
Parent class define a method say connect() which does connection to some remote service.
Child class has better way to do connection than Parent class and don't want to use Parent class connect() method, So it overrides Parent's class connect() method by providing own implementation of connect() method,  Now whenever connect() method is called using Child class object, then connect() method of Child class will be called and not the connect() method of Parent/Super class, this concept is called Method overriding.

Example of Method Overriding:
```class Parent{
public void connect(){
System.out.println("Doing connection in Parent way");
}
}

class Child extends Parent {
@Override
public void connect() {
System.out.println("Doing connection in Child way");
}
}
```

### Rules of Method Overriding

Parameters that need to be consider in case of Method Overriding,
1. Access Specifier of method
2. Return Type of method
3. Name of method
4. Arguments/Parameters of method
5. Exception that method throws.

Access Specifier of method
Overriding method in Child class can either have same access specifier as that of Parent class method or can increase visibility but cannot decrease it.

If Parent class method is declared as,
```protected void connect(){}
```
then valid access specifier for Child class overriding method connect() is,
```public void connect(){} OR
protected void connect(){}```

Return Type of method:
Overriding method in Child class can either have same return type or should be Subclass of return type declared in method of Super class.

If Parent class method is declared as,
```protected Number connect(){}
```

then valid Return type for overriding connect() method in Child class is either Number class or all subclass of Number class,
```public Integer connect(){}
protected Long connect(){}
protected Number connect(){}```

Name of method:
Name of the overriding method in Child class must be exactly same as that of method declared in Parent Class

Arguments/Parameters of method:
Total number and Type of arguments present in overriding Child class method must be exactly same as that of Parent class method.

Note:
Arguments present in Child class method should be exactly of same type (Subclass will not work) as that of Parent class method.
Why Subclass argument won't work, Let's understand it with below example,
```class A1{}
class A2 extends A1{}
class A3 extends A1{}

class Parent{
protected Number connect(A1 a1){
System.out.println("Doing connection in Parent way");
return null;
}
}

class Child extends Parent {
@Override
public Long connect(A2 a2) {
System.out.println("Doing connection in Child way");
return null;
}
}
```
In above example,
Super class connect method take generic agument A1.
Child class overriding connect method take specific agument A2

If Covariant parameters are allowed in Method overriding than what will be output of below lines,
```Parent p = new Child();
p.connect(new A3());
```

Above line will call connect() method of Child class method due to Polymorphic behaviour. Also, According to Parent class method definition it should work but according to Child class overriding definition it will not work.

This problem occurred because Child class overriding method accepted specific(Subclass) argument compared to Parent class method which is accepting generic argument.

To avoid this situation, parameter in overriding method must be exactly same.

Exception that method throws:

Unchecked Exception:
Overriding method in Child class can throw any number of Unchecked Exception irrespective of Parent class overriden method has declared any Checked/Unchecked Exception or not.
Below example shows valid overriden method connect() and connect1().
```class Parent{
protected Object connect(String s1) {
System.out.println("Doing connection in Parent way");
return null;
}

protected Object connect1(String s1) throws NullPointerException{
System.out.println("Doing connection in Parent way");
return null;
}
}

class Child extends Parent {
@Override
public Integer connect(String s2) throws RuntimeException, NullPointerException{
System.out.println("Doing connection in Child way");
return null;
}

@Override
protected Object connect1(String s1) throws RuntimeException{
System.out.println("Doing connection in Parent way");
return null;
}

public static void main(String[] args) {
Parent p = new Child();
p.connect("hello");
}
}

```

Checked Exception:
If say Overriden method of Parent class throws IOException, then overriding method in Child class can either throw
1. No Exception,
2. Same IOException,
3. Any number of Subclass of IOException like FileNotFoundException, EOFException etc.

Not Allowed:
If say Overriden method of Parent class throws IOException, then overriding method in Child class cannot throw
1. It cannot throw exception from totally new inheritance hierarchy like SQLException.
2. It cannot throw broader exception like Throwable or Exception in our case.

Conclusion:
Overriding method of Child class can throw any number of Unchecked Exception irrespective of Overriden method of Super class throwing or not throwing any exception.

If Super class overriden method throws Cheked Exception then Overriding method of Child class can either choose not to throw any exception, or throws same exception or throws any number of subclass of Exception thrown by overriden method

Lets see few example and understand:
```class Parent{
protected Object connect(String s1) {
System.out.println("Doing connection in Parent way");
return null;
}

protected Object connect1(String s1) throws Exception{
System.out.println("Doing connection in Parent way");
return null;
}

protected Object connect2(String s1) throws IOException, SQLException{
System.out.println("Doing connection in Parent way");
return null;
}

protected Object connect3(String s1) throws IOException{
System.out.println("Doing connection in Parent way");
return null;
}

protected Object connect4(String s1){
System.out.println("Doing connection in Parent way");
return null;
}

}

class Child extends Parent {
@Override
public Integer connect(String s2){ //It will work
System.out.println("Doing connection in Child way");
return null;
}

protected Object connect1(String s1) throws Exception, FileNotFoundException, MalformedURLException{ //It will work
System.out.println("Doing connection in Child way");
return null;
}

protected Object connect2(String s1) throws FileNotFoundException{ //It will work
System.out.println("Doing connection in Child way");
return null;
}

protected Object connect3(String s1) throws Exception{ //It will NOT work
System.out.println("Doing connection in Child way");
return null;
}

protected Object connect4(String s1) throws Exception{ //It will NOT work
System.out.println("Doing connection in Child way");
return null;
}

public static void main(String[] args) {
Parent p = new Child();
p.connect("hello");
}
}

```

In case if you like to try program using different Exception hierarchy, here is Exception hierarchy tree.

### You may also like to see

#### Interface interview questions and answers in Java

Enjoy !!!!

If you find any issue in post or face any error while implementing, Please comment.

## Find the number of Islands using DFS.

### Count total number of Islands ORThe "Island Count" Problem

Given a Ocean in a form of 2D matrix as shown below in which there are few Island present
(or may not be present).

In a matrix given above, which has only two values ‘1’ and ‘0’.
1 represents land and
0 represents water,
Find the total number of Islands.

Lets understand what is the input and the expected output with few samples.

Sample 1:
Input:
int[][] island = new int[][] {
{ 1, 1, 0, 0, 0 },
{ 0, 1, 0, 0, 1 },
{ 1, 0, 0, 1, 1 },
{ 0, 0, 0, 0, 0 },
{ 1, 0, 1, 0, 1 }
};
Output: 5

Sample 2:
Input:
int[][] island = new int[][] {
{0, 0, 0, 0, 0 },
{0, 0, 0, 0, 0 },
{0, 0, 0, 0, 0 },
{0, 0, 0, 0, 0 },
{0, 0, 0, 0, 0 }
};

Output:0

Sample 3:
Input:
int[][] island = new int[][] {
{ 1, 0, 0, 0, 0 },
{ 0, 1, 0, 0, 0 },
{ 0, 0, 1, 0, 0 },
{ 0, 0, 0, 0, 0 },
{ 1, 1, 1, 0, 0 }
};

Output:2