Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Java copyValueOf() Method

Java copyValueOf() Method

Java String ClassJava String class


In Java, copyValueOf(char[] data) is a static method of the String class. It copies all the characters from the specified character array into a new character array and returns a new string. This method is very similar to the valueOf(char[] data) method in the String class, but it returns a new character array instead of using the characters in the input array to create a new string object.

The copyValueOf(char[] data) method has two overloaded forms, one of which allows you to specify the starting position and the number of characters to copy from the input array:

Syntax


public static String copyValueOf(char[] data)

或

public static String copyValueOf(char[] data, int offset, int count)

Parameters

Return Value

Returns a string representing the character sequence in the specified array.

Example

Example

public

class

Test

{

public

static

void

main

(

String

args

[

]

)

{

char

[

]

Str1

=

{

'

h

'

,

'

e

'

,

'

l

'

,

'

l

'

,

'

o

'

,

'

'

,

'

r

'

,

'

u

'

,

'

n

'

,

'

o

'

,

'

o

'

,

'

b

'

}

;

String

Str2

=

"

"

;

Str2

=

Str2

.

copyValueOf

(

Str1

)

;

System

.

out

.

println

(

"

Return result:

"

Str2

)

;

Str2

=

Str2

.

copyValueOf

(

Str1

,

2

,

6

)

;

System

.

out

.

println

(

"

Return result:

"

Str2

)

;

}

}

Str2.copyValueOf( Str1 ); uses the entire input character array to create a new string object.

Str2.copyValueOf( Str1, 2, 6 ); starts from the 3rd character of the input character array (i.e., offset 2), copies 6 characters, and creates a new string object.

**Note:**offset and count The value of the parameter must not exceed the bounds of the input character array, otherwise a ArrayIndexOutOfBoundsException exception.

The execution result of the above program is:


返回结果:hello runoob
返回结果:llo ru

Java String ClassJava String class