Thursday 4 February 2016

How to get first and last character of String in Java - Example

You can get the first and last character of a String using charAt() method in Java. This method accepts an integer index and returns the corresponding character from String. Since Java String is backed by an array, their index is also zero-based, which means the first character resides at index zero and the last character is at index, length-1, where length is the number of characters in the String. You can get the length of String by calling the length() method. The charAt() method is not defined on java.lang.String class, but on its super interface java.lang.CharSequence, hence it will also work for StringBuffer and StringBuilder. This method returns the char value at the specified index. An index ranges from 0 to length() - 1. The first char value of the sequence is at index 0, the next at index 1, and so on, as for array indexing. If the char value specified by the index is a surrogate, the surrogate value is returned.
Read more »

No comments:

Post a Comment