Oswald
Oswald

Reputation: 21

Palindrome number check- issue with output

I tried to write a program to check whether a number is a palindrome or not in Java. I tried to convert int to String, and using built-in methods, wrote this logic. But I don't know why I am getting incorrect output for the given input.

class Main {
    public static void main(String[] args) {
        int x=1213;
        
        StringBuilder s= new StringBuilder();
        s.append(x);
        StringBuilder s2=new StringBuilder();
        s2=s.reverse();
       
        
        if((s.toString()).equals(s2.toString()))
        {
           System.out.println(x+" is a palindrome number");
        }
        else{
            System.out.println(x+"is not a palindrome number");
        }
    }

Upvotes: 0

Views: 49

Answers (2)

khelwood
khelwood

Reputation: 59113

You call s.reverse(), which reverses s in place; and you assign it to s2, so s and s2 are the same object.

You don't need two StringBuilders at all, since you only need to make one modification.

StringBuilder sb = new StringBuilder();
sb.append(x);
sb.reverse();
if (sb.toString().equals(String.valueOf(x))) {
    // the number is a palindrome
}

Upvotes: 2

Oussama ZAGHDOUD
Oussama ZAGHDOUD

Reputation: 2159

 s2=s.reverse();

Here the StringBuilder class is not immutable , reverse operation will reverse the content of the original the StringBuilder s, you should construct a new StringBuilder here :

public class Main {
public static void main(String[] args) {
    int x=1213;
    
    StringBuilder s= new StringBuilder();
    s.append(x);
    StringBuilder s2=new StringBuilder();
    s2=new StringBuilder(s).reverse();
   
    
    if((s.toString()).equals(s2.toString()))
    {
       System.out.println(x+" is a palindrome number");
    }
    else{
        System.out.println(x+"is not a palindrome number");
    }
}
}

Upvotes: 2

Related Questions