Method Overloading Interview Questions in Java

How compiler resolves ambiguous method overloading call. OR
Which overloaded method will get selected for null parameter in java. OR
Important Java Interview Questions On Method Overloading OR
Method Overloading Tutorial


Method Overloading Interview Questions in Java. Can we overload static method in Java. Method overloading Java rules.

What is method overloading?

If a class have multiple methods with same name but with different parameters list, it is known as Method Overloading. Parameters lists should differ in either,
  1. Number of parameters.
  2. Data type of parameters.
  3. Sequence of data type of parameters. 

Types of Binary Tree.

Types of Binary Tree.


Types of Binary Tree in Data Structure. Let's see Binary Tree types with example. There are mainly 3 types of Binary trees.

  1. Full binary tree / Proper binary tree / 2-tree / Strictly binary tree) 
  2. Perfect Binary Tree. 
  3. Complete Binary Tree:

Print Linked List In Reverse Order in Java

Print Linked List In Reverse Order in Java.


Print linked list in reverse order in java. print singly linked list in reverse order using recursion. java program to print linked list in reverse.

Let's understand the problem statement in simple words, 
You are given a Singly linked list, print the linked list in reverse way, from end to start.

Example: 
Input:     10 -> 20 -> 30 -> 40 -> 50 -> null
Output:  50      40     30      20      10
 


Find Minimum length Unsorted Subarray, Sorting which makes the complete array sorted.

Find Minimum length Unsorted Subarray, Sorting which makes the complete array sorted.


Find minimum unsorted subarray index m and n such that if you sort elements from m through n, then complete array would be sorted.

Let's understand the problem statement in simple words, 
Given an array of partially sorted integers, you have to find start index 'm' from where mismatch started that is the point from which array is not in sorted order,  and you have to find index 'n' till which index array is unsorted, and if you sort elements m through n, then entire array would be sorted.
 

Let's see example to understand what is the input and expected output.



Count trailing zeros in factorial of a number.

Count trailing zeros in factorial of a number.


Count trailing zeros in factorial of a number. there are many ways to count trailing 0 in factorial of number. Java program to count trailing zero.

What is Trailing Zero in a number?
Trailing zeros are a sequence of 0 in the decimal representation of a number, after which no other digits follow.

Example: 5! = 120
Number of Trailing Zero = 1

Example: 7! = 5040
Number of Trailing Zero = 1

Example: 10! = 3628800
Number of Trailing Zero = 2

Below you can get Factorial of number till 20 for testing Trailing Zeros in java program.

Swap two numbers In Java without using third variable.

Swap two numbers In Java without using third variable.


Swap two numbers In Java without using third variable. Write a program to swap/exchange 2 numbers without using temporary or third variable.

There are many approaches to solve this problem, we will see all of them one by one.


BFS vs DFS with Example in Java

BFS vs DFS with Example


Breadth First Search(BFS) Vs Depth First Search(DFS) with example in Java. DFS uses Stack while BFS uses Queue.

Given two words, startWord and endWord, and a dictionary, find the length of shortest transformation sequence from startWord to endWord.
Rules:

1. Only one letter can be changed at a time.
2. Each intermediate word must exist in the dictionary.

Input
startWord     = CAT
endWord      = DOG
dictionary    = CAT, BAT, COT, COG, COW, RAT, BUT, CUT, DOG, WEB 


Output

One shortest transformation is CAT –> COT –> COG –> DOG.
the program should return Path and its length 4.


Let's look at few more example and better understand problem statement.

There can be many paths for reaching from startWord to endWord, but we have to find shortest path possible.

Can static method be called using object in java

Java Interview Questions


Can static method be called using object in java. Static methods are called by Class name. Static members belongs to class.

Java interview questions and answers focused on "Method overriding and Method hiding".
There are interview questions on other topics like Multithreading, Exception Handling, Type Casting, Ambiguous Overloaded methods etc with detailed explanation on each question.

You will get link of all articles at bottom of this post.

Can we override static methods in java. Explain with example.

Can we override static methods in java. Explain with example.


Can we override static methods in java. Static methods cannot be overridden because Static methods are not polymorphic in nature.

 
Java interview questions and answers focused on "Method overriding and Method hiding". 

There are interview questions on other topics like Multithreading, Exception Handling, Type Casting, Ambiguous Overloaded methods etc with detailed explanation on each question.

You will get link of all articles at bottom of this post.

Method overriding and Method hiding Interview Question in Java

Method overriding and Method hiding Interview Question in Java


Method overriding and Method hiding Interview Question in Java. Can we Override static methods in java? What is method hiding in Java?  
 
Java interview questions and answers focused on "Method overriding and Method hiding".
There are interview questions on other topics like Multithreading, Exception Handling, Type Casting, Ambiguous Overloaded methods etc with detailed explanation on each question.

You will get link of all articles at bottom of this post.

Factorial of number in Java

Factorial of number in Java.


Factorial of number in Java. Factorial of number is product of a number and all number below it. Example: 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.

