Java Program to Swap Two Strings

Ramesh Fadatare
2 min readDec 13, 2024

--

Introduction

Swapping two strings is a common exercise to understand how variables work in programming. This task helps you to practice basic operations like assignment and the use of temporary variables in Java. This guide will walk you through writing a Java program that swaps the values of two strings.

Learn everything about Java: https://www.javaguides.net/

Problem Statement

Create a Java program that:

  • Prompts the user to enter two strings.
  • Swaps the values of the two strings.
  • Displays the strings after swapping.

Example:

  • Input: String 1: "Hello" String 2: "World"
  • Output: After swapping: String 1: "World" String 2: "Hello"

Solution Steps

  1. Read the Strings: Use the Scanner class to take two strings as input from the user.
  2. Swap the Strings: Use a temporary variable to hold one string while you assign the second string to the first, and then assign the temporary variable to the second.
  3. Display the Swapped Strings: Print the strings after swapping.
  4. Close Resources: Close the Scanner class object automatically using the try-resource statement.

Java Program

// Java Program to Swap Two Strings

import java.util.Scanner;

public class SwapStrings {
public static void main(String[] args) {
// Step 1: Read the strings from the user
try (Scanner scanner = new Scanner(System.in)) {
System.out.print("Enter the first string: ");
String string1 = scanner.nextLine();

System.out.print("Enter the second string: ");
String string2 = scanner.nextLine();

// Step 2: Swap the strings using a temporary variable
String temp = string1;
string1 = string2;
string2 = temp;

// Step 3: Display the swapped strings
System.out.println("After swapping:");
System.out.println("First string: " + string1);
System.out.println("Second string: " + string2);
}
}
}

Explanation

Step 1: Read the Strings

  • The Scanner class is used to read two string inputs from the user. The nextLine() method captures each line as a string.

Step 2: Swap the Strings

  • A temporary variable temp is used to hold the value of string1.
  • string1 is then assigned the value of string2.
  • Finally, string2 is assigned the value stored in temp.

Step 3: Display the Swapped Strings

  • The program prints the values of string1 and string2 after swapping, showing that their values have been exchanged.

Output

Enter the first string: Hello
Enter the second string: World
After swapping:
First string: World
Second string: Hello

Conclusion

This Java program demonstrates how to swap the values of two strings using a temporary variable. It covers basic concepts of variable manipulation and input/output operations, making it a useful exercise for beginners learning Java programming.

Learn everything about Java: https://www.javaguides.net/

--

--

No responses yet