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.