Reverse String in Java.

How to Reverse String in Java.


Reverse String in Java. String can be reversed using Iterative and Recursive approach. We will Reverse a String using Recursion and using loop. For reversing a String we should not use any inbuilt methods.

Input:      "Reverse String"
Output:   "gnirtS esreveR"

Input:      "HELLO"
Output:   "OLLEH"

Input:      "123 abc"
Output:   "cba 321"

When to use SOAP over REST Web Service. Is REST better than SOAP?

When to use SOAP over REST Web Service.
Is REST service better than SOAP service?
Difference between SOAP and REST Web Service. OR
SOAP Vs REST Web Service.


When to use SOAP over REST Web Service. Is REST service better than SOAP service. Benefits of SOAP over REST service. 

Let's see, important difference between SOAP and REST Service which will help you decide which to choose among both.


How Floyd's Cycle finding algorithm work

How floyd's cycle-finding algorithm work.


How floyd's cycle finding algorithm work in java. Floyd's cycle finding algorithm helps to detect and remove loop in linked list.

What is Loop in Linked list?

Generally, the last node of the linked list points to NULL, which is a indication of end of list.
But in Linked list containing Loop, last node instead of pointing NULL, it points to some of the internal node/starting node/itself.
In this case, If we traverse the Linked list node one by one, our traversal will never ends as it goes in loop.

Check below images for better understanding on how Linked list containing loop looks like.



Find start node of loop in linked list in Java

Identify start node of loop in Linked list.


Find start node of loop in linked list in Java. For identifying start node of cycle in Circular linked list, first detect loop in linked list.
 
Let's begin with, What is Loop in Linked list?

Generally, the last node of the linked list points to NULL, which is a indication of end of list.
But in Linked list containing Loop, last node instead of pointing NULL, it points to some of the internal node/starting node/itself.
In this case, If we traverse the Linked list node one by one, our traversal will never ends as it goes in loop.

Check below images for better understanding on how Linked list containing loop looks like.



Floyd's Cycle Detection Algorithm in Java

Floyd's Cycle Detection Algorithm in Java. OR
Detect loop in Linked list.


Floyd's Cycle Detection Algorithm in Java. Floyd's Cycle finding algorithm helps to detect loop  in linked list. How Floyd's Cycle Algorithm works.
 

Let's start with, What is Loop in Linked list?

Generally, the last node of the linked list points to NULL, which is a indication of end of list.
But in Linked list containing Loop, last node instead of pointing NULL, it points to some of the internal node/starting node/itself.
In this case, If we traverse the Linked list node one by one, our traversal will never ends as it goes in loop.

Check below images for better understanding on how Linked list containing loop looks like.



Find a Loop in Singly Linked List

Detect loop in Linked list.
Find Cycle in Linked list.
Identify start node of loop in Linked list.
Remove loop in Linked list.


Find a Loop in Linked List. To Detect cycle in linked list is popular interview question. Java Program to Detect loop in linked list in Java.

What is Loop in Linked list?

Generally, the last node of the linked list points to NULL, which is a indication of end of list.
But in Linked list containing Loop, last node instead of pointing NULL, it points to some of the internal node/starting node/itself.
In this case, If we traverse the Linked list node one by one, our traversal will never ends as it goes in loop.

Check below images for better understanding on how Linked list containing loop looks like.



Remove loop from Linked list in Java

Remove loop in Linked list.


Remove loop from Linked list in Java. Given a linked list, detect and remove loop in Linked list? Java Program to remove loop in linked list.

Remove loop in Linked list.


Removing the loop in Linked list is simple,

After identifying the loop node, we just require the previous node of loop node, So that we can set it to NULL.

For identifying the previous node of loop node, we will keep the previousPointer pointing to just previous node of loop node.

CASE 2:
When the meeting node of both pointers in loop is start node or root node itself, in this case by just setting previousPointer to NULL will work because previousPointer is already pointing to last node of the linked list.

CASE 1:
When the meeting node of both pointers in loop is in-between the linked list, in this case, first task is to identify the start of loop node in the way as we saw above and then by setting fastPointer, which is already pointing to last node of list to NULL will work.

Program to Remove loop in linked list.


package linkedlist.singly;

public class RemoveLoopInLinkList {
 
 Node startNode;
 public static void main(String[] args) {
  RemoveLoopInLinkList g = new RemoveLoopInLinkList();
  
  Node n1 = new Node(10);
  Node n2 = new Node(20);
  Node n3 = new Node(30);
  Node n4 = new Node(40);
  Node n5 = new Node(50);
  Node n6 = new Node(60);
  Node n7 = new Node(70);
  Node n8 = new Node(80);
  
  g.startNode = n1;
  
  n1.setNext(n2);
  n2.setNext(n3);
  n3.setNext(n4);
  n4.setNext(n5);
  n5.setNext(n6);
  n6.setNext(n7);
  n7.setNext(n8);
  n8.setNext(n6);
  
  //Detect and Remove Loop in a Linked List
  Node newStart = detectAndRemoveLoopInLinkedList(g.startNode);
  g.printList(newStart);
 }
 
