String Objects in Java – String vs StringBuffer vs StringBuilder

In this post,we will discuss some of the important aspects of the Java Objects, String, StringBuffer and StringBuilder.

Unknowingly, you have worked with Strings in the previous example. A String is not a primitive data type. A string is a class. Since, we have not covered classes yet, we will postpone a full-fledged discussion on String at this point. But since the String Class is so very convenient to test things, we will understand a few of the characteristics. If you want to understand why it works that way, this will require an understanding of classes and objects which we will cover in the subsequent classes.

[java title=”CharacterStream.java” gutter=”true” highlight=”10″]
package com.sample;

public class StringObject {

public static void main(String[] args) {
// TODO Auto-generated method stub
String first_name = new String();

// Here is the hashcode ( Rough Equivalent of the Address )
// of the first_name String Object
System.out.println ("Hash-code of first_name is " + System.identityHashCode(first_name));

// Now, we are setting the Object’s value to "siva"
// Look at the new address
first_name = "Siva";
System.out.println ("Hash-code of first_name is " + System.identityHashCode(first_name));

// We are resetting the Object’s value to "Siva 1"
// Look at the new address
first_name = "Siva 1";
System.out.println ("Hash-code of first-Name is " + System.identityHashCode(first_name));

// This tells you that String Objects are immutable.
// Your Java Trainer will explain more about immutable objects

// Strings can be concatenated using the + Operator
String last_name = "Prasad";
String full_name = first_name + last_name ;
System.out.println (full_name);

// I think we forgot to put a space in between isn’t it ? Let’s add it.
full_name = first_name + " " + last_name;
System.out.println (full_name);
// Now we got it right. What this goes to show is that strings can be concatenated any number of times

// The ‘+’ character is a special concatenation operator provided by the String class for our convenience.
// Do, don’t go try and subtract Bill from Gates 🙂 . It doesn’t work.

// You can use Strings more or less like primitive variables when it comes to manipulating strings
// For example, apart from concatenating strings, you can create arrays of strings using []

String[] bill_gates = {"Bill Gates 1" , "Bill Gates 2"};
System.out.println ("We just produced the first copy of the richest person – Bill Gates – " + bill_gates[0]);
System.out.println ("We just produced the second copy of the richest person – Bill Gates – " + bill_gates[1]);

// You can find out the length of a string anytime using the length function
// I wish I had a billion $. I am not sure how many zeros in it though.

String billion = "1000000000";
System.out.println ("A billion has " + billion.length() + " zeros" );
// It says the length is 10. I checked with google. It says there are only 9 zeros.
// Where did we go wrong ?
// OOPS !! This counts the numeral 1 in the billion.
// So, we need to subtract 1 from the length to get the correct number of zeros.
// Can we say System.out.println ("A billion has " + billion.length()-1 + " zeros" );
// This wouldn’t compile.
// We would need to use a parenthesis to indicate operator precedence.
System.out.println ("A billion has " + ( billion.length() – 1 ) + " zeros" );
// But thats a subject of discussion for another day (Operator Precedence in Java).

// Now, let’s consider StringBuffer
// StringBuffer is a thread-safe mutable implementation of String
// Both the hash-codes below are same.

StringBuffer address = new StringBuffer();
System.out.println ("Hash-code of Address is " + System.identityHashCode(address));

address.append("1000 Broadway, New York City");
System.out.println ("Has-code of Address is " + System.identityHashCode(address));

// StringBuilder is a non-threadsafe, mutable implementation of String
// Both the hash-codes below are same. What does this tell you ?
StringBuilder City = new StringBuilder();
System.out.println ("Hash-code of City is " + System.identityHashCode(City));

City.append("New York");
System.out.println ("Hash-code of City is " + System.identityHashCode(City));

// More examples on String
// Does the Object change if the value of the object does NOT change ?
// In the case below, the hash-code of the string Object name does NOT change
// Because they still refer to the same "Siva" in memory

String name = "Siva";
System.out.println ("Hash-code of name is " + System.identityHashCode(name));
name = "Siva";
System.out.println ("Hash-code of name is " + System.identityHashCode(name));

// Here are some of the other major methods of String
// 1. Substring

name = "Siva Prasad";
String last_name = name.substring(5);
System.out.println ("last name is " + last_name);
// The output is "Prasad"

// 2. Find the index of a particular letter.
//    For example, find out the index of the letter "P"
int index = last_name.indexOf("P");
System.out.println ( " The index of the letter P is " + index );

// 3. length – Find out the length of the String

int length = last_name.length();
System.out.println ( "The length of the string is " + length );

// 4. equals – Checks if 2 string objects are equal

String animal1 = "Zebra";
String animal2 = "Zebra";
if (animal1.equals(animal2))
{
System.out.println (" Both animals are same");
}
}
}
[/java]

Question 1 : Explain in your own words, the difference between String , StringBuffer and StringBuilder in Java ?

More Questions : Write the code for the following scenarios. In order to answer this question, you should refer to the Java String API.

[java title=”CharacterStream.java” gutter=”true” highlight=”10″]
String String1 = "Bill";
String String2 = "Gates";
String String3 = ??
// <strong>Question 3</strong> : Write the statement to concatenate String1
// and String2 with a blank space in between into Strint3

String fname = "Siva";
String cfname = "SIVA";

if ( ???? )
{
System.out.println ( "Both fname and cfname strings are the same with case difference" );
}
// Question 4 : Write the statement in the if condition to verify
// if the string fname and cfname are same irrespective of the case
// Hint : <strong>equalsIgnoreCase</strong>

fname = "quick brown fox jumps over lazy dog";
<strong>// Question 5</strong> : Print out the character at index 10 of the string fname
// Hint : indexOf

fname = "Siva";
cfname = ???
lfname = ???
// Question 6 : Convert fname to Upper Case characters and put it in cfname
// Question 7 : convert lfname to Lower Case characters and put it in lfname

// String does NOT have a reverse function, StringBuffer has it.
// Question 8 : Write code to convert the string alphabet to reverse_alphabet
String alphabet = "ABCD";
String reverse_alphabet = ???

[/java]

Advertisements

2 thoughts on “String Objects in Java – String vs StringBuffer vs StringBuilder

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s