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

Java Examples – Concatenating Strings

Java Example – Concatenate strings

Java Examples Java Examples

The following example demonstrates concatenating strings with the "+" operator and the StringBuffer.append() method, and compares their performance:

StringConcatenate.java file

public

class

StringConcatenate

{

public

static

void

main

(

String

[

]

args

)

{

long

startTime

=

System

.

currentTimeMillis

(

)

;

for

(

int

i

=

0

;

i

<

5000

;

i

++

)

{

String

result

=

"

This is

"

"

testing the

"

"

difference

"

"

between

"

"

String

"

"

and

"

"

StringBuffer

"

;

}

long

endTime

=

System

.

currentTimeMillis

(

)

;

System

.

out

.

println

(

"

String concatenation

"

"

"

(

endTime

startTime

)

"

ms

"

)

;

long

startTime1

=

System

.

currentTimeMillis

(

)

;

for

(

int

i

=

0

;

i

<

5000

;

i

++

)

{

StringBuffer

result

=

new

StringBuffer

(

)

;

result

.

append

(

"

This is

"

)

;

result

.

append

(

"

testing the

"

)

;

result

.

append

(

"

difference

"

)

;

result

.

append

(

"

between

"

)

;

result

.

append

(

"

String

"

)

;

result

.

append

(

"

and

"

)

;

result

.

append

(

"

StringBuffer

"

)

;

}

long

endTime1

=

System

.

currentTimeMillis

(

)

;

System

.

out

.

println

(

"

String concatenation

"

"

"

(

endTime1

startTime1

)

"

ms

"

)

;

}

}

The output of the above code example is:



字符串连接 - 使用 + 操作符 : 0 ms

字符串连接 - 使用 StringBuffer : 6 ms

Java Examples Java Examples