 private static Node detectAndRemoveLoopInLinkedList(Node startNode) {
  Node slowPointer=startNode;
  Node fastPointer=startNode;
  Node previousPointer=null;
  
  while(fastPointer!=null && fastPointer.getNext()!=null){
   slowPointer = slowPointer.getNext();
   previousPointer = fastPointer.getNext(); // For capturing just previous node of loop node for setting it to null for breaking loop.
   fastPointer = fastPointer.getNext().getNext();
   
   if(slowPointer==fastPointer){ // Loop identified.
    slowPointer = startNode;
 
    //If loop start node is starting at the root Node, then we slowpointer, fastpointer and head all point at same location. 
    //we already capture previous node, just setting it to null will work in this case.
    if(slowPointer == fastPointer){
     previousPointer.setNext(null);
     
    }else{
     // We need to first identify the start of loop node and then by setting just previous node of loop node next to null.  
     while(slowPointer.getNext()!=fastPointer.getNext()){
      slowPointer = slowPointer.getNext();
      fastPointer = fastPointer.getNext();
     }
     fastPointer.setNext(null);
    }
   }
  }
  return startNode; 
 }
 
 //Print linked list.
 private void printList(Node startNode){
  while(startNode!=null){
   System.out.print(startNode.getData() + " " ); 
   startNode=startNode.getNext();
  }
 }
 
} 
 

Check below images for better understanding on how Linked list containing loop looks like. 



Check Number is Palindrome in Java Program

Java Program to Check Number is Palindrome.


Java Program to Check Number is Palindrome. Number is called Palindrome, if the reverse of number is equal to original number. Example: 12321, 545.

In this post, we will see Algorithm to check whether number is palindrome or not.


Java Program to check whether Number is Palindrome or not.


It is very easy to check whether Number is Palindrome or not.

Approach 1:

In this approach, 
STEP 1: Reverse the original number.
STEP 2: Check, whether original number and reversed number is same. If Yes, then number is
               Palindrome otherwise not


 Lets understand above algorithm step by step with below example.



Java Program to Check number is Palindrome or not.
package com.javabypatel;

public class PalindromeCheck {
 public static void main(String[] args) {
  palindromCheck(12321);
 }

 private static void palindromCheck(int number){
  if(number < 0){
   System.out.println("Invalid number");
   return;
  }

  int temp = number;

  int reverseNumber = 0;
  while(number > 0){
   int mod = number % 10; //Get last digit of number 
   reverseNumber = (reverseNumber * 10) + mod;  //Append Last digit got to reverseNumber.
   number = number/10; //Get the remaining number except last digit.
  }

  if(temp == reverseNumber){
   System.out.println("Number is Palindrome");
  }else{
   System.out.println("Number is not Palindrome");
  }
 }
}


Approach 2:

STEP 1: Convert the Number to String by using String.valueOf() method.
STEP 2: Reverse the String.
STEP 3: Compare Reversed String with String we got in STEP 1, if both are same then Number is 
              Palindrome else not.

package com.javabypatel;
class PalindromeCheck{  
 public static void main(String args[]){
  System.out.println(isPalindrome(12122));
 }  

 public static boolean isPalindrome(int number){
  if(number < 0){
   System.out.println("Invalid number");
   return false;
  }
  String originalString = String.valueOf(number);
  String reversedString = "";
  for (int i = originalString.length()-1; i >= 0; i--) {
   reversedString += originalString.charAt(i); 
  }

  return originalString.equals(reversedString);
 }
}
 


Approach 3:
In Approach 2, we reverse the whole String and then compared it with original string. 
In Approach 3, we will check whether string is palindrome without reversing original string and by comparing the characters of original string from both end that is from front and back together.

STEP: 1
Take 2 variable, pointer1 and pointer2. 
pointer1 initialise to index 0 and pointer2 initialise to originalString.length()-1.

STEP 2:
Compare characters at pointer1 and pointer2, if they are not same, then they are not Palindrome and stop. If they are same then increment pointer1, decrement pointer2.

STEP 3: Repeat STEP 2 til pointer1 < pointer2.
class PalindromeCheck{  
 public static void main(String args[]){
  System.out.println(isPalindrome(1221));
 }  

 public static boolean isPalindrome(int number){
  if(number < 0){
   System.out.println("Invalid number");
   return false;
  }
  String originalString = String.valueOf(number);
  
  int pointer1 = 0;
  int pointer2 = originalString.length()-1;
  
  while(pointer1 < pointer2) {
   if(originalString.charAt(pointer1) != originalString.charAt(pointer2)) {
    return false;
   }
   pointer1++;
   pointer2--;
  }
  return true;
  
 }
}


I hope below diagram wil help you understand algorithm in better way. 

You may also like to see




Enjoy !!!! 

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

SQL Injection attack example in Java.

Explain SQL Injection along with example?


