0
String str = new String("javaTrain") ;  /*new object1  in heap memory */

System.out.println(str ==  str.substring(0) )   ==> return true ??

why the result is true ?

str.substring(0) ==> /*new object2 in heap memory   */

why objet1 and object2 are equals ?

Dave Newton
  • 158,873
  • 26
  • 254
  • 302
  • 5
    Why shouldn't they be? Who promised you that `substring(0)` should create a new object? See [the docs](https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#substring-int-) - the method returns "a string", not "a new string". – kaya3 Sep 01 '21 at 11:11
  • 4
    I'm going to go further and say that you have a misunderstanding of _what you need to care about_. Except in _vanishingly rare_ situations, you don't need to care about a string's identity: you just have a string with the right (or wrong) contents. It doesn't matter if they are the same instance or not. – Andy Turner Sep 01 '21 at 11:14
  • String is immutable so using method substring will create a new copy of String ( new object ) - can you explain how this method is implemented in java 8 ? – thefirewall Sep 01 '21 at 11:15
  • 2
    "String is immutable so using method substring will create a new copy of String ( new object )" That's not true, as you've demonstrated here. – Andy Turner Sep 01 '21 at 11:15
  • 1
    That's a non-sequitur - being immutable means it doesn't matter whether it returns a new object or not, as long as the value is correct. – kaya3 Sep 01 '21 at 11:16
  • @thefirewall: as you demonstrated (and Andy Turner commented) that statement is false. A more correct one would be "String is immutable so using substring to return a *different string value* will create a new string object". `x.substring(0)` will always have the same content as `x`. – Joachim Sauer Sep 01 '21 at 11:17
  • I would add to JoachimSauer's comment: "`x.substring(0)` will always have the same content as `x`", and `x` is immutable, so there's no point in returning a copy of `x`. – Andy Turner Sep 01 '21 at 11:18
  • Note that `substring(0)` will return the same string as it doesn't make sense to create a copy of an immutable instance that has the exact same content. From the source code of `String substring(int beginIndex)`: `... if (beginIndex == 0) { return this; } ... ` – Thomas Sep 01 '21 at 11:18
  • yes ,the link above answer my question – thefirewall Sep 01 '21 at 11:19
  • They changed the description in the documentation: https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#substring-int- where originally was: https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#substring(int) They now (in Java 8) don't mention that a new string is created anymore. – César Ferreira Sep 01 '21 at 11:21
  • I checked the java.lang.String source code as far back as version 1.4.2 and the optimization was already part of that release. And this is not suprising - it is an easy optimization and completely safe. – Thomas Kläger Sep 01 '21 at 11:35

0 Answers0