Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on String
  • Practice String
  • MCQs on String
  • Tutorial on String
  • String Operations
  • Sort String
  • Substring & Subsequence
  • Iterate String
  • Reverse String
  • Rotate String
  • String Concatenation
  • Compare Strings
  • KMP Algorithm
  • Boyer-Moore Algorithm
  • Rabin-Karp Algorithm
  • Z Algorithm
  • String Guide for CP
Open In App
Next Article:
Capitalize the First Letter of a String in Java
Next article icon

How to find the first and last character of a string in Java

Last Updated : 13 Dec, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

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’.

Method 1: Using String.charAt() method

  • The idea is to use charAt() method of String class to find the first and last character in a string. 
  • The charAt() method accepts a parameter as an index of the character to be returned.
  • The first character in a string is present at index zero and the last character in a string is present at index length of string-1.
  • Now, print the first and last characters of the string.

Below is the implementation of the above approach: 

Java




// 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 

Method 2: Using String.toCharArray() method

  • The idea is to first convert the given string into a character array using toCharArray() method of String class, then find the first and last character of a string and print it.

Below is the implementation of the above approach: 

Java




// 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 

Time complexity: O(1)
Auxiliary space: O(n) because it is using extra space for charArray



Next Article
Capitalize the First Letter of a String in Java
author
prashant_srivastava
Improve
Article Tags :
  • DSA
  • Java Programs
  • Strings
  • Java-String-Programs
Practice Tags :
  • Strings

Similar Reads

  • Remove first and last character of a string in Java
    Given a string str, the task is to write the Java Program to remove the first and the last character of the string and print the modified string. Examples: Input: str = "GeeksForGeeks"Output: "eeksForGeek"Explanation: The first and last characters of the given string are 'G' and 's' respectively. Af
    5 min read
  • How to Convert a String to a Character in Java?
    String and char are fundamental and most commonly used datatypes in Java. A String is not a primitive data type like char. To convert a String to char in Java, we have to perform character-based operations or have to process individual characters. In this article, we will learn how to convert a Stri
    3 min read
  • Capitalize the first and last character of each word in a string
    Given the string, the task is to capitalise the first and last character of each word in a string.Examples: Input: Geeks for geeks Output: GeekS FoR GeekS Input: Geeksforgeeks is best Output: GeeksforgeekS IS BesT Approach Create a character array of the StringRun a loop from the first letter to the
    6 min read
  • Java program to swap first and last characters of words in a sentence
    Write a Java Program to Swap first and last character of words in a Sentence as mentioned in the example? Examples: Input : geeks for geeks Output :seekg rof seekg Approach:As mentioned in the example we have to replace first and last character of word and keep rest of the alphabets as it is. First
    2 min read
  • Capitalize the First Letter of a String in Java
    In Java, to check if a String contains only uppercase letters, we can use many approaches. These approaches verify each character in the String to ensure they are all in uppercase. A simple method, such as iterating through the characters and checking their case. In this article, we will discuss how
    4 min read
  • Iterate Over the Characters of a String in Java
    Given string str of length N, the task is to traverse the string and print all the characters of the given string. Illustration: Input : “GeeksforGeeks” Output : G e e k s f o r G e e k sInput. : “Coder” Output : C o d e r Methods: Using Naive ApproachUsing String.toCharArray() methodUsing Character
    9 min read
  • Convert a String to Character Array in Java
    Converting a string to a character array is a common operation in Java. We convert string to char array in Java mostly for string manipulation, iteration, or other processing of characters. In this article, we will learn various ways to convert a string into a character array in Java with examples.
    2 min read
  • Java Program to Add Characters to a String
    We will be discussing out how to add character to a string at particular position in a string in java. It can be interpreted as follows as depicted in the illustration what we are trying to do which is as follows: Illustration: Input: Input custom string = HelloOutput: --> String to be added 'Gee
    5 min read
  • Find the first element of a Stream in Java
    Given a stream containing some elements, the task is to get the first element of the Stream in Java. Example: Input: Stream = {"Geek_First", "Geek_2", "Geek_3", "Geek_4", "Geek_Last"} Output: Geek_First Input: Stream = {1, 2, 3, 4, 5, 6, 7} Output: 1 There are many methods to the find first elements
    3 min read
  • Java Program to Separate the Individual Characters from a String
    The string is a sequence of characters including spaces. Objects of String are immutable in java, which means that once an object is created in a string, it's content cannot be changed. In this particular problem statement, we are given to separate each individual characters from the string provided
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences