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

Moderator: admin

Post Reply
Dan Lee
Posts: 4
Joined: Tue May 20, 2014 12:41 am
Contact:

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

Post by Dan Lee » Thu May 29, 2014 3:54 am

Am I correct, if like below

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

then the output is abc?

admin
Site Admin
Posts: 7412
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

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

Post by admin » Thu May 29, 2014 4:15 am

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.
If you like our products and services, please help us by posting your review here.

SeoaneR
Posts: 7
Joined: Tue Nov 07, 2017 8:23 am
Contact:

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

Post by SeoaneR » Fri Nov 10, 2017 3:18 pm

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

admin
Site Admin
Posts: 7412
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

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

Post by admin » Fri Nov 10, 2017 9:43 pm

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.
If you like our products and services, please help us by posting your review here.

Post Reply

Who is online

Users browsing this forum: No registered users and 6 guests