String or a number is said to be a palindrome if it remains the same even after it is reversed. For example, ‘MADAM’ is a palindrome string since it is spelled ‘MADAM’ even if it is reversed. But in the case of ‘LUCKY’, this string is not palindrome as it is ‘YKCUL’ when it is reversed. Some of the palindrome numbers are 365563, 48984, 12321, 171, 88, 90009, 343, and some of the palindrome strings are MADAM, MALAYALAM, LOL, DAD, MOM, C++&++C, etc. Let us see the logic and implementation of palindrome in the following sections. In this topic, we are going to learn about?Palindrome in Java.
Start Your Free Software Development Course
Web development, programming languages, Software testing & others
Logic Behind Palindrome in Java
In order to check whether a number is a palindrome, the following algorithm can be used.
- Take an input string or number that has to be checked whether it is a palindrome or not.
For example, let us take the number 353 as input.
- Take the input number and copy it into a temp variable
353-> temp
- Reverse it using for, while or any method of your choice.
Reversednumber: rev=353
- Compare the input number and reversed number.
If they are the same, then the number is said to be a palindrome number.
Else, the number is not a palindrome number.
i.e.
If(inputnum==rev) { then palindrome } Else not palindrome
How to Test Palindrome using Various Methods?
There are several methods in order to check whether the given input number is a palindrome or not.
- For Loop
- While Loop
- Library Method(for strings)
Let us look into each of them in detail:
1. Program to check palindrome number using for loop
Code:
//Java program to check whether a String is a Palindrome or not using For Loop import java.util.*; public class PalindromeNumberExample { //main method public static void main(String[] args) { int r=0 ; //reversed Integer int rem, num; //remainder and original number Scanner s = new Scanner(System.in); System.out.print("Enter number that has to be checked:"); num = s.nextInt(); //Store the number in a temporary variable int temp = num; //loop to find the reverse of a number for( ;num != 0; num /= 10 ) { rem = num % 10; // find the modulus of the number when divided by 10 r = r * 10 + rem; } //check whether the original and reversed numbers are equal if (temp == r) { System.out.println(temp + " is input number"); System.out.println(r + " is the reversed number"); System.out.println("Since they are equal " + temp + " is a palindrome number"); } else { System.out.println(temp + " is input number"); System.out.println(r + " is the reversed number"); System.out.println("Since they are not equal " + temp + " is not a palindrome number"); } } }
Output 1:
Here, as 353 is the same when reversed, it is considered as a palindrome.
Output 2:
Here, as 234 remains not the same when reversed, it is not considered a palindrome.
2. Program to check palindrome number using While loop
Code:
//Java program to check whether a number is a Palindrome or not using While Loop import java.util.*; public class PalindromeNumberExample { public static void main(String[] args) { int r=0, rem, num; Scanner s = new Scanner(System.in); System.out.print("Enter number that has to be checked:"); num = s.nextInt(); //Store the number in a temporary variable int temp = num; //loop to find the reverse of a number while( num != 0 ) { rem= num % 10; r= r * 10 + rem; num=num/10; } //check whether the original and reversed numbers are equal if (temp == r) { System.out.println(temp + " is input number"); System.out.println(r + " is the reversed number"); System.out.println("Since they are equal " + temp + " is a palindrome number"); } else { System.out.println(temp + " is input number"); System.out.println(r + " is the reversed number"); System.out.println("Since they are not equal " + temp + " is not a palindrome number"); } } }
Output 1:
Output 2:
3. Program to check palindrome number using library method (for strings)
Code:
//Java program to check whether a String is a Palindrome or not using Library method import java.util.*; public class PalindromeNumberExample { //Function to check whether the string is palindrome or not public static void PalindromeCheck(String str) { // reverse the input String String rev = new StringBuffer(str).reverse().toString(); // checks whether the string is palindrome or not if (str.equals(rev)) { System.out.println("input string is :" + str); System.out.println("Reversed string is :" + rev); System.out.println("Since the input and reversed string are equal, "+ str +" is a palindrome"); } else { System.out.println("input string is :" + str); System.out.println("Reversed string is :" + rev); System.out.println("Since the input and reversed string are not equal, "+ str +" is not a palindrome"); } } public static void main (String[] args) { PalindromeCheck("MALAYALAM"); } }
Output:
Here, the input string is passed in the program itself.
To check whether a string is a palindrome, the following program is also used.
Code:
//Java program to check whether a String is a Palindrome or not import java.util.*; public class PalindromeNumberExample { public static void main(String args[]) { String st, rev = ""; Scanner sc = new Scanner(System.in); System.out.println("Enter the string that has to be checked:"); st = sc.nextLine(); int len = st.length(); //length of the string for ( int i = len- 1; i >= 0; i-- ) rev = rev + st.charAt(i); if (st.equals(rev)) { System.out.println("input string is :" + st); System.out.println("Reversed string is :" + rev); System.out.println("Since the input and reversed string are equal, "+ st +" is a palindrome"); } else { System.out.println("input string is :" + st); System.out.println("Reversed string is :" + rev); System.out.println("Since the input and reversed string are not equal, "+ st +" is not a palindrome"); } } }
Output:
Conclusion
A number is said to be palindrome if it remains the same even when it is reversed. A palindrome can be checked in strings also. Some of the palindrome numbers and strings are MOM, MALAYALAM, DAD, LOL, 232, 1331, etc. In this document, several aspects of Palindrome are covered, such as algorithm, methods, implementation, etc.
The above is the detailed content of Palindrome in Java. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