SQL Injection attack with Example in Java. Let's see what is SQL Injection. How SQL Injection attack works. How to prevent SQL Injection. SQL Injection is code injection technique.

SQL Injection is code injection technique where SQL is injected by user (as part of user input) into the back end query. Injected SQL data alters the purpose of original query and upon execution can gives harmful result.  

A SQL injection attack is very dangerous and attacker can,
1. Read sensitive data from the database.
2. Update database data (Insert/Update/Delete).

3. Slowdown the complete Database system etc.


Analysis of Heap Sort Time Complexity.

Analysis of Heap Sort Time Complexity.


Analysis of Heap Sort Time Complexity. Heap sort worst case, best case and average case time complexity is guaranteed O(n Log n). Heap sort space complexity is O(1). 

 

Heap Sort Time Complexity


1. Heap sort has the best possible worst case running time complexity of O(n Log n).
2. It doesn't need any extra storage and that makes it good for situations where array size is large.


Before looking into Heap Sort, let's understand what is Heap and how it helps in sorting.

What is Complete Binary Tree?


A Complete binary tree is a binary tree in which every node other than the leaves has two children. In complete binary tree at every level, except possibly the last, is completely filled, and all nodes are as far left as possible. Let's understand with simple words now,
If a Binary Tree is filled level by level, left to right (Left child followed by Right child.) then it is called complete binary tree.
If Right child is present without Left child then it is not complete.



Analysis of Bubble Sort Time Complexity

Analysis of Bubble Sort Time Complexity.


Analysis of Bubble Sort Time Complexity. Bubble sort worst case time complexity is O(n^2), best case is O(n) and average case time complexity is O(n^2). Bubble Sort Java Program.

Time Complexity of Bubble Sort Algorithm.


1. Time complexity of Bubble sort in Worst Case is O(N^2), which makes it quite inefficient for 
    sorting large data volumes.
    O(N^2) because it sorts only one item in each iteration and in each iteration it has to compare n-i 
    elements.
2.
Time complexity of Bubble sort in Best Case is O(N)
    When the given data set is already sorted, in that case bubble sort can identify it in one single
    iteration hence O(N).
    It means while iteratng, from i=0 till arr.length, if there is no swapping required, then the array 
    is already sorted and stop there.
3. Bubble sort can identify when the list is sorted and can stop early.
4. Bubble sort is efficient for (quite) small data sets. 

5. It is Stable sort; i.e., does not change the relative order of elements with equal keys.
6. It takes O(1) extra space.


Let's see Bubble sort java program, How Bubble sort works in Java, Bubble sort Algorithm in java. 


Sort array using Bubble sort in Java.
Lets understand what is the input and the expected output.

Why Selection sort is faster than Bubble sort.

Why Selection sort is faster than Bubble sort.


Selection sort is faster than Bubble sort because Selection sort swaps elements "n" times in worst case, but Bubble sort swaps almost n*(n-1) times.

Why is Selection sort faster than Bubble sort?


Selection sort swaps elements "n" times in worst case, but Bubble sort swaps almost n*(n-1) times.

We all know, Reading time is less than writing time even in-memory. 

(Compare and running time can be ignored)

If we have a system where write operations are extremely expensive and read operations are not, then Selection sort could be ideal.
Selection sort is good for sorting arrays of small size.

Selection sort is better than Bubble sort due to less swapping required.

Note:
In Bubble sort, we can identify whether list is sorted or not in 1st iteration but in Selection sort we can't able to identify that.
Compared to Selection sort, Bubble sort should be used when the given array is almost sorted.


Selection sort Time Complexity Analysis


Selecting the lowest element requires scanning all n elements (this takes n - 1 comparisons) and then swapping it into the first position.
 

Finding the next lowest element requires scanning the remaining n - 1 elements and so on, 
= (n - 1) + (n - 2) + ... + 2 + 1 = n(n - 1) / 2 
= O(n^2) comparisons.

Best Case :       O(n)^2 
Worst Case :    O(n)^2 
Average Case : O(n)^2 
Worst Case Space Complexity : O(1) 

Stable : No

Bubble Sort Time Complexity Analysis


1. Time complexity of Bubble sort in Worst Case is O(N^2), which makes it quite inefficient for 
    sorting large data volumes.
    O(N^2) because it sorts only one item in each iteration and in each iteration it has to compare n-i 
    elements.
2.
Time complexity of Bubble sort in Best Case is O(N)
    When the given data set is already sorted, in that case bubble sort can identify it in one single
    iteration hence O(N).
    It means while iteratng, from i=0 till arr.length, if there is no swapping required, then the array 
    is already sorted and stop there.
3. Bubble sort can identify when the list is sorted and can stop early.
4. Bubble sort is efficient for (quite) small data sets. 

5. It is Stable sort; i.e., does not change the relative order of elements with equal keys.
6. It takes O(1) extra space.


You may also like to see


Merge Sort

Heap Sort

Bubble Sort

Insertion Sort

Enjoy !!!! 

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

