Java Program to Copy String

This article covers multiple programs in Java that copies one string to another. Here are the list of programs included in this article:

Copy String without using Function in Java

The question is, write a Java program to copy string. The string to copy, must be received by user at run-time of the program. The program given below is its answer:

import java.util.Scanner;

public class CodesCracker
{
   public static void main(String[] args)
   {
      String strOrig, strCopy;
      Scanner scan = new Scanner(System.in);
      
      System.out.print("Enter the String: ");
      strOrig = scan.nextLine();
      
      strCopy = strOrig;
      
      System.out.println("\nstrOrig = " +strOrig);
      System.out.println("strCopy = " +strCopy);
   }
}

The snapshot given below shows the sample run of above program with user input codescracker:

java program copy string

Copy String using StringBuffer Class in Java

To copy string using StringBuffer class, just replaced the following statement, from above program:

strCopy = strOrig;

with the statement given below:

StringBuffer strCopy = new StringBuffer(strOrig);

Also from the statement:

String strOrig, strCopy;

remove strCopy variable, as the variable is declared and initialized using previous statement.

Copy String using valueOf() Method in Java

This program uses valueOf() method to do the same job, that is, of copying entered string into another variable.

import java.util.Scanner;

public class CodesCracker
{
   public static void main(String[] args)
   {
      Scanner scan = new Scanner(System.in);
      
      System.out.print("Enter the String: ");
      String strOrig = scan.nextLine();
      
      String strCopy = String.valueOf(strOrig);
      
      System.out.println("\nstrOrig = " +strOrig);
      System.out.println("strCopy = " +strCopy);
   }
}

Also the following statement, from above program:

String strCopy = String.valueOf(strOrig);

can also be replaced with the statement given below:

String strCopy = String.valueOf(strOrig.toCharArray(), 0, strOrig.length());

Copy String using copyValueOf() Method in Java

To copy string using copyValueOf() method, then only replace the following statement, from previous program:

String strCopy = String.valueOf(strOrig);

with:

String strCopy = String.copyValueOf(strOrig.toCharArray());

or

String strCopy = String.copyValueOf(strOrig.toCharArray(), 0, strOrig.length());

Same Program in Other Languages

Java Online Test


« Previous Program Next Program »


Liked this post? Share it!