Saturday, June 8, 2024

Write a Java program to check if a string is a palindrome.

 import java.util.Scanner;


public class Palindrome {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter a string: ");

        String str = scanner.nextLine();

        scanner.close();

        

        boolean isPalindrome = isPalindrome(str);

        System.out.println("Is Palindrome: " + isPalindrome);

    }

    

    public static boolean isPalindrome(String str) {

        int i = 0, j = str.length() - 1;

        while (i < j) {

            if (str.charAt(i) != str.charAt(j))

                return false;

            i++;

            j--;

        }

        return true;

    }

}


No comments:

Post a Comment