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.


An alternative way to get the first and last character is to convert String to a char array and then extract first and last element from an array, both works same way. Let's see a couple of examples of retrieving the first and last character from String in Java and some important points about charAt() function.



Java Program to get first and last character of String

Here is a sample java program to demonstrate how you can use the charAt() method from CharSequence interface to retrieve the leading and trailing character from String in Java. In this program I have shown two examples, first one uses the charAt() method for getting the first and last character and the second one using toCharArray() method to first convert String to a character array and then retrieve the first and last element.

Since StringBuffer and StringBuiler also implement CharSequnce interface, they can also use the charAt() method directly to get the first and last character, which is shown in the 3rd example.

public class Solution {

public static void main(String args[]) {

// You can use the charAt(int index) method to get the first and last
// character of a String in Java. 

// suppose you want the first and last character from a String
// here first character of "iPhone"is "i" and last character
// is "e"
String phone = "iPhone";

char first = phone.charAt(0); // just like array, string index is zero based
char last = phone.charAt(phone.length() - 1); // last char is at index length - 1

System.out.printf("first character of string \"%s\" is '%c' %n", phone, first);
System.out.printf("last character of string \"%s\" is '%c' %n", phone, last);


// Alternatively, you can also get the character array from String
// and than extract first and last characters as shown below

String device = "Bluetooth headset";
char[] characters = device.toCharArray();

char firstChar = characters[0]; // first character is from index zero
char lastChar = characters[characters.length - 1]; // first character is from index length -1

System.out.printf("first character of string \"%s\" is '%c' %n",
device, firstChar);
System.out.printf("last character of string \"%s\" is '%c' %n",
device, lastChar);


// You can also use charAt() function to retrieve first and last
// character from StringBuffer and StringBuilder as well

StringBuffer buffer = new StringBuffer("Programming");
char firstCharacter = buffer.charAt(0);
char lastCharacter = buffer.charAt(1);

System.out.printf("first character of StringBuffer \"%s\" is '%c' %n",
buffer, firstCharacter);
System.out.printf("last character of StringBuffer \"%s\" is '%c' %n",
buffer, lastCharacter);
}

}

Output:
first character of string "iPhone" is 'i' 
last character of string "iPhone" is 'e' 
first character of string "Bluetooth headset" is 'B' 
last character of string "Bluetooth headset" is 't' 
first character of string "Programming" is 'P' 
last character of string "Programming" is 'r' 

You can see from the output that charAt() method is working as expected. It also worked fine with StringBuffer and you can test it with StringBuilder as well. If you are curious about \" in System.out.printf() method then that is to escape double quotes in Java. Since double quotes "" is a special character if used literally it will mark the end of String passed to printf() method, to prevent that I have escaped it using the backslash (\) character.


Important points about charAt() function in Java

1) The charAt() method accepts an integer index and returns the corresponding character from the index.

2) The range of valid index is 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.

3) The charAt() function throws IndexOutOfBoundsException, if the index argument is negative or not less than the length of this string.

4) Since charAt() method is declared at CharSequence interface, you can also use it to get the first and last character from StringBuffer and StringBuilder in Java, as they also implement the CharSequence interface.

Here is nice summary of both approaches to get the first and last character array in Java:
How to get first and last character from String in Java


That's all about how to get the first and last character from String in Java. You can see that charAt() method makes your job so easy, you just need to remember that first character resides at index zero and the last character resides at index length() - 1, where length() returns the length of String. Alternatively, you can also convert String to an array and then retrieve the first and last element of an array in Java.

Other Java String tutorials for further Reading
  • How to prepare Java Interviews? (book)
  • How to compare two String object in Java? (solution)
  • How to reverse String in Java using iteration and recursion? (solution)
  • How to convert byte array to Hex String in Java? (answer)
  • How to convert Double to String in Java? (answer)
  • When to use the intern() method in Java? (answer)

Recommended Books
Clean Code
Core Java, Volume 1 9th Edition

2 comments :

Vicente Martinez said...

Thank you this is a very good one

Rana Prathap said...

char lastCharacter = buffer.charAt(1);

last character of string "Programming" is 'r' :)

Change it

Post a Comment