Given a string str, the task is to print the first and the last character of the string.
Examples:
Input: str = “GeeksForGeeks” Output: First: G Last: s Explanation: The first character of the given string is ‘G’ and the last character of given string is ‘s’. Input: str = “Java” Output: First: J Last: a Explanation: The first character of given string is ‘J’ and the last character of given string is ‘a’.
Below is the implementation of the above approach:
// Java program to find first // and last character of a string class GFG { // Function to print first and last // character of a string public static void firstAndLastCharacter(String str) { // Finding string length int n = str.length(); // First character of a string char first = str.charAt(0); // Last character of a string char last = str.charAt(n - 1); // Printing first and last // character of a string System.out.println("First: " + first); System.out.println("Last: " + last); } // Driver Code public static void main(String args[]) { // Given string str String str = "GeeksForGeeks"; // Function Call firstAndLastCharacter(str); } }
Output:
First: G Last: s
Below is the implementation of the above approach:
// Java program to find first // and last character of a string class GFG { // Function to print first and last // character of a string public static void firstAndLastCharacter(String str) { // Converting a string into // a character array char[] charArray = str.toCharArray(); // Finding the length of // character array int n = charArray.length; // First character of a string char first = charArray[0]; // Last character of a string char last = charArray[n - 1]; // Printing first and last // character of a string System.out.println("First: " + first); System.out.println("Last: " + last); } // Driver Code public static void main(String args[]) { // Given string str String str = "GeeksForGeeks"; // Function Call firstAndLastCharacter(str); } }
Output:
First: G Last: s
Australia
UK
UAE
Singapore
Canada
New
Zealand
Malaysia
USA
India
South
Africa
Ireland
Saudi
Arab
Qatar
Kuwait
Hongkong
Copyright 2016-2023 www.programmingshark.com - All Rights Reserved.
Disclaimer : Any type of help and guidance service given by us is just for reference purpose. We never ask any of our clients to submit our solution guide as it is, anywhere.