Re: Newbie String Questions



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
.



Relevant Pages

  • Re: Bernsteins Haydn Paris Symphonies
    ... this case with the huge string section, ... justification for the winds being somewhat recessed. ... doubled winds - the combined forces of O18thC and OAE. ... The difference in volume might be subtle but I think the difference in articulation and clarity wouldn't be subtle at all. ...
    (rec.music.classical.recordings)
  • Re: Newbie String Questions
    ... Why is there a String constructor? ... Yes, there is a difference, but it is very subtle. ... Oliver ...
    (comp.lang.java.programmer)
  • Re: Programmers unpaid overtime.
    ... > Perhaps, but this is the first time I have seen it used on Usenet, ... > practical example (which will compile) and your alternative that is ... call Split on that string, perhaps multiple times, within loops, while ... I gather EGN and John Nash both see "developers" no one else can see. ...
    (comp.programming)
  • First Major Guitar Tech Job
    ... Well it's not a tour or anything but I guitar teched for my friends ... It wasn't the first time but it was the first time I ... and I brought my Les Paul Studio for a backup. ... where you string the strings backwards and first song the low E pulled ...
    (alt.guitar)
  • Re: Action Settings work on Windows, but not Mac
    ... convert the result back to string. ... the first time you click on the link and invoke the macro. ... Steve Rindsberg, PPT MVP ...
    (microsoft.public.powerpoint)