Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reason for using CharSequence as parameter in String replace method

Tags:

java

Is there a logical explanation why some methods in String class have parameters with CharSequence type and others with String type? For example:

public String replace(CharSequence target, CharSequence replacement)

and

public boolean startsWith(String prefix)

Why replace method does not use String for its parameters just like startsWith method does?

like image 481
bridgemnc Avatar asked Mar 03 '23 08:03

bridgemnc


1 Answers

Is there a logical explanation why some methods in String class have parameters with CharSequence type and others with String type?

Short answer: Backwards compatibility.

CharSequence was added in Java 1.4.

replace(CharSequence target, CharSequence replacement) was added in Java 1.5, so it could use the already existing CharSequence type.

startsWith(String prefix) has existed since Java 1.0, so it couldn't use the non-existing CharSequence type at the time, and couldn't be modified in Java 1.4 (or later) because that would cause backwards compatibility issues.

Why replace method does not use String for its parameters just like startsWith method does?

So you can pass other types of objects which implement CharSequence.

like image 80
Andreas Avatar answered Apr 26 '23 17:04

Andreas