Analysis of Selection Sort Time Complexity.

Analysis of Selection Sort Time Complexity.


Analysis of Selection Sort Time Complexity. Selection sort worst case, best case and average case time complexity is O(n^2). Selection Sort Java Program.

Selection sort Time Complexity Analysis


Selecting the lowest element requires scanning all n elements (this takes n - 1 comparisons) and then swapping it into the first position.
 

Finding the next lowest element requires scanning the remaining n - 1 elements and so on, 
= (n - 1) + (n - 2) + ... + 2 + 1 = n(n - 1) / 2 
= O(n^2) comparisons.

Best Case :       O(n)^2 
Worst Case :    O(n)^2 
Average Case : O(n)^2 
Worst Case Space Complexity : O(1) 

Stable : No


Let's start with Selection sort Java program, How Selection sort works in java, Selection sort Algorithm in java. 
 
Sort an array of integers using Selection sort in Java.
Lets understand what is the input and the expected output.
 

Analysis of Insertion Sort Time Complexity.

Time Complexity of Insertion Sort


Insertion sort worst case time complexity is O(n^2), Best case complexity is O(n), Average case complexity is O(n^2). Insertion sort is stable sort and in-place.

Analysis of Insertion Sort Time Complexity.


1. The insertion sort, unlike the other sorts, passes through the array only once. 
2. The insertion sort splits an array into two sub-arrays,

    First sub-array on left side is always sorted and increases in size as the sort continues.
    Second sub-array is unsorted, contains all the elements yet to be inserted into the first sub-array, 

    and decreases in size as the sort continues.

3. Insertion sort is efficient for (quite) small data sets.
4. It is more efficient than selection sort or bubble sort.
5. Insertion sort is very efficient for arrays which is nearly(almost) sorted and it sorts nearly sorted 

    array in time complexity of O(N).
    (For sorting an array containing elements in descending order to ascending order, insertion sort 

    will give poor performance and complexity will be O(N^2))

6. It is Stable sort; i.e., does not change the relative order of elements with equal keys.
7. It is In-place sort; i.e., only requires a constant amount O(1) of additional memory space
8. It can sort elements as it receives it and no need of complete data initially before start sorting.

    (Online).

Given a array of integers, Sort it using Insertion sort.  

Lets understand what is the input and the expected output.

Insertion Sort Algorithm in Java

Insertion Sort Algorithm in Java


Insertion sort is popular sorting algorithm. Let's see, how Insertion sort works and Insertion sort Java Program. Insertion sort works by shifting element at its correct position in array.

Given a array of integers, Sort it using Insertion sort.  

Lets understand what is the input and the expected output.

Check whether String is Palindrome or Not in Java.

Java Program to Check whether String is Palindrome or Not.


String is called Palindrome, if it is read same from front as well as from back.
In this post, we will see Algorithm to check whether string is palindrome or not.


Java Program to check whether String is Palindrome or not.


It is very easy to check whether String is Palindrome or not.

Approach 1:

Reverse the original string and compare Reversed String with original string.
If reversed string and original string is same then String is Palindrome else not.

class PalindromeCheck{  
 public static void main(String args[]){
  System.out.println(isPalindrome("ABCBA"));
 }  

 public static boolean isPalindrome(String originalString){
  if(originalString == null){
   return true;
  }
  
  String reversedString = "";
  for (int i = originalString.length()-1; i >= 0; i--) {
   reversedString += originalString.charAt(i); 
  }
  
  return originalString.equals(reversedString);
 }
} 


Approach 2: In this approach, we will check whether String is Palindrome or not by comparing the characters of string from front and back together.

STEP: 1
Take 2 variable, pointer1 and pointer2. 
pointer1 initialise to index 0 and pointer2 initialise to originalString.length()-1.

STEP 2:
Compare characters at pointer1 and pointer2, if they are not same, then they are not Palindrome and stop.
If they are same then increment pointer1, decrement pointer2.

Repeat STEP 2 til pointer1 < pointer2.


class PalindromeCheck{  
 public static void main(String args[]){
  System.out.println(isPalindrome("ABCBA"));
 }  

 public static boolean isPalindrome(String originalString){
  int pointer1 = originalString.length()-1;
  int pointer2=0;
  while(pointer1 > pointer2) {
   if(originalString.charAt(pointer1) != originalString.charAt(pointer2)) {
    return false;
   }
   pointer1--;
   pointer2++;
  }
  return true;
 }
} 


You may also like to see




Enjoy !!!! 

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

Java Program to Concatenate Strings in Java

Write a program to Concatenate Two Strings in Java.

There are many ways to Concat Strings in java. We will see 2 approach to concatenate Strings in Java by using + operator and by using concat() method.

Approach 1: By using + operator.

You can concat two or more strings in Java using + Operator. Let's see below program and things will be more clear.
class Test{  
 public static void main(String args[]){  
  String str = "Java" + "By" + "Patel";  
  System.out.println(str);  
 }  
} 

Output: JavaByPatel


