-1

The result of this code:

public class Test {
    public static void main(String[] args) {
        String s = "Java";
        s.concat(" SE 6");
        s.replace('6', '7');
        System.out.print(s);
    }
}

will be "Java" Who can tell me how many instances of String will be created during execution?

Ruslan Lomov
  • 485
  • 1
  • 7
  • 20
  • 1
    Strings are immutable in Java. I believe three – walkerrandophsmith Sep 15 '15 at 15:32
  • @WalkerRandolphSmith actually 4, you're creating 2 new strings at `s.concat(" SE 6");` the resulting `"Java SE 6"` and the `" SE 6"` – Jordi Castilla Sep 15 '15 at 15:36
  • `concat` and `replace` returns new stirngs, and you already have `"Java"` and `" SE 6"` strings. – Pshemo Sep 15 '15 at 15:38
  • stop minusing my question lol – Ruslan Lomov Sep 15 '15 at 15:39
  • @JordiCastilla good catch. I didn't think about that. – walkerrandophsmith Sep 15 '15 at 15:39
  • @RuslanLomov this is one of the tipical questions in SO, you have every day a *how many strings will be created here???*, with *why this overriden method is not getting called??* joined to *how to parse this date with format `xxxxYYYYzzzz`???* if you don't make a research expect downvotes – Jordi Castilla Sep 15 '15 at 15:46
  • 1
    It almost certainly depends on the internal implementation of `replace`... – Louis Wasserman Sep 15 '15 at 16:21
  • It also depends whether the optimizer is smart enough to determine that the `concat` and `replace` calls can be optimized away. And the internal implementation of `print` and the output stack – Stephen C Sep 15 '15 at 16:27
  • And it what you mean by "during execution". – Stephen C Sep 15 '15 at 16:29
  • there are always people that will point you somewhere else but not with the help answer! Too much ambitions i would say.If you don't understand the question or if you don't want to answer it just skip it. Don't tell other people what they should do, it is there own choice.Thanks alot to the people that make their sentence to help resolve a problem – Ruslan Lomov Sep 15 '15 at 17:55

1 Answers1

4

String is immutable in Java. Though you are invoking methods on it, they returns a new string each time.

There are 4 instance created here in this case

Please follow the comments:

    String s = "Java";   // 1
    s.concat(" SE 6");   // 2 & 3 for concat method returns a new string  and  another literal created " SE 6"
    s.replace('6', '7'); // 4 returns a new string instance  which you are not receiving
    System.out.print(s);
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307