- To find the first and last character of a string in Java we have methods to find them.
Methods
- To find the first and last character of a string in java ,you can use the char At() method along with the length() method.
Explanation :
- To find the first character of string in java use charAt(O) method since string indexing starts from O.
- To get the last character of string in java use charAt(str.length() -1).
public class Main { public static void main(String[] args) { String str = "Iam Navya Sahithi"; char firstChar = str.charAt(0); System.out.println("First character: " + firstChar); char lastChar = str.charAt(str.length() - 1); System.out.println("Last character: " + lastChar); } }
Output
: First character: I Last character: i === Code Execution Successful ===