Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No reverse method in String class in Java?

Why there is no reverse method in String class in Java? Instead, the reverse() method is provided in StringBuilder? Is there a reason for this? But String has split(), regionMatches(), etc., which are more complex than the reverse() method.

When they added these methods, why not add reverse()?

like image 654
Pradeep Kumar Avatar asked Sep 14 '11 17:09

Pradeep Kumar


2 Answers

Since you have it in StringBuilder, there's no need for it in String, right? :-)

Seriously, when designing an API there's lots of things you could include. The interfaces are however intentionally kept small for simplicity and clarity. Google on "API design" and you'll find tons of pages agreeing on this.

Here's how you do it if you actually need it:

str = new StringBuilder(str).reverse().toString();
like image 58
aioobe Avatar answered Oct 20 '22 00:10

aioobe


Theoretically, String could offer it and just return the correct result as a new String. It's just a design choice, when you get down to it, on the part of the Java base libraries.

like image 29
Sajid Avatar answered Oct 19 '22 23:10

Sajid