Java program to swap first and last character of a string

Java program to swap first and last character of a string :

In this tutorial, we will learn how to swap the first and last character in Java. The user will enter one string, our program will swap the first and last character of that string and print out the result. Let’s take a look at the program first :

Java Program :

import java.util.Scanner;

public class Main {

    private static String swapCharacters(String inputString) {

        int length = inputString.length();

        if (length <= 1) {
            return inputString;
        } else {
            return inputString.charAt(length - 1) + inputString.substring(1, length - 1) + inputString.charAt(0);

    public static void main(String[] args) {
        Scanner scanner = new Scanner(;

        System.out.println("Enter a string : ");

        String userInput =;

        System.out.println("Output String : " + swapCharacters(userInput));



Explanation :

The commented numbers in the above program denote the step number below :

1. Create one Scanner object to get the user input string.
2. Ask the user to enter a string.
3. Get the input from the user and save it in the variable userInput .
4. To swap first and last character of a string, we are calling swapCharacters function. It takes one string as input and returns one string .
5. Calculate the length of the string and save it in variable length.
6. Check if the length is less than or equal to 1. If yes, return the same String. For a string of length 1, the output will be same.
7. Else, create one string by taking the last character + substring excluding the first and last character + first character and return this string.

charAt(int index) method returns the character at index position index. subString(int beginIndex,int endIndex) function returns one substring starting from index beginIndex and ends at index endIndex.

Sample Output :

Enter a string : 
Output String : oellH

Enter a string : 
Output String : dorlw

Enter a string : 
Output String : toot

Leave a Reply