why string length -1

I have found the following program to check if a string is palindrome.

import java.util.Scanner;

public class PalindromeString{
    public static void main(String[] args){
        Scanner in = new Scanner(System.in);
        System.out.println("Enter the string which you want to check whether that is palindrome or not: ");
        String s = in.next();
        String r = "";
        for(int i=s.length()-1; i>=0; i--){
            r = r+s.charAt(i);
        }
        System.out.println("Reverse of entered string "+s+" is "+r);
        if(r.equals(s)){
            System.out.println("String "+s+" is palindrome.");
        }else{
            System.out.println("String "+s+" is not palindrome.");
        }
    }
}

I did not understand why the coder initialized the loop variable i to s.length()-1. Can anyone explain me why? I have searched related content for string length but couldn’t find an answer for this.

Source: java

Leave a Reply