charAt() method

    charAt() method

    Java string method charAt() will provide you with the char value at the specific index value. This index starts from 0 to n-1 value, where n denotes the length of the string. If the provided index is greater than the string length or has a negative value then the StringIndexOutOfBoxException will get raised.

    Method implementation-

    public char charAt(int index) {  
    
           if ((index < 0) || (index >= value.length)) {  
    
               throw new StringIndexOutOfBoundsException(index);  
    
           }  
    
           return value[index];  
    
       }  

    Method syntax-

    public char charAt(int index)

    Example-

    public class Simple{  
    
       public static void main(String args[])
    {  
          String name="Welcome";  
          char ch=name.charAt(4);
         System.out.println(ch);  
        }
    }  

    Output-

    Example with Exception-

    public class Simple
        {  
        public static void main(String args[]){  
         String name="Welcome";  
         char ch=name.charAt(10);
         System.out.println(ch);  
        }
    }  

    Example using the string length-

    public class Simple {  
        public static void main(String[] args) {  
        String str = "Welcome to Java";      
        int len = str.length();      
    
        System.out.println("0 index is: "+ str.charAt(0));      
        System.out.println("last index is: "+ str.charAt(len-1));      
        }  
    }  

    Output-

    Java String length Method