topics content@scaler.com
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Versions and GitHub Sync Note Insights Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       owned this note    owned this note      
    Published Linked with GitHub
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    --- title: Java Program to Check Whether a String/Number is a Palindrome - Scaler Topics description: Learn how to check palindrome string in Java by Scaler Topics. In this article, we have discussed Java program to check string palindrome. author: Srijan Kumar Samanta category: Java --- :::section{.main} A palindrome string in java is a number, word, phrase or other sequence of characters that reads the same forwards and backwards. This article focuses on determining whether a given word or number is a palindrome or not. ### Palindrome Example The string "abcba" is a palindrome, while the string "abca" is not. In the image given below, there is a sequence of digits that make it a palindrome number- ![program to check palindrome string in java](https://scaler.com/topics/images/program-to-check-palindrome-string-in-java-768x350.webp) ::: :::section{.main} ## Methods to Check Palindrome String in Java There are three main methods to check palindrome string in Java. They are listed below: 1. **Naive Method** 2. **Two Pointer Method** 3. **Recursive Method** ### Naive Method to Check Palindrome String in Java In this approach, we check whether the palindrome string is in Java by reversing it and comparing it with the original string. Lets see the below example to understand clearly: ```java import java.io.*; class PalindromeChecker { public static boolean isPalindrome(String str) { // Initialize an empty string to store the reversed version of the original string String reversed = ""; for (int i = str.length() - 1; i >= 0; i--) { // Append each character to the 'reversed' string reversed = reversed + str.charAt(i); } return str.equals(reversed); } public static void main(String[] args) { // Example input string String input = "radar"; // Convert the input string to lowercase (optional, for case-insensitive comparison) input = input.toLowerCase(); boolean isPal = isPalindrome(input); // Output the result System.out.println("Is the string \"" + input + "\" a palindrome? " + isPal); } } ``` **Output:** ``` Is the string "radar" a palindrome? true ``` #### Time Complexity: O(N) N is the length of the input string, as the for loop iterates through each character once to create the reverse string. #### Space Complexity- O(N) because the reverse string is stored in a separate variable proportional to the length of the input string. ### Two Pointer Method for String Palindrome Program in Java In this approach, we utilize two pointers, `i` and `j`, where `i` points to the start of the string and `j` points to the end. We compare the characters at these positions by incrementing `i` and decrementing `j`. If they match, we continue; otherwise, we conclude that the string is not a palindrome. ```java public class PalindromeChecker { // Method to check if a given string is a palindrome static boolean isPalindrome(String str) { int left = 0, right = str.length() - 1; while (left < right) { if (str.charAt(left++) != str.charAt(right--)) return false; } return true; } public static void main(String[] args) { String example1 = "radar"; String example2 = "level"; // Convert examples to lowercase example1 = example1.toLowerCase(); example2 = example2.toLowerCase(); if (isPalindrome(example1)) System.out.println(example1 + " is a palindrome."); else System.out.println(example1 + " is not a palindrome."); if (isPalindrome(example2)) System.out.println(example2 + " is a palindrome."); else System.out.println(example2 + " is not a palindrome."); } } ``` **Output:** ``` radar is a palindrome. level is a palindrome. ``` #### Time Complexity- O(n) #### Space Complexity- O(1) ### Recursive Method to Check String Palindrome in Java We adopt a recursive approach similar to the two-pointer technique to determine if a palindrome string in java. Two pointers, 'i' and 'j', initially point to the start and end of the string, respectively. We compare the characters at positions 'i' and 'j' during each recursive call. If they match, we move 'i' one step forward and 'j' one step backwards and make a recursive call with the updated indices. This process continues until 'i' becomes greater than or equal to 'j'. If, at any point, the characters at 'i' and 'j' don't match, we immediately return false, indicating that the given string is not a palindrome. If every character pairs match until 'i' becomes greater than or equal to 'j', we conclude that the string is a palindrome and return true. ```java public class PalindromeChecker { // Method to check if a given string is a palindrome static boolean isPalindrome(String str,int i,int j) { if (i >= j) { return true; } // comparing the characters on those pointers if (str.charAt(i) != str.charAt(j)) { return false; } //rechecking everything recursively return isPalindrome(str,i + 1, j - 1); } public static void main(String[] args) { String example1 = "radar"; String example2 = "level"; // Convert examples to lowercase example1 = example1.toLowerCase(); example2 = example2.toLowerCase(); if (isPalindrome(example1,0,example1.length()-1)) System.out.println(example1 + " is a palindrome."); else System.out.println(example1 + " is not a palindrome."); if (isPalindrome(example2,0,example1.length()-1)) System.out.println(example2 + " is a palindrome."); else System.out.println(example2 + " is not a palindrome."); } } ``` **Output:** ``` radar is a palindrome. level is a palindrome. ``` #### Time Complexity- O(n) #### Space Complexity- O(n) ::: :::section{.summary} ## Conclusion * A palindrome is a word, number, phrase or a general sequence that reads the same backwards as forwards. * We can determine whether a string is a palindrome by reversing and comparing it with the given original string. * One slightly optimized approach is to compare the values at indices equidistant from both ends. * We can determine a palindromic number by reversing it and comparing it with the original number. :::

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully