Java how to copy a string

Java how to copy a string

To copy a string in Java, you can use the String class's copyValueOf method or the String class's valueOf method.

Here is an example of how to use the copyValueOf method to copy a string:

String original = "Hello, World!";
char[] characters = original.toCharArray();
String copy = String.copyValueOf(characters);
System.out.println(copy); // "Hello, World!"
Source:w‮w‬w.lautturi.com

In this example, the original string is first converted to an array of characters using the toCharArray method. The copyValueOf method is then used to create a new string from the character array. The resulting string is printed to the console using the println method of the System.out object.

Here is an example of how to use the valueOf method to copy a string:

String original = "Hello, World!";
String copy = String.valueOf(original);
System.out.println(copy); // "Hello, World!"

In this example, the valueOf method is used to create a new string from the original string. The resulting string is printed to the console using the println method of the System.out object.

Both of these examples will output the string "Hello, World!" to the console, which is a copy of the original string.

Note that in Java, strings are immutable, which means that they cannot be modified once created. When you copy a string, you are creating a new string object with the same value as the original string. Any changes made to the copy will not affect the original string.

Created Time:2017-11-03 22:21:04  Author:lautturi