Approach 2: By using String API's concat() method.

We can also using String class concat() method to concat 2 Strings in Java. Let's see one example below on how to use concat() method in Java.
class Test{  
 public static void main(String args[]){
  String str1 = "Java";
  String str2 = "By";
  String str3 = "Patel";
  
  String str1str2ConcatResult = str1.concat(str2);
  System.out.println(str1str2ConcatResult);
  
  String str1str2str3ConcatResult = str1str2ConcatResult.concat(str3);
  System.out.println(str1str2str3ConcatResult);
 }  
} 


Output: 
JavaBy 
JavaByPatel

You may also like to see


Exception Handling Interview Question-Answer

Method Overloading - Method Hiding Interview Question-Answer

Advanced Multithreading Interview Questions-Answers In Java

Type Casting Interview Questions-Answers In Java

How Thread.join() in Java works internally

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.

How to Reverse Word in Java Program

How to Reverse Word in Java.


Let's see, how to Reverse Words in Java using Iteration and Recursion. We will Reverse a Word using Recursion and using loop. For reversing a word we should not use any inbuilt methods.

Input:      "ReverseWord"
Output:   "droWesreveR"

Input:      "HELLO"
Output:   "OLLEH"

Input:      "123abc"
Output:   "cba321"

Tower Of Hanoi Program in Java.

Tower Of Hanoi Java Program


Lets see Tower of Hanoi program in Java. We will use Recursive algorithm to solve Tower of Hanoi problem. Towers of  Hanoi is a basically a famous game in which you are given a 3 Pegs, Start peg, Auxiliary or Helper peg and End Peg.

Start peg contains 3 disks of different sizes as shown. You have to move all the disk from Start peg to End peg using Auxiliary peg.  

There are few rules that need to keep in mind,
1. Only one disk can be moved at a time.
2. Large size disk can't be placed on top of small sized disk.

Lets understand what is the input and the expected output.

Fibonacci Series in Java Program

Java Program to print Fibonacci series. OR
Java Program to Print Fibonacci Series upto K Number. OR
Iterative Program to print Fibonacci series. OR
Recursive Program to print Fibonacci series.


Let's see, Fibonacci series in Java Program using Iterative and recursive Algorithm. we will also see Java Program to Print Fibonacci Series upto K Number. Fibonacci series is a series of natural number where next number is equivalent to the sum of previous two number.

Example: 
Java program to print fibonacci series up to a given number k. 
Input   = 5 Output = 0, 1, 1, 2, 3

Input   = 2
Output = 0, 1

Input   = 7
Output = 0, 1, 1, 2, 3, 5, 8  

Java Multithreading and Concurrency Interview Questions and Answers with Example

Java Multithreading and Concurrency Interview Questions and Answers


Java Multithreading and Conncurrency Interview questions answers for freshers and experienced.  Java Threads is popular Interview topic. lets start with how many ways Threads can be created in java.

Question 1. What are Threads in Java?

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 parallely.  

Insert Node in Binary Tree and Java Program to add a Node in Binary Tree

Insert Node in Binary Tree


Let's see how to Insert node in Binary Tree in Java and Java Program to add a Node in Binary Tree. For adding a node, start scanning a Binary Tree level by level and wherever we encounter vacant position, place a new Node there.

See below image to get better understanding of position of a new Node to insert.
Given a binary tree, we need to add a Node with value 8 marked in dotted lines below in its correct position.


Binary Tree Inorder Traversal in Java

Binary Tree Inorder Traversal in Java OR
Inorder Traversal Java Program


Binary Tree Inorder traversal is popular interview question. Inorder traversal is one of the way to traverse binary Tree. In Inorder traversal, Left subtree is read first then Root Node and then Right subtree.

There are 2 ways to do Inorder traversal,
1. Recursive Inorder traversal of Binary tree.
2. Iterative Inorder traversal of Binary tree.
   
Inorder traversal example.


Reverse a Linked list in Java Program

Reverse a Linked list OR
Reverse a Singly linked list.


Let's see, how to Reverse a Singly linked list in Java, how to Reverse Linked list using recursion, and how to Reverse a Linked list iteratively.

There are 2 ways to Reverse a Linked list using,

1. Recursive Algorithm.
2. Iterative Algorithm.

 Lets understand what is the input and the expected output.

Bubble Sort Program in Java

Bubble Sort in Java


Let's see Bubble sort java program, How Bubble sort works in Java, Bubble sort Algorithm in java.  

Sort array using Bubble sort in Java.
Lets understand what is the input and the expected output.

Selection Sort in Java

Selection Sort Program in Java


Lets understand Selection sort program in java, How Selection sort works in java, Selection sort Algorithm in java. 

Sort an array of integers using Selection sort in Java.
Lets understand what is the input and the expected output.
 

Why default constructor is not called during Deserialization process in Java.

Why default constructor is not called during deserialization process. OR
Why Deserialization does not invoke constructor in Java.


