0

I want to find the palindrome of a string.

public static void main(String[] args)
    {
      String s1 = "eye",s2="";
     for(int i = s1.length()-1;i<=0;--i)
     {
          s2 =s2+String.valueOf(s1.charAt(i));

     }
          System.out.println(s1);
        System.out.println(s2);
    }
}

I expected the output eye eye but, s2 isn't printing.

Hien Nguyen
  • 24,551
  • 7
  • 52
  • 62

1 Answers1

2

You have the wrong condition in the for loop. The correct condition should be i>=0.

Remember that as long as this condition is true, the for loop will run. Your original condition, i<=0 is false at the very beginning, when i is 2, so the for loop never starts.

A less important problem is that you should not concatenate strings in a for loop, and should use a StringBuilder instead. See this.

Sweeper
  • 213,210
  • 22
  • 193
  • 313