Microsoft Word Document

traderainΛογισμικό & κατασκευή λογ/κού

15 Αυγ 2012 (πριν από 5 χρόνια και 3 μήνες)

328 εμφανίσεις

Programming in Java with NetBeans

The StringBuilder Class

One of the odd things about java is that a lot of stuff goes on behind the scenes that
doesn’t often show itself. For example, did you know that when you assign a String a
value in java that you ca
n’t change that value?


String s1= “Welcome”;

s1 = s1 + “ to Thornhill”;

This actually creates a new instance of the String object and this can create memory
issues. Now most of the time you can get away with doing what is above but since we
to do things correctly there is a better and more secure way to do this.

String Builders

The StringBuilder is a class with a bunch of methods that allows us to make big long
combined Strings.

StringBuilder sb = new StringBuilder(s1);

//then we append to
it to add more strings

sb.append(“ to Thornhill”);

The StringBuilder instance (sb) will now have both “Welcome “ and “ to Thornhill”

added into it. So in essence you build a string by adding other strings into the
StringBuilder instance.