-5

I please check the code below.

I can understand that String s1 is not assigned and so even though concat(string) method is used it is giving the original output.

But also, in case of String s2 no variable is assigned but concatenation worked.

Can someone please explain?

package com.stringconcat.main;

public class StringConcat {

    public static void main(String[] args) {

        String  s1 = "Hello";
        s1.concat(" World");
        System.out.println("String s1 output: " + s1);

        String s2 = "Hello" /*s1*/;
        System.out.println("String s2 output: " + s2.concat(" World"));
    }
}

The outputs are: String s1 output: Hello String s2 output: Hello World

4
  • 1
    System.out.println("String s2 output: " + s2.concat(" World")); is basically String temp1 = "String s2 output: "; String temp2 = s2.concat(" World "); System.out.println(temp1 + temp2);.
    – Pshemo
    Sep 7, 2018 at 9:47
  • Thanks man !! Sorry, my bad, I missed it !! Sep 7, 2018 at 9:52
  • OK GUYS!!! MY BAD, MY MISTAKE !! I AM SORRY THAT I MISSED IT AND THANKS TO THOSE WONDERFUL PEOPLE WHO JUST CARED TO CLEAR CONFUSION AND HELP AS MUCH AS THEY CAN ! IF ANYONE IS ANNOYED I APOLOGIZE AGAIN. IF THAT DOESN'T HELP GO HELP YOURSELF! Sep 7, 2018 at 9:59
  • 1
    @AbhiroopNandiRay remove this comment, seriously. you will get flagged and most probably removed from stackoverflow and besides this is rude... like super rude
    – Eugene
    Sep 7, 2018 at 10:07

3 Answers 3

2

Because in the second case you are concatenating the result of s2.concat(" World") to "String s2 output: ", you are not ignoring it.

2
  • Thank you !!! Sorry I missed it !! Sep 7, 2018 at 9:48
  • 1
    @AbhiroopNandiRay it's ok...
    – Eugene
    Sep 7, 2018 at 9:49
0

Concat returns a new instance of String containing the concatenated strings. You just drop this concatenated version by not assigning it to a variable.

1
  • I already got the answer from some good person. Thanks for whatever you wanted to say. Sep 7, 2018 at 9:48
0

It's because s1 is Hello while s2.concat(" World") is another string object with concatenated string as Hello World. concat#string method always return new instance of string object with concatenated string to it.

Not the answer you're looking for? Browse other questions tagged or ask your own question.