Java Program to copy one string to another.
Objective
Write a Java program to copy the contents of one string to another.
Algorithm / Approach
- Read a string from the user using
Scanner.nextLine()and store it ins1. - Declare a new string variable
s2. - Assign the value of
s1tos2using the assignment operator (=). - 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
s1tos2makes both references point to the same string object in the String Pool. - If you modify
s1later, a brand new string object is created, leavings2safely holding the original copied value.
Complexity
Time Complexity
O(1)
Space Complexity
O(1)