w3resource

Java: Create a new string from a given string swapping the last two characters of the given string


57. Swap Last Two Characters

Write a Java program to create a string from a given string by swapping the last two characters of the given string. The string length must be two or more.

Visual Presentation:

Java String Exercises: Create a new string from a given string swapping the last two characters of the given string.


Sample Solution:

Java Code:

import java.util.*;

// Define a class named Main
public class Main {
    
    // Method to swap the last two characters of a string
    public String lastTwo(String str) {
        // Check if the string has less than two characters, return the string as is
        if (str.length() < 2) return str;
        
        // Swap the last two characters of the string and return the modified string
        return str.substring(0, str.length() - 2) + str.charAt(str.length() - 1) + str.charAt(str.length() - 2);
    }

    // Main method to execute the program
    public static void main(String[] args) {
        Main m = new Main(); // Create an instance of the Main class

        // Define a string for swapping the last two characters
        String str1 = "string";

        // Display the given string and the string after swapping its last two characters using the lastTwo method
        System.out.println("The given string is: " + str1);
        System.out.println("The string after swapping the last two characters is: " + m.lastTwo(str1));
    }
}

Sample Output:

The given strings is: string
The string after swap last two characters are: strign

Flowchart:

Flowchart: Java String Exercises - Create a new string from a given string swapping the last two characters of the given string.


For more Practice: Solve these Related Problems:

  • Write a Java program to swap the last two characters of a string and handle edge cases for minimal length.
  • Write a Java program to interchange the final two characters and validate the swap against the original string.
  • Write a Java program to swap the last two characters using substring manipulation techniques.
  • Write a Java program to create a new string by swapping the last two characters, then output its reverse.

Go to:


PREV : Append Strings Without Double Characters.
NEXT : Ends With Specific Two Characters.

Java Code Editor:

Improve this sample solution and post your code through Disqus

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.