Am I correct, if like below
String abc = "";
String def = abc.concat("abc");
System.out.print(def);
then the output is abc?
About Question enthuware.ocajp.i.v7.2.941 :
Moderator: admin
-
- Posts: 4
- Joined: Tue May 20, 2014 12:41 am
- Contact:
-
- Site Admin
- Posts: 10058
- Joined: Fri Sep 10, 2010 9:26 pm
- Contact:
Re: About Question enthuware.ocajp.i.v7.2.941 :
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.
thank you,
Paul.
If you like our products and services, please help us by posting your review here.
-
- Posts: 8
- Joined: Tue Nov 07, 2017 8:23 am
- Contact:
Re: About Question enthuware.ocajp.i.v7.2.941 :
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
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
-
- Site Admin
- Posts: 10058
- Joined: Fri Sep 10, 2010 9:26 pm
- Contact:
Re: About Question enthuware.ocajp.i.v7.2.941 :
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.
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.
Who is online
Users browsing this forum: No registered users and 87 guests