Page 1 of 1

About Question enthuware.ocajp.i.v7.2.941 :

Posted: Thu May 29, 2014 3:54 am
by Dan Lee
Am I correct, if like below

String abc = "";     
String def = abc.concat("abc");          
System.out.print(def);

then the output is abc?

Re: About Question enthuware.ocajp.i.v7.2.941 :

Posted: Thu May 29, 2014 4:15 am
by admin
I can tell you the answer, but you should try it out yourself by compiling and running it. If you don't understand the output, then post a question here.

thank you,
Paul.

Re: About Question enthuware.ocajp.i.v7.2.941 :

Posted: Fri Nov 10, 2017 3:18 pm
by SeoaneR
Hi there
When i type out the following code
String abc = " ";
abc.concat("abc");
abc.concat("def");
System.out.println(abc);
I get a blank reply

whereas the answer says i should get abcdef
I assumed that String was immutable .
If I type out System.out.println((abc.concat("abc"))+(abc.concat("def"))); i get a reply abcdef

I find the question a bit confusing... please advise

Re: About Question enthuware.ocajp.i.v7.2.941 :

Posted: Fri Nov 10, 2017 9:43 pm
by admin
No, the answer says, "It will print empty string (or in other words, nothing)."

Why do you think the question is confusing? It shows a piece of code and expects you to find out what will be printed.

You are right about String being immutable. That is the reason abc.concat("abc") doesn't modify the string referred to by the variable abc. The concat method returns a new String object that contains "abc".

That is why when you do (abc.concat("abc"))+(abc.concat("def")), you are basically using the two new String objects "abc" and "def" (created by the concat methods) and to create yet another new String containing "abcdef" using the + operator.