Let see why default constructor is not called during deserialization in java and how are the constructors invoked during serialization and deserialization.

Java serialization specification says, "For serializable objects, the no-arg constructor for the first non-serializable supertype is run". Lets see what this is all about and understand it with example.
 
See below diagram to get overview of Serialization and Deserialization process.

Serialization Interview Questions In Java

Serialization Interview Questions in Java OR
How are constructors called during serialization and deserialization OR
Why default constructor is not called while deserialization process.


Lets see Serialization Interview Questions in Java. Serialization in java example. Serialization Interview questions and answers for experienced.
 
Java Serialization and Deserialization is important concept and most asked in interviews at beginners level.


See below diagram to get overview of Serialization and Deserialization process.

Java Serialization and Deserialization Interview Questions with Example

Serialization and Deserialization Java Interview Questions OR
Serialization interview questions in Java OR
How are constructors called during serialization and deserialization OR
Why default constructor is not called while deserialization process.


In this post, we will see Serialization and Deserialization Interview Questions in Java.
How Serialization - Deserialization works in Java. Serialization - Deserialization example in Java. 

 
Java Serialization and Deserialization is important concept and most asked in interviews at beginners level.


See below diagram to get overview of Serialization and Deserialization process.

What is Websocket. Use of Websocket. Client server example using Websockets, AngularJS and Java.

What is Websocket? Use of Websocket? Client server program using Websockets, AngularJS and Java.


In this post, we will see what is websocket, use of websocket, websocket in java, websocket client server example using Websockets, AngularJS and Java. 
 
Websocket is bi-directional communication protocol over web that helps client to server and server to client communication on single TCP connection and on same port.
 

What is the use of Websocket and how it is helpful?
How things works before Websocket ?


For communication on web, HTTP is the standard protocol that is used.


HTTP is stateless protocol. It means,
    1. Client Request connection
    2. Connection established
    3. Client sends a request.
    4. Server gives response.
    5. Connection closed Now client and server are independent and unaware of each other.
If client want to communicate again then it has to again go with above steps,
Also, request is always initiated by client and server can't initiate communication.


So, if Server has to say something to the client then how to achieve that?



First of all, why server want to communicate with the client, Lets see below example,
   1. Say, Jayesh requested for fare information of Flight number MH 198 from Mumbai 
       to Ahmedabad. 
   2. Server responded to Jayesh "Price is 5000 INR."
   3. Jayesh is thinking whether to book a flight at 5000 INR and then finally after 5 minutes,
        he made a mind to book it.
   4. Now after filling long form of passenger list and other flight information, 
       when Jayesh pressed the "Book" button, he found that now Flight price is 6000 INR, 
       how this happen??????????
   5. Jayesh is frustrated and thinking why server not notified him before filling the long form 
       on passenger list.

Ideally, Server should notify Jayesh that flight price is changed, please refresh the page. 
But how the server will know that to which all clients he need to inform and top of all, Server doesn't know any information on client.
This is possible only if server is capable of identifying client that, "who all client are connected to server and notify them on updates".

As communication happens over HTTP, Before Websocket, Server notify to the client using below techniques,

1. Polling

In this technique,
  1. Client requests a webpage from a server using regular HTTP request.
  2. The requested webpage executes JavaScript which requests for updates from the server at 
       regular intervals (say 1 seconds).
  3. The server checks for updates and responds back, just like normal HTTP response.

In Polling, client continuously polls server at regular intervals, asking is there any updates for client?

Disadvantage: if there is no updates, then unnecessarily client sends request to server and it hits server performance.

2. Long Polling

In this technique, 
  1. A client requests a webpage from a server using regular HTTP request.
  2. The requested webpage executes JavaScript which requests for updates from the server.
  3. Now if server does not has any updates, then server does not immediately responds telling 
      "no update" instead waits until there's new information available.
      When there's update available, the server responds with the updated information that help 
      client  on information say price has changed.
  4. The client receives updated price information and immediately sends another request 
       to the server, re-starting the process.

Disadvantage: Server like Tomcat would spawned thread to handle for each request, that reserve resources, till its done. So the traffic is smaller, but eats resources fast (also block resources).

Websocket overcome issues present in Polling and Long Polling.
One limitation with Websocket is that it is only supported with HTML 5 compliant  browsers.

Lets see a sample application on updating total count of connected clients using WebSockets, AngularJS and Java.


Client Side HTML and Javascript

index.html
<!DOCTYPE html>
<html>
 <head>
 
  <title>Websocket Example</title>  
  <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.0/angular.js"></script>
  <script src="app.js"></script>  
 
 </head>
 <body  data-ng-app="websocketDemoApp" style="margin:0px;">  
  
  <div data-ng-controller="appController">
   
   <label style="font-size: 20px; font-weight: bold;">Messages from Websocket Communication : </label>
   <pre>{{ websocketMessage }}</pre><br>
   
   <label style="font-size: 20px; font-weight: bold;">Connected Clients : </label>
   <label style="font-size: 40px; font-weight: bold;">{{ numberOfUsersConnected }}</label>
   
  </div>
  
 </body>
