GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing codescracker.com — Java Program to Copy String
Java Program to Copy StringThis 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 JavaThe 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: Copy String using StringBuffer Class in JavaTo 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 JavaThis 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 JavaTo 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« Previous Program Next Program » Practice Quizzes
Test your programming and computer science knowledge with interactive MCQs and topic-based quizzes. Popular Topics
Explore the most popular programming and computer science tutorials on CodesCracker. |
| You are visitor 01402503 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |