String, StringBuiler and StringBuffer
Autor: Gustavo | Publicado: 2015-04-13T10:30:00-03:00


&nbsp; &nbsp;I
will write this month about things I've already wrote in this blog.
The idea is to get used to write in this blog in English, once I've
already have posts written in Portuguese, translating it will giving
me time to become used to write in two languages. As I am done
translating and redoing all my pasts posts I will start new ones, but
if you prefer any subject in special, suggest here and I will be glad
to give preference to your mentioned post.

&nbsp; &nbsp;At
the end of this month o pretend to have redone all my principles
posts and so translated them. Today I will start writing about
String, StringBuilder and StringBuffer. Hope you enjoy. :-)

Critics
and suggestions are always welcome.

String,
StringBuilder and StringBuffer




&nbsp; &nbsp;The
first thing you need to know about Strings is that they will never
change their value.&nbsp;&nbsp; &nbsp;Once you created a String instance object, this
object will maintain with this value until its ends of life. Of
course we will say more about that but be already known.

&nbsp; &nbsp;String
is an object as everything in Java, and every object need to have its
reference to a variable if you want to use it in somewheres code. The
String Object has many different kinds of constructors it means that
you can declare and instantiate it in many different ways as you can
see in figure 1.









Figure-1




 

&nbsp; &nbsp;In
spite of having many different kinds of constructors to initialize a
String object, the most commonly used you will see are these two
here:




  String
var
= new
String();

  String
