Java Program to Copy a String

  • Java program to find length of a sting using length method.

In this java program, to copy a string we will first ask user to enter a string and store it in an String object "str". Then to copy a string we will create a new Object of String class by passing str to constructor method of String class. The new string object will contain the same set of character sequence as in original input string.

For Example,
Input String : Apple
Copied String : Apple

Java program to copy a string

In this java program, we first ask user to enter a string and then store it in String object "str". Then we copy the input string by creating a new String object "copy" which is initialized with "str".

package com.tcc.java.programs;

import java.util.Scanner;

/**
 * Java Program to Copy a String
 */
public class CopyString {
    public static void main(String args[]) {
        String str, copy;
        Scanner scanner = new Scanner(System.in);

        System.out.println("Enter a String");
        str = scanner.nextLine();
        // Copying str string to copy string
        copy = new String(str);

        System.out.println("Input String : " + str);
        System.out.println("Copied String : " + copy);
    }
}
Output
Enter a String
Tech Crash Course
Input String : Tech Crash Course
Copied String : Tech Crash Course

Recommended Posts
Java Program to Concatenate Two Strings
Java Program to Find Length of a String
Java Program to Delete All Spaces from a String
Java Program to Reverse a String
Java Program to Count Words in a Sentence
Java Program to Check Whether two Strings are Equal or Not
Java Program to Delete a Word from Sentence
Java Program to Reverse Sequence of Words of a Sentence
Java Program to Check Two Strings are Anagram or Not
Java Program to Delete all Vowel Characters from String
Java Program to Print Pascal Triangle
All Java Programs