18

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()?

Rob Hruska
  • 118,520
  • 32
  • 167
  • 192
Pradeep Kumar
  • 471
  • 2
  • 6
  • 14
  • 5
    Stretching your logic, someone can argue and request for all methods of StringUtils to be made part of String. API's should be designed to provide with the bare bone structure so that other libraries can be built on top of it. – Scorpion Sep 14 '11 at 17:33
  • 3
    Maybe because of all "real world" uses of `reverse` being homework? Maybe not exactly, but it's hard to find what it should be good for. – maaartinus Oct 03 '14 at 13:27

7 Answers7

31

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();
aioobe
  • 413,195
  • 112
  • 811
  • 826
  • 3
    I like this answer, but the String API is hardly small as it is. – Adrian Mouat Sep 14 '11 at 17:32
  • 1
    Hehe, true. That's just yet an argument to leave methods such as reverse out though :-) – aioobe Sep 14 '11 at 17:33
  • 6
    They made a very conscious effort to keep the String api small and simple. It still ended up with 15 constructors and 52 methods. Imagine if they had not tried so hard to keep it simple?! – corsiKa Sep 14 '11 at 17:35
3

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.

Sajid
  • 4,381
  • 20
  • 14
1

If you want an historical reason, String are immutable in Java, that is you cannot change a given String if not creating another String.

While this is not bad "per se", initial versions of Java missed classes like StringBuilder. Instead, String itself contained (and still contains) a lot of methods to "alter" the String but since String is immutable, each of these methods actually creates and return a NEW String object.

This caused simple expressions like :

String s = "a" + anotherString.substr(10,5).trim().toLowerCase();

To actually create in ram something like 5 strings, 4 of which are absolutely useless, with obvious performance problems (despite after there has been some optimizations regarding underlying char[] arrays).

To solve this, Sun introduced StringBuilder and other classes that ARE NOT immutable. These classes freely modify a single char[] array, so that calling methods does not need to produce many intermediate String instances.

They added "reverse" quite lately, so they added it to StringBuilder instead of String, cause that's now the preferred way to manipulate strings.

Simone Gianni
  • 11,426
  • 40
  • 49
  • 11
    Immutability is a non argument. String has also `toUpperCase()` and like which just returns a brand new String instance. A fictive `reverse()` could have done the same. – BalusC Sep 14 '11 at 17:40
  • 6
    *While this is not bad "per se", initial versions of Java missed classes like StringBuilder.* -- Uhm, [`StringBuffer`](http://download.oracle.com/javase/6/docs/api/java/lang/StringBuffer.html) (the mutable version of `String`) has existed since Java 1.0! – aioobe Sep 14 '11 at 17:40
  • Yes, sure, but they moved from "creating new instances" to "use a mutable class", that's the historical reason. Not that they couldn't have added that method to String as well. – Simone Gianni Sep 14 '11 at 17:41
  • 2
    When did they "move" to "use mutable classes"? `String` was not deprecated last time I checked. :-) – aioobe Sep 14 '11 at 17:46
0

As a side-note, in Scala you use the same java.lang.String class and you do get a reverse method (along with all kinds of other handy stuff). The way it does it is with implicit conversions, so that your String gets automatically converted into a class that does have a reverse method. It's really quite clever, and removes the need to bloat the base class with hundred of methods.

Luigi Plinge
  • 50,650
  • 20
  • 113
  • 180
-1

String is immutable, meaning it can't be changed.

When you reverse a String, what's happening is that each letter is switched on it's own, means it will always create the new object each times.

Let us see with example: This means that for instance Hello becomes as below

  • elloH lloeH loleH olleH

and you end up with 4 new String objects on the heap. So think if you have thousands latter of string or more then how much object will be created.... it will be really a very expensive. So too much memory will be occupied.

So because of this String class not having reverse() method.

Manish Kumar
  • 227
  • 4
  • 9
  • 3
    No. One could transfer all characters to a `char[]` array, reverse the array, then create a String from the resulting array. No intermediade String objects required. – aioobe Jun 27 '16 at 07:37
  • Isn't this the case with other methods like toUpperCase etc? – Saurabh Tiwari Aug 13 '21 at 18:59
-2

Well I think it could be because it is an immutable class so if we had a reverse method it would actually create a new object.

Amanpreet
  • 526
  • 3
  • 12
  • thats not the reason, there are tons of methods that mutate `String` obj. see here http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/lang/String.java#String.matches%28java.lang.String%29 – roottraveller Jul 11 '17 at 13:03
-3

reverse() acts on this, modifying the current object, and String objects are immutable - they can't be modified.

It's peculiarly efficient to do reverse() in situ - the size is known to be the same, so no allocation is necessary, there are half as many loop iterations as there would be in a copy, and, for large strings, memory locality is optimal. From looking at the code, one can see that a lot of care was taken to make it fast. I suspect the author(s) had a particular use case in mind that demanded high performance.

Ed Staub
  • 15,480
  • 3
  • 61
  • 91
  • 8
    That's not the reason. You could very well return a copy of the string. Many immutable data structures have such "manipulation"-methods. – aioobe Sep 14 '11 at 17:31
  • 3
    @Ed Staub: What you say is true. However, the hypothetical `String.reverse()` could *return* the result. – NPE Sep 14 '11 at 17:32
  • 3
    @Ed Staub, Compare with the `replace` methods for instance. – aioobe Sep 14 '11 at 17:39