</html> 
app.js
'use strict';
var module = angular.module('websocketDemoApp', [ ]);

angular.module('websocketDemoApp').controller("appController", ['$scope', function($scope) {

 $scope.websocketMessage = "";
 
 $scope.getURLWithOutProtocalFromCurrentContext = function() {
  var hostName = window.location.host;
  var currentPath = window.location.pathname;
  return hostName + currentPath;
 };
 
 var urlWithOutProtocol = $scope.getURLWithOutProtocalFromCurrentContext();
 var wsUri = "ws://" + urlWithOutProtocol +"endpoint";
 var websocket = new WebSocket(wsUri);
 
 websocket.onopen = function(evt) {
  console.log("connection established");
  
  $scope.$apply(function(){
   $scope.websocketMessage = $scope.websocketMessage + "Connection to Websocket has established." + "\n";
        });
  
 };
 
 websocket.onmessage = function(evt) {
  console.log("message received: "+evt.data);
  var jsonResponse = JSON.parse(evt.data);
  
  $scope.$apply(function(){
   
   if(jsonResponse.count!=null || !angular.isUndefined(jsonResponse.count))
    $scope.numberOfUsersConnected = jsonResponse.count;
   
   if(jsonResponse.message!=null || !angular.isUndefined(jsonResponse.message))
    $scope.websocketMessage = $scope.websocketMessage + "Data Received: " +jsonResponse.message + "\n";
   
   
  });
 };
 
 websocket.onerror = function(evt) {
  console.log('websocket error: ' + jsonResponse);
  $scope.websocketMessage = $scope.websocketMessage + "There is some error while establishing connection to web socket." + "\n";
 };
 
 websocket.onclose = function(){
  $scope.websocketMessage = $scope.websocketMessage + "Web Socket connection is closed now..." + "\n";
    };
 
}]);


Server Side Java Code


ServerPush.java
package com.websocket.test;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.websocket.CloseReason;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

@ServerEndpoint("/endpoint")
public class ServerPush {
 private static Map<Object, Session> mapConnections = new HashMap<Object, Session>();

 public ServerPush() {
  //Starting notifier to push data to client at 1 minute interval
  new NotifierExample();
 }

 //This method is called when websocket connection is established or open.
 @OnOpen
 public void start(Session session) {
  mapConnections.put(session.getId(), session);
  String json = "{ \"count\" : \""+mapConnections.size()+"\"}"; 
  broadcastToAll(json);
 }

 @OnMessage
 public void echoTextMessage(Session session, String msg, boolean last) {
  String json = "{ \"count\" : \""+mapConnections.size()+"\"}";
  broadcastToAll(json);
 }
 
 //This method is called when websocket connection is closed or when browser tab is closed. 
 @OnClose
 public void end(Session session, CloseReason reason) {
  mapConnections.remove(session.getId());
  String json = "{ \"count\" : \""+mapConnections.size()+"\"}"; 
  broadcastToAll(json);
 }

 //For sending data to single connected client for one to one communication between client and server.
 public static void broadcast(String key, String message) {
  Session session = mapConnections.get(key);
  if(session!=null){
   try {
    session.getBasicRemote().sendText(message);
   } catch (IOException e) {
    try {
     session.close();
    } catch (IOException e1) {
     // Ignore
    }
   }
  }
 }

 //For sending data to all the connected clients
 public static void broadcastToAll(String message) {
  for(Session session : mapConnections.values()){
   if(session!=null){
    try {
     session.getBasicRemote().sendText(message);
    } catch (IOException e) {
     try {
      session.close();
     } catch (IOException e1) {
      // Ignore
     }
    }
   }
  }
 }

}

NotifierExample.java
package com.websocket.test;

import java.util.Timer;
import java.util.TimerTask;

public class NotifierExample extends TimerTask{

 //After every 60 seconds, server will push the data to all connected clients.
 public NotifierExample() {
     Timer timer = new Timer();
     timer.schedule(this, 5000, 60000);
 }
 
 @Override
 public void run() {
  String json = "{ \"message\" : \"Database table is updated, Please refresh to get updated records.\"}";
  ServerPush.broadcastToAll(json);
 }
}


Note: ServerPush.java use classes from websocket jar, So make sure you have websocker-api.jar present in tomcat lib folder, if not then download using below dependency,

    javax.websocket
    javax.websocket-api
    1.0


After setup, Run the application in Tomcat.
  1.  Open browser and try to access application "http://localhost:8080/AppName"
  2.  Now, open firefox browser and try to access application "http://localhost:8080/AppName"
In the browser you will observe that as and when number of connected clients increase, 
the server pushes the total connected client count information on browser as well without explicit request from client

Output:


You may also like to see


Number Range Spinner in Angular JS

Using JQuery Datatable in AngularJS application.

Download binary file AngularJS + REST service

Configure Angular2 + Webpack + Maven Sample


Enjoy !!!! 

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