Saturday, July 2, 2022

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

You can get the first and last character of a String using the 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 the 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 the first and the last element from an array; both work the 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 the charAt() function.

Btw, I am expecting that you are familiar with basic Java Programing and Java API in general. If you are a complete beginner, then I suggest you first go through a comprehensive course like  The Complete Java MasterClass on Udemy to learn more about core Java basics and such gems from Java API.




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

Here is a sample java program to demonstrate how you can use the charAt() method from the CharSequence interface to retrieve the leading and trailing character from String in Java.

In this program, I have shown two examples. The first one uses the charAt() method for getting the first and last character, and the second one using the toCharArray() method to first convert String to a character array and then retrieve the first and last element.

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


Java Program to get first and last character of given String in Java

Here is a complete Java program to extract first and last character of given String in Java using charAt(index) method
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 the \" 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() method of String in Java

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

2. The valid index range 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 the charAt() method is declared at the CharSequence interface, you can also use it to get the first and last character from StringBuffer and StringBuilder in Java also implement the CharSequence interface.

Here is a 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 the charAt() method makes your job so easy; you just need to remember that the 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? (topics and resources)
  • How to compare two String objects 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)
  • 35 Java String concepts interview questions (questions)
  • How to use intern() method of String in Java? (intern method)

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