Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

String immutable? 2

Status
Not open for further replies.

chrissie1

Programmer
Aug 12, 2002
4,517
BE
In .net a string is immutable is it the same for java and how to concat the correct way?

Christiaan Baes
Belgium

I just like this --> [Wiggle] [Wiggle]
 
Yes, it is:
Simplest way to concat two Strings:

Code:
String one = "0ne";
String two = "two";
String oneplustwo = one + two;

Another way

Code:
String one = "0ne";
String two = "two";
String oneplustwo = one.concat(two);

The rigth way (performace issue)

Code:
String one = "0ne";
String two = "two";
StringBuffer oneplustwo = new StringBuffer(6);
oneplustwo.append(one);
oneplustwo.append(two);
String myFinalString = oneplustwo.toString();

Cheers,
Dian
 
Thanks.

Christiaan Baes
Belgium

I just like this --> [Wiggle] [Wiggle]
 
I would always use Dian's method one - its just the easiest and there are no problems doing it.

Similarly, if you have a primitive (int, double, char etc) that you want to convert to a String the easiest way is :

int i = 5;
String s = i +"";

--------------------------------------------------
Free Java/J2EE Database Connection Pooling Software
 
Yep, but like in .net, won't it create an overhead for example
forgive the syntax.

Code:
String oneplustwo;
oneplustwo += "one";
oneplustwo += " two";
oneplustwo += " three";
oneplustwo += " four";

would need 5 memoryallocations
while

Code:
StringBuffer oneplustwo = new StringBuffer(6);
oneplustwo.append("one");
oneplustwo.append("two");
oneplustwo.append("three");
oneplustwo.append("four");
String myFinalString = oneplustwo.toString();

this will only need two, give or take a one here and there.


Christiaan Baes
Belgium

I just like this --> [Wiggle] [Wiggle]
 
If you are appending lots of Strings, or several alrge Strings then a StringBuffer is the right approach.
But if its just something like :

String server = "localhost";
String port = "8080";
String serverPort = server +":" +port;

then I wouldn't other using a StringBuffer - you just won't see an overhead or differrence in such a case.


--------------------------------------------------
Free Java/J2EE Database Connection Pooling Software
 
I understand, thanks.

Christiaan Baes
Belgium

I just like this --> [Wiggle] [Wiggle]
 
Very interesting, thanks.

Christiaan Baes
Belgium

I just like this --> [Wiggle] [Wiggle]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top