var1
= new
String("Let's
Surf!");




&nbsp; &nbsp;On
your daily work initialize your string variable can be much more
simpler, you are able to have other different way to start your
string variable as you can see down here:




  String
var
= "";

  String
var1
= "Let's
Surf!";




&nbsp; &nbsp;As I've already said, when we declare
and initialize an String Object, it'll never leave its value again,
but it doesn't mean that your variable should perform the same way
that a String object does. Actually what happens is that you change
the variable reference. Look at the code bellow and you will see
that, first it is pointing to some String object without text, as you
change its reference to another string, the old stay without
reference on your pool.




 String
var
= "
";

 var
= "Let's
Surf!";




&nbsp; &nbsp;Representing
this first line
of the code
in a graphical mode
could be like that:









&nbsp; &nbsp;Here
we have a square that represents our declared variable “var”, our
String object is drawn as a circle in the memory pool represented by
a cloud.

If
we continues reading our first code witch have only two lines we can
see the graphic bellow that represents when the code lines is
executed, we can notice what really happened with our heap, object
and its reference that changed as the second line was executed.









&nbsp; &nbsp;We
can say that our String object with the value “Let's Surf” was
not just created, but pointed to the variable “var”, that has
changed the other object reference created in line one of our code.
As this happened, the object that was created in line one, is lost on
our heap and will never be referenced to a new variable again. That's
the bad thing of working too much with Strings when you need to make
many changes on the string value. Your heap will have many lost
string objects that it won't be needed occupying space without
usability.

&nbsp; &nbsp;Getting
deeper a little bit about what I just said, look at this code down
here and imagine how simple and how many objects are created.




  String
var1
= new
String("Let's
Surf");



  String
var2
= "
In Rio";
//
attributing
value
“in
Rio” to
var2

  System.out.println(var2);
//
print:
In Rio

  var2
= var1+var2;//
attributing
value
of var1+var2
to
var2 again

  System.out.println(var2);//
Let's
Surf In Rio

  var2.concat("
Baby!");//
change
value without  giving its reference

  System.out.println(var2);//
print
value:
Let's Surf In Rio

  var2
= var2.concat("!");//
ok
now with its reference

  System.out.println(var2.toUpperCase());//uppper
case without reference

  var2.toUpperCase();

  System.out.println(var2);//
as
the reference hadn't been done nothing happened

  

Console:


In
Rio

Let's
Surf In Rio

Let's
Surf In Rio

LET'S
SURF IN RIO!

Let's
Surf In Rio!




&nbsp; &nbsp;Would
you know how many objects we created up here?

&nbsp; &nbsp;Take
a deep breath, and let's understand what happened with that code we
just saw. At the beginning we can see a traditional instantiation of
a string object and its reference's to a variable var1, the
same thing is done on the second line but now with var2. After
printing var2 value in the third line, a new string object is
created with the concatenation of two variables var1 and var2,
after creating an object a reference to the variable var2 is
done, and its old object containing the “In Rio” value became
lost on our heap. We can verify that on the next line when we print
the var2 object reference's and see that its value has been
changed. On the next line another string object is created now
increasing the text with the word “Baby!”, but as this object
isn't referencing to any variable, this object will be lost on the
heap with the others string objects. Different to what happen when we
compare with the next lines where we add an exclamation mark at the
end of the text but give reference to the var2 variable. On
the three ending lines where we can ratify what we have seen here is,
that on using the toUpperCase() method a
new string is created,  but as
you already know, without
giving its reference the
string won't be able to be used again onces the variable won't be
pointing to its variable.

&nbsp; &nbsp;Look
the graphics bellow and see if you understand them.





&nbsp; &nbsp;

&nbsp; &nbsp;The
first graphics represents the first and second line and the second
graphic represents the fourth where the concatenation happened to
create another string object.

&nbsp; &nbsp;The
object with the string “Let's Surf in Rio Baby” didn't
received any reference as it
was created as you can see on
the next figure.

















 

&nbsp; &nbsp;As
we already explained in
this
graphic the concatenation with the exclamation mark and
the last lines where the text is redone in a upper case character by 
using the method  toUpperCase.





&nbsp; &nbsp;Understanding
everything to here, you will have learned most part of what you will
need about strings.  But  let's continue...

&nbsp; &nbsp;Is
always good to know when you are or not creating a new string object,
so once you already learned when a string object is created, we will
see when it is not created. A String object is not created when: 






 Is
 referenced to another object;


 Its
 variable is started with a hard-code and its value is already in our
 pool.






&nbsp; &nbsp;The
first item should not be surprise for you, if we point a object to
another object the same values and memory they will share. This don't
happen only when using strings but any kind of java object.




 
String
 var3
 = "um";

String
 var4
 = var3;//
 reference
 to
 same object





&nbsp; &nbsp;Our
second item is a bit more complex but easy to understand. When you
set a value on a string variable, before reserve a space on your
heap, the JVM look if this string already exists in the pool. In case
there is one string exactly equal, in spite of creating another
object, it just point to that existing string, but be careful because
this won't happen if call a string method or instantiate calling the
new keyword.

&nbsp; &nbsp;

&nbsp; &nbsp;Look
those examples:




String
var5
= "LET'S
SURF IN RIO";//new
String

String
var6
= "Let's
surf in Rio Baby!";//new
String

String
var7
= "Let's
surf in Rio";//new
String

String
var8
= "Let's
surf in Rio";//already
exist, not a new string

String
var9
= new
String("Let's
surf in Rio");//
calling
new
word it always  make a new object

String
var10
= var9.toLowerCase();
//
calling
a string method it will create a new object too




Métodos
String



&nbsp; &nbsp;There
are many good method to use on your daily at work.  Those methods can
help you a lot. I like to recommend oracle
documentation
every time you are in doubt or need to learn a bit more about how a
method works and its examples.

&nbsp; &nbsp;In
case you haven't been presented to those methods, here are the
principles methods used in my daily just to have an idea .





CharAt(
 )
 -  It
 will return the character in the specific indice of the
 string.String
 aux
 = "0123456789";System.out.println("aux.charAt(5)
 = "+aux.charAt(5));Console:
 aux.charAt(5)
 = 5


Concat()=
 Add
 text at the end of the actual string variable, also can be used by
 the plus mark
 (+).String
 aux
 = "0123456789
 ";aux
 += aux.concat(aux);System.out.println("aux
 = "+aux);Console:
 aux
 = 0123456789 0123456789 0123456789


toUpperCase:Create
 a new string with its charterers in upper case.String
 aux
 =
 "testMyString";System.out.println(aux.toUpperCase());Console:TESTMYSTRING


toLowerCase:Create
 a new string with its charterers in lower case.String
 aux
 =
 "testMyString";System.out.println(aux.toLowerCase());Console:testmystring


equalsIgnoreCase(
 ):
 Verify
 if two strings are equals disregarding if the character is upper
 case or lower case.String
 aux
 =
 "testMyString";System.out.println(aux.toLowerCase().equalsIgnoreCase(aux.toUpperCase()));

Console:true


Length():
 Measures
 the number of characters that a string has.String
 aux
 = "01234";System.out.println(aux.length());Console:5


Replace(oldChar,newChar):
 Replace
 characters in a string, the oldChar parameter should be the
 character that will be replaced
 and
 the newChar parameter to place the new character.String
 aux
 = "testMyString";System.out.println(aux.replace("t","X"));

Console:
 XesXMySXring


trim()
 : Remove
 spaces from the beginning and end of your string.

aux
 = "
 test My String
 ";System.out.println("*"+aux+"*");System.out.println("*"+aux.trim()+"*")

Console:*
 test My String **test My String*






StringBuffer
e StringBuilder




&nbsp; &nbsp;StringBuffer
and StringBuilder are two classes that have many things in common,
starting with their methods that work “exactly” the same. Is
possible to do many different things with strings when using those
methods and the good thing, is that when you manipulate strings using
StringBuilder or StringBuffer class methods you don't create another
object, leaving your pool free of objects that you won't need.

&nbsp; &nbsp;Proceeding
what I mentioned, StringBuilder
and StringBuffer are almost ”exactly” the same. The only
difference is that StringBuffer
is synchronized,
it means that is more secure to use
StringBuffer when you intend to develop to a multi thread
environment. In
the other hand,
StringBuilder is
much more faster to execute, once it doesn't need to be careful with
threads. Even tho if you look in Oracle API documentation you will
see that they recommend, or at least give preference to StringBuilder
and personalize your synchronize method on
the way your application will need.

 Here
are some examples of code comparing String, StringBuffer and
StringBuilder. 





  String
 testString
= "surfing";

  StringBuilder
 testStringBuilder
= new
StringBuilder("surfing");

  StringBuffer
 testStringBuffer
= new
StringBuffer("surfing");

  testString.concat("
in Rio!");

  testStringBuffer.append("
in Rio!");

  testStringBuilder.append("
in Rio!");

  System.out.println("testString
= "+testString);

  System.out.println("testStringBuffer
= "+testStringBuffer);

  System.out.println("testStringBuilder
= "+testStringBuilder);

  testString
= testString.concat("
in Rio!");

  System.out.println("&gt;&gt;
testString = "+testString);




Console:

testString
= surfing

testStringBuffer
= surfing in Rio!

testStringBuilder
= surfing in Rio!

&gt;&gt;
testString = surfing in Rio!




&nbsp; &nbsp;As
you can see either StringBuffer or StringBuilder don't need to give
or even receive reference like you need when you do using String.




Constructors
StringBuffer and StringBuilder




&nbsp; &nbsp;Constructor
are the signatures that show to the developer how you can instantiate
your object. StringBuffer and StringBuilder have the same number and
kind of constructors so here I will refer to StringBuilder
constructors but you can be sure that if you do the same thing when
using StringBuffer the same thing will happened.





 StringBuilder():Constructor
 default
 that store an capacity  of 16
 characteres.


 StringBuilder(charSeq
 c):
 Contructor
 that receive a char array that will be set up on your variable and
 store more 16 bits of characteres.


 StringBuilder(int
 capacity):Constructor
 that get you integere parameter so as to personalizethe capacity to
 be stored, in spite of the 16 default bits. If you set a negative
 number, an exception will happened:
 NegativeArraySizeException.


 StringBuilder(String
 str):Constructor
 that
 read your string parameter and add the 16
 character
 to
 be stored.









Methods
StringBuffer e StringBuilder




&nbsp; &nbsp;Repeating
what have done on the string topic, I will describe some of the
principle methods of StringBuffer and  and StringBuilder I daily use,





 append(String
 s): This
 was already demonstrate in case you didn't know about it. Is similar
 to the concat
 method
 when you use Strings. It is also overloaded receiving many others
 forms of parameter.

 


delete(int
 start, int end):
 This
 method has two overloaded methods. One
 you
 set two integers that is needed to define the interval from where
 will start count and to where it will finish the delete characteres.
 The
 second method you just detete one character setting its position
 form the string as
 you can see the example:.//delete

 System.out.print("testStringBuffer
 (delete)= "+testStringBuffer);

testStringBuffer.deleteCharAt(5);//delete
 indice
 5

 System.out.println("(delete
 5)= "+testStringBuffer);



Console:testStringBuffer
(delete)= surfing in Rio!(delete 5)= surfig in Rio!





insert(int
 offset, String s);Here
 is the same thing on the delete method but it  add in
 spite
 of delete.//
 insert

System.out.print("testStringBuilder=
 "
 + testStringBuilder);

  
   
    
testStringBuilder.insert(7,
    "
    all day ");



System.out.println("(insert
  7)= "
  + testStringBuilder);

Console:testStringBuilder=
  surfing in Rio!(insert 7)= surfing all day  in Rio!









reverse():Its
 name already say a lot about what this method does, just get all its
 value and reverse its positions.//
 reverseSystem.out.print("testStringBuilder
 reverse"+testStringBuilder.reverse());Console:testStringBuilder
 reverse= !oiR ni  yad lla gnifrus

 


 toString():
 Parse the value of the variable to a  string form. You will need
 this method in times where you should pass parameters in a string
 form and you are using StringBuffer and StringBuilder.

//
 toString

System.out.print("testStringBuffer
 toString=”+testStringBuffer.toString())



GitHub=https://github.com/gmachado1/blog/tree/branche1/String-StringBuilder-StringBuffer