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.

find smallest window in array sorting which will make entire array sorted
Find smallest window in array sorting which will make entire array sorted

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.
factorial of a number from 1 to 20 table
Count trailing zeros in factorial of a number

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. 
soap vs rest api
SOAP vs REST

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.

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


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 javabypatel;

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 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.string;

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.string;

public 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.
package com.javabypatel.string;

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



Approach 4:
In this approach, we compare first and last digit of a number, (example say 12321, so we compare first 1 and last 1). 
- If they are not same, return false,
- If they are same, remove first and last digit from the number(remaining number 232 ) and repeat the same steps again for remaining number.
package com.javabypatel.string;

public class PalindromeCheck{ 

    public static void main(String[] args) {
        int number = 12321;
        boolean result = checkPalindrome(number);
        System.out.println(result);
    }

    private static boolean checkPalindrome(int number) {
        int divisor = findDivisor(number);

        while (number != 0) {
            int lastDigit = number % 10;        //for 12321 % 10    -> last 1
            int firstDigit = number / divisor;  //for 12321 / 10000 -> first 1

            if (firstDigit != lastDigit) {
                return false;
            }

            number = number % divisor;          //for 12321 % 10000 -> remove first 1 from number = 2321
            number = number / 10;               //for 2321/10 -> remove last 1 from number = 232

            //we remove two numbers from 12321 and new number is 232, so we need to calculate new divisor
            //we remove two numbers so two zeros should be removed from divisor, so we can do divisor/100 to get
            //new divisor
            divisor = divisor / 100;

            //repeat the step for 232
        }
        return true;
    }

    private static int findDivisor(int number){
        int divisor = 1;

        // 12321/1 = 12321(it is >= 10), so 12321/10 = 1232, so 12321/100 = 123, so 12321/1000 = 12, so 12321/10000 = 1 end
        while (number / divisor >= 10) {
            divisor = divisor * 10;
        }
        return divisor;
    }
}

You may also like to see


Check whether String is Palindrome or Not in Java.

Count number of Bits to be flipped to convert A to B 

Count number of Set Bits in Integer. 

Check if number is Power of Two. 

Find all subsets of a set (Power Set). 

Skyline Problem in Java. 

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

Count trailing zeros in factorial of a number 

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

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.

In this post we will see Bubble sort java program, How Bubble sort works in Java, Bubble sort Algorithm in java and Sorting array using Bubble sort in Java.

Lets understand what is the input and the expected output.

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 iterating, 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.It takes O(1) extra space.

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.

Check if Number is Palindrome in Java


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.

package javabypatel;

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


package javabypatel;

public 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



Check if Number is Palindrome in Java

Given an array of integers. All numbers occur thrice except one number which occurs once. Find the number in O(n) time & constant extra space. 

Count number of Bits to be flipped to convert A to B 

Count number of Set Bits in Integer. 

Check if number is Power of Two. 

Find all subsets of a set (Power Set). 

Skyline Problem in Java. 

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

Count trailing zeros in factorial of a number 

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

Tower Of Hanoi Program in Java. 

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.
package javabypatel;

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

package javabypatel;

public 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


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.

Binary Tree Inorder traversal is a very popular interview question so better to understand it properly. 

There are 2 ways of doing Inorder traversal,
  1. Recursive Inorder traversal of Binary tree.
  2. Iterative Inorder traversal of Binary tree.

Reverse a Linked list in Java Program

Reverse a Linked list OR
Reverse a Singly linked list Iteratively.


Let's see, how to Reverse a Singly linked list Iteratively 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.