Java String charAt()
The java string charAt() method returns a char value at the given index number. The index number starts from 0. It returns StringIndexOutOfBoundsException if given index number is greater than this string or negative index number.Signature
The signature of string charAt() method is given:public char charAt(int index)
Parameter
index: index number, starts with 0Returns
char valueSpecified by
CharSequence interfaceThrows
StringIndexOutOfBoundsException : if index is negative value or greater than this string length.Java String charAt() method example
public class CharAtExample{ public static void main(String args[]){ String name="Catchmecoder"; char ch=name.charAt(7); //returns the char value at the 4th index System.out.println(ch); }}
Output:
c
StringIndexOutOfBoundsException with charAt()
see the example of charAt() method where we are passing greater index value. In such case, it throws StringIndexOutOfBoundsException at run time.Example:
public class CharAtExample{ public static void main(String args[]){ String name="Catchmecoder"; char ch=name.charAt(12); //returns the char value at the 10th index System.out.println(ch); }}
Output:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 12 at java.lang.String.charAt(String.java:658) at CharAtExample.main(CharAtExample.java:4)
Java String endsWith
The java string endsWith() method checks if this string ends with given suffix. It returns true if this string ends with given suffix else returns false.Signature
The syntax or signature of endsWith() method is given:Syntax:
public boolean endsWith(String suffix)
Parameter
suffix : Sequence of characterReturns
true or falseJava String endsWith() method example
Example:
public class EndsWithExample{ public static void main(String args[]){ String s1="catch by catchmecoder"; System.out.println(s1.endsWith("r")); System.out.println(s1.endsWith("coder")); }}
Output:
true true