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 {
//4
private static String swapCharacters(String inputString) {
//5
int length = inputString.length();
//6
if (length <= 1) {
return inputString;
} else {
//7
return inputString.charAt(length - 1) + inputString.substring(1, length - 1) + inputString.charAt(0);
}
}
public static void main(String[] args) {
//1
Scanner scanner = new Scanner(System.in);
//2
System.out.println("Enter a string : ");
//3
String userInput = scanner.next();
//8
System.out.println("Output String : " + swapCharacters(userInput));
}
}
Explanation :
The commented numbers in the above program denote the step number below :
-
Create one Scanner object to get the user input string.
-
Ask the user to enter a string.
-
Get the input from the user and save it in the variable userInput .
-
To swap first and last character of a string, we are calling swapCharacters function. It takes one string as input and returns one string .
-
Calculate the length of the string and save it in variable length.
-
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.
-
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 :
Hello
Output String : oellH
Enter a string :
world
Output String : dorlw
Enter a string :
toot
Output String : toot
Similar tutorials :
-
Java program to find the counts of each character in a String
-
Java program to print a rectangle using any special character
-
Java Program to find the last non repeating character of a string
-
Java program to count the occurrence of each character in a string
-
4 different ways to Sort String characters Alphabetically in Java