Re: Newbie String Questions
- From: Wesley Hall <noreply@xxxxxxxxxxx>
- Date: Tue, 28 Nov 2006 22:09:27 +0000
Dom wrote:
Anyone have some time to answer simple String questions?
1. Why is there a String (String) constructor? Is there any
difference between these statements:
a) -- String s = new String ("ABC");
b) -- String s = "ABC";
Yes, there is a difference, but it is very subtle.
String s1 = new String("ABC");
String s2 = "ABC";
System.out.println(s1 == "ABC"); //This will print false
System.out.println(s2 == "ABC"); //This will print true
This is because the first time a string literal is encountered a String
object is created behind the scenes. The second time it is encountered
the string object is reused, so s1 and "ABC" point to the same string
object and == returns true. However, by doing 'new String' you are
explicitly creating a new string instance so == returns false.
It is better to use literals as it prevents garbage collector churn in
collecting all the temporary strings.
2. Why is there a concat method? Is there any difference between
these statements:
a) -- s = s.concat ("ABC");
b) -- s = s + "ABC";
Functionally, there is no difference, although there are probably some
subtle things related to the above. I can't be bothered to think it
through right now :oP
.
- Follow-Ups:
- Re: Newbie String Questions
- From: Steve W. Jackson
- Re: Newbie String Questions
- References:
- Newbie String Questions
- From: Dom
- Newbie String Questions
- Prev by Date: Re: serialver?
- Next by Date: Re: How to update a jar file for one source file change?
- Previous by thread: Re: Newbie String Questions
- Next by thread: Re: Newbie String Questions
- Index(es):
Relevant Pages
|