Java Program to Swap Two Strings

This article covers a program in Java that swaps two strings, entered by user at run-time of the program.

Swap two strings in Java

The question is: write a Java program to swap two strings. Both strings must be received by the user at runtime. The program given below is its answer:

import java.util.Scanner;

public class CodesCracker
   public static void main(String[] args)
      String strOne, strTwo, strTemp;
      Scanner scan = new Scanner(;
      System.out.print("Enter the First String: ");
      strOne = scan.nextLine();
      System.out.print("Enter the Second String: ");
      strTwo = scan.nextLine();
      System.out.println("\nString before Swap:");
      System.out.println("strOne = " +strOne);
      System.out.println("strTwo = " +strTwo);
      strTemp = strOne;
      strOne = strTwo;
      strTwo = strTemp;
      System.out.println("\nString after Swap:");
      System.out.println("strOne = " +strOne);
      System.out.println("strTwo = " +strTwo);

The snapshot given below shows the sample run of the above program, with user input codes and cracker as the first and second strings to swap:

Java Program swap two strings

The program starts by declaring three string variables named "strOne," "strTwo," and "strTemp" and a "Scanner" object named "scan."

The program then prompts the user to input the first and second strings using the "Scanner" object's nextLine() method and assigns these values to the strOne and strTwo variables, respectively.

The program then prints out the original values of the two strings using the System.out.println() method.

The program swaps the values of the two strings using the temporary variable strTemp. This is done by assigning the value of strOne to strTemp, then assigning the value of strTwo to strOne, and finally assigning the value of strTemp to strTwo.

The program then prints out the swapped values of the two strings using the System.out.println() method.

Same Program in Other Languages

Java Online Test

« Previous Program Next Program »

Liked this article? Share it!

Like/follow us on social media for updates!