The rational use of semantic tags in HTML can improve page structure clarity, accessibility and SEO effects. 1. Used for independent content blocks, such as blog posts or comments, it must be self-contained; 2. Used for classification related content, usually including titles, and is suitable for different modules of the page; 3. Used for auxiliary information related to the main content but not core, such as sidebar recommendations or author profiles. In actual development, labels should be combined and other, avoid excessive nesting, keep the structure simple, and verify the rationality of the structure through developer tools.

When you encounter the prompt "This operation requires escalation of permissions", it means that you need administrator permissions to continue. Solutions include: 1. Right-click the "Run as Administrator" program or set the shortcut to always run as an administrator; 2. Check whether the current account is an administrator account, if not, switch or request administrator assistance; 3. Use administrator permissions to open a command prompt or PowerShell to execute relevant commands; 4. Bypass the restrictions by obtaining file ownership or modifying the registry when necessary, but such operations need to be cautious and fully understand the risks. Confirm permission identity and try the above methods usually solve the problem.

There are three main differences between Callable and Runnable in Java. First, the callable method can return the result, suitable for tasks that need to return values, such as Callable; while the run() method of Runnable has no return value, suitable for tasks that do not need to return, such as logging. Second, Callable allows to throw checked exceptions to facilitate error transmission; while Runnable must handle exceptions internally. Third, Runnable can be directly passed to Thread or ExecutorService, while Callable can only be submitted to ExecutorService and returns the Future object to

Javaprovidesmultiplesynchronizationtoolsforthreadsafety.1.synchronizedblocksensuremutualexclusionbylockingmethodsorspecificcodesections.2.ReentrantLockoffersadvancedcontrol,includingtryLockandfairnesspolicies.3.Conditionvariablesallowthreadstowaitfor

Java's class loading mechanism is implemented through ClassLoader, and its core workflow is divided into three stages: loading, linking and initialization. During the loading phase, ClassLoader dynamically reads the bytecode of the class and creates Class objects; links include verifying the correctness of the class, allocating memory to static variables, and parsing symbol references; initialization performs static code blocks and static variable assignments. Class loading adopts the parent delegation model, and prioritizes the parent class loader to find classes, and try Bootstrap, Extension, and ApplicationClassLoader in turn to ensure that the core class library is safe and avoids duplicate loading. Developers can customize ClassLoader, such as URLClassL

The key to Java exception handling is to distinguish between checked and unchecked exceptions and use try-catch, finally and logging reasonably. 1. Checked exceptions such as IOException need to be forced to handle, which is suitable for expected external problems; 2. Unchecked exceptions such as NullPointerException are usually caused by program logic errors and are runtime errors; 3. When catching exceptions, they should be specific and clear to avoid general capture of Exception; 4. It is recommended to use try-with-resources to automatically close resources to reduce manual cleaning of code; 5. In exception handling, detailed information should be recorded in combination with log frameworks to facilitate later

Java supports asynchronous programming including the use of CompletableFuture, responsive streams (such as ProjectReactor), and virtual threads in Java19. 1.CompletableFuture improves code readability and maintenance through chain calls, and supports task orchestration and exception handling; 2. ProjectReactor provides Mono and Flux types to implement responsive programming, with backpressure mechanism and rich operators; 3. Virtual threads reduce concurrency costs, are suitable for I/O-intensive tasks, and are lighter and easier to expand than traditional platform threads. Each method has applicable scenarios, and appropriate tools should be selected according to your needs and mixed models should be avoided to maintain simplicity

Polymorphism is one of the core features of Java object-oriented programming. Its core lies in "one interface, multiple implementations". It implements a unified interface to handle the behavior of different objects through inheritance, method rewriting and upward transformation. 1. Polymorphism allows the parent class to refer to subclass objects, and the corresponding methods are called according to the actual object during runtime; 2. The implementation needs to meet the three conditions of inheritance relationship, method rewriting and upward transformation; 3. It is often used to uniformly handle different subclass objects, collection storage and framework design; 4. When used, only the methods defined by the parent class can be called. New methods added to subclasses need to be transformed downward and accessed, and pay attention to type safety.
