Skip to main content

ProwessApps

Learn · Practice · Excel

Java Program to copy one string to another.

Java Code Example — String Programs

ADVERTISEMENT

Java Program to copy one string to another.

Objective

Write a Java program to copy the contents of one string to another.

Algorithm / Approach

  1. Read a string from the user using Scanner.nextLine() and store it in s1.
  2. Declare a new string variable s2.
  3. Assign the value of s1 to s2 using the assignment operator (=).
  4. Print the copied string s2.
Test.java
import java.util.Scanner;
class Test {
 public static void main(String[] a)
 {
  Scanner s=new Scanner(System.in);
  System.out.print("Enter String: ");
  String s1=s.nextLine();
  String s2=s1;
  System.out.print("Copied String: "+s2);
 }
}

Expected Output

Enter String: Java Prowess
Copied String: Java Prowess

Explanation of the Program

  • Unlike C/C++ where copying a string requires iterating through character arrays or using strcpy(), Java handles string assignment seamlessly.
  • Since Strings are immutable in Java, assigning s1 to s2 makes both references point to the same string object in the String Pool.
  • If you modify s1 later, a brand new string object is created, leaving s2 safely holding the original copied value.

Complexity

Time Complexity O(1)
Space Complexity O(1)
ADVERTISEMENT