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 the string must be received by user at run-time. 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 above program, with user input codes and cracker as first and second string to swap:

Java Program swap two strings

Same Program in Other Languages

Java Online Test

« Previous Program Next Program »

Follow/Like Us on Facebook

Subscribe Us on YouTube