Java String Class and String Methods with Examples

I dedicate this chapter to learning everything about Java String Class and String Methods and I will not rest until I have covered every important topic there is under String. Okay, that was a tad extreme. I might doze off a little every now and then but that’s not the point. We, my dear friend, by the time we reach the end, we will be brimming up with so much knowledge that people are going to call us String Gods. That’s our aim.

Let’s get it started.

We have already seen some part of String in our earlier ventures, but it’s alright to forget them for a while, because what we are going to learn here today is going to ‘override’ everything. You see what I did there?

lame seal meme

That play of words takes us to the primal question of this chapter:

What is a String?

A String is nothing but an object that represents a sequence of characters. So it was characters that were responsible for the existence of String. You take an array of characters and line ’em up, what you get is a String.

So the following code is going to print what a String might look like.

char []c = {'l','i','f','t'}; 

for(int i=0; i<c.length;i++ ) {

        System.out.print(c[i]); 

}

Or you could use the String constructor that takes an array as arguments to get the same result:

char []c = {'l','i','f','t'}; 

System.out.println(new String(c));

As you can see there is just too much work with the characters. What if we had tons of characters lined up? It would end up taking a lot of your time.

Instead of choosing to go through all the extra work above, we could have simply used String data type to print the message:

String s = "lift"; 

System.out.println(s);

or even better:

System.out.println("lift");

Better?

So what is going on in reality? The moment your JVM encounters the literal “lift” it creates a String object and provides it the value. It does the same when you are using the new keyword to create a String object. The latter you could relate with since you have been using new to instantiate objects for a while now.

Java String Class

Java provides us with the eponymous String Class that has ways to create and manipulate strings. There are tons of String methods available here and we are going to see the most important ones in this chapter.

The Java String Class implements the following three interfaces:

  1. Serializable
  2. Comparable
  3. CharSequence

CharSequence is used to represent sequence of characters and is also implemented by StringBuilder and StringBuffer classes. It clearly means that you can use these two classes as well apart from String Class to create a string in Java.  We are going to learn all about these two classes at a later stage.

The Immutability

The Java String is immutable. Immutable means that you cannot change the object. If you try to change it a new instance will be created instead. The object will remain unchanged.

So even though you are using string methods to modify the object, the result will always create a new instance instead of bothering the already created instance.

For example,

String s = "Carnival";

s.concat(" of the rust");

System.out.println(s);

The above program uses concat method to concatenate or append a string to the end. If we use the above program the output we will get will be:

Carnival

So did the appending happen? Yes it did. It is just that it created a separate instance for that.

diagram to depict java string class immutability

We can choose to assign the method calling to a reference variable and then display it as an alternative:

String s = "Carnival";       

String m = s.concat(" of rust");

System.out.println(m);

Now if you will try to run the program you will get the expected result:

Carnival of rust

How to make a Class Immutable?

Now since a String class is immutable, you might be wondering how to make your very own class immutable?

No biggie there. You just have to remember a couple of points:

  1. Your class needs to be final.
  2. Instance variable of the class needs to be final.
  3. There should be no setter method.

Here’s an example wherein I am trying to create an immutable class:

public final class BSB {

   final String s;

           public BSB(String s) {

                  this.s = s; 

           }

            public String getWordOut(){

            return s;

          }

}

The above BSB class has become an immutable class since it doesn’t have a Setter method to change anything. Even you can’t edit the instance variable since it is final. You can’t subclass this class too. So there! You have it. Your very own immutable class.

How to Create a String Object

As you might have already guessed from the example above, a String object can be created in the following two ways:

  1. Using literal (with double quotes)
  2. Using new keyword (with new String())

Using Literal | String Pool

Whenever you are creating a String object using literal, JVM goes to check in a place called String constant pool where all literals get stored. If you are using the same literal again then it doesn’t create a new string object but gives you simply the reference of the first one. This is done in order to save space.

So, for example, writing the following code:

String s = "Carnival";

will create a new instance named Carnival in the string constant pool. But when you immediately try to create another String object using the same literal:

String a = "Carnival";

It will not create a separate instance rather go looking in the String constant pool first to see if the instance is already there. On finding that it is already there, it will simply return the same instance and not create a new one.

New Keyword | Heap Memory

Using new keyword to create a String object will create a new instance in heap memory.

You can create a String object using new keyword like this:

String s = new String("Carnival");

Here there will be two objects created. One that will create a new instance in heap, the other “Carnival” literal will be placed inside the String constant pool. However the reference variable ‘s’ will point to the one in the heap.

String Compare

How do you compare two strings? Imagine there are two strings and you wish to check whether they are the same or not. You can do so based on their content and reference.

There are three ways in Java that can let you compare strings:

  1. By equals() method
  2. By = = operator
  3. By compareTo() method

We will see each method one by one.

equals() Method

The equals() method of Java String Class lets you compare the content of the string. It overrides the equals() method of Object class.

There are two variants available:

  • boolean equals(Object object)
  • boolean equalsIgnoreCase(String another)

Both the methods return boolean value. Here an example would help:

String s = "Carnival";        

String t = "carnival"; 

System.out.println(s.equals(t)); 

System.out.println(s.equalsIgnoreCase(t));

If you run the above program you will get the following result:

false
true

The first one will return false because of the first letter’s case. equals() doesn’t takes cases seriously. To curb that issue we have equalsIgnoreCase.

= = Operator

If you have references to compare = = operator comes in handy. Remember it doesn’t compare values.

String s = "Carnival";       

String t = "Carnival";

String m = new String("Carnival");

System.out.println(s == t);

System.out.println(s == m);

In the above code, line 2 will try to find the instance available in the String Pool thus referencing itself to ‘s’. Both will become equal, and hence the operator result for it will turn out to be true. For the second sysout display the result will be false because m has become a different instance in the heap. Here’s the result of the above program:

true
false

At times you might want your second sysout display to give out the same reference by deliberately searching for the instance passed as an argument in the String pool. You could achieve that by making use of intern() method in Java.

Java String Class intern() Method

What intern() method of Java String Class does is that it tries to first look into the String pool to check if the String object is already there. If it is, then it returns the string otherwise it will simply add the String object to the pool and return the reference.

So, in the example above if you add another line:

String p = m.intern();

And try to print p, it will capture “Carnival” into the reference variable:

Carnival

And then if you say s = = p it would return true.

Another example to show this would be:

String s = new String("Carnival of rust");    

String l = s.intern();

System.out.println(l);

is going to display:

Carnival of rust

As simple as that.

compareTo() Method

compareTo() method is a tad different owing to its strange return type. It compares values lexicographically meaning alphabetically, and returns result in the form of integer value. If the strings are equal it returns 0. If the first string is lexicographically greater than the second string, then it will give you a positive number which is the difference of character value. If it is smaller then a negative number with the difference of character value.

  • s1 = = s2 : 0
  • s1 > s2 : +
  • s1 < s2 : –

Let us see this in a program and make it crystal clear:

String s = "Carnival";       

String t = "Carnival";

String m = "Eagle Boys";

System.out.println(s.compareTo(t));

System.out.println(s.compareTo(m));

The above will return the following result:

0
-2

The first result 0 is pretty clear since both s and t are same. To justify the second result you can see that s<t since ‘C’ comes prior to ‘E’. Hence the result is negative. The value 2 is the difference of character value, here C is 67 and E is 69. The difference is 2.

String Length

You can find out the length of the string too. It helps when you have huge files to deal with.

There is an accessor method called length() from Java String Class that tells you the length of your string. The counting is done right from the starting character and includes blank spaces too.

An example:

String s = "Carnival of rust";       

System.out.println(s.length());

If you run the above you will get:

16

Go ahead you can count the characters in “Carnival of rust” including spaces. They are 16!

String Concatenate

We have already seen one example earlier. Let’s delve into it in detail.

There are two ways you can concatenate strings.

  1. Using + (string concatenation operator)
  2. Using concat() method

The good old ‘+’ operator is useful for concatenating. We have been using it for so long now that we know how it works. Still here’s an example:

String s = "Carnival of rust";     

String p = "POTF"; 

System.out.println(s + " by " +  p);

I have used another string without providing a reference variable in the form of “by” in the middle. It would be concatenated as well. Here’s our result:

Carnival of rust by POTF

Basically, it isn’t the virtue of one of string’s methods but of StringBuilder class’s method called append(). So when you are using the ‘+’ operator to augment strings, in the background your compiler actually goes:

(new StringBuilder()).append(s).append("by").append(p).toString();

But you don’t have to worry about that. Just use the operator.

We will once again see a concat() example so that there’s no element of doubt left whatsoever:

String s = "Carnival of rust";     

System.out.println(s.concat(" by POTF"));

The result is going to be same. You can go ahead and check this one yourself.

Substring in Java

Substring is nothing but a part of a string. There could be testing times where you could be asked to grab a string out of a text file. At those times using a substring method from Java String Class proves to be very helpful.

Here are the substring methods you need to remember:

  • String substring(int startIndex)
  • String substring(int startIndex, int endIndex())

startIndex and endIndex imply the position from which you wish to extract the string and the position where you wish to stop. Remember the positions or indices work like an array. So the first one would be 0.

Let’s see it in an example:

String s = "Carnival of rust";

System.out.println(s.substring(9));

What is the 10th character if you start counting from C? Remember C has to be 0. It is ‘o’. So our result is going to show everything that comes after ‘o’ with ‘o’ included. startIndex is inclusive.

The output to the above would be:

of rust

Now using the second method to specify the endIndex too. Let’s extract the word ‘of’:

System.out.println(s.substring(9,11));

endIndex is exclusive of the character and hence we need to specify a number +1. Here’s the result:

of

String Uppercase and Lowercase Methods

Java String Class has a whole lot of string methods that you can use to manipulate strings as you please. Here is how you can make all or some letters in your string to Uppercase or Lowercase.

You need to make use of toUpperCase() if you wish to turn a string into capitals. You use toLowerCase() if you wish to do the opposite.

Here’s one example to help you understand this:

String s = "Carnival of rust";     

System.out.println(s.toUpperCase());

System.out.println(s.toLowerCase());

The result of the above code will be:

CARNIVAL OF RUST
carnival of rust

Now, what if you just wanted only the word ‘Carnival’ to be shown in all Caps? A nice exercise right?

Try that with the method substring() we learned earlier.

Lost, already?

Okay here it is:

System.out.println(s.substring(0,9).toUpperCase() + s.substring(9));

Using the above code we will get the following result:

CARNIVAL of rust

Cool, huh? Java’s fun indeed.

Java String trim() Method

Suppose there was a source code you were trying to extract but there were too many white spaces in the starting and ending of the document? What would you do to eliminate those white spaces?

Do not worry! Java String Class has a built-in trim() method for you to remove the white spaces from the beginning and end of a string.

So if your string was something like this:

String s = "             Carnival of rust                   ";

We can get rid of the starting and ending white spaces by using s.trim():

System.out.println(s.trim());

The above will print the result as:

Carnival of rust

What if we wished to remove the gaps that are in between? That’s where replace() method comes into the picture.

Java Replace() Method

The Java replace() method of the Java String Class comes in handy when you want to replace something with something. There are two parameters to be passed here. The first one defines what you want to replace, and the second one what you want to replace it with.

We will pick the above example to test this:

System.out.println(s.replace("Car", "Bar"));

If you replace the Car with Bar in your string, the world would become a better place. Wouldn’t it? Here’s what you will get:

Barnival of rust

Now what about the spaces? Can we remove the spaces in between too? Yes, you can.

System.out.println(s.replace(" ", ""));

If you will run the above you will get:

Carnivalofrust

It isn’t the preferred method though. We can make use of Regular Expressions to replace all those instances where white spaces are encountered. We will learn all about regex in the next chapter.

Java startsWith() and endsWith() Methods

Another pair of crucial String methods from Java String Class. It is a standard boolean check to see if the string we are looking for indeed starts with or ends with a character or a string we want.

So in our example above we can check if our string starts with a C like this:

System.out.println(s.startsWith("C"));

If you run it you will get the following:

true

You can check it if starts with more than one character as well for example “Carnival”:

System.out.println(s.startsWith("Carnival"));

The answer would be once again:

true

In a similar manner, you can check if for strings that end with a character or a string:

System.out.println(s.endsWith("f"));

System.out.println(s.endsWith("rust"));

Does it end with an f? No of course not. Does it end with “rust”? Yes it does! So our result will be:

false
true

charAt() Method

This is another useful String Java String Class method. What if you wanted to know what character is at particular index or position of your string? What is the character at say 9?

You could make use of charAt() method to figure that out. The method takes int as its parameter.

The following example will help:

String s = “Carnival of rust”;

System.out.println(s.charAt(10));

The answer to the above is:

f

So the letter f was there at the index no. 10. Hmm…interesting!

valueOf() Method

valueOf() method is one of those static methods that helps you to grab representation of any data type in the expected data type format.

That being said it isn’t limited to just String class. You can have it for Integer, Float, Boolean etc. as well.

Here’s the string representation of it:

System.out.println(String.valueOf(8) + 54);

This will give you a result as:

854

Remember it is the String representation and hence it will be treated as a String and not a number. Hence the addition of 8 and 54 wasn’t performed.

toString() Method of Java String Class

If there’s an object you need to display as String, you can make use of toString() method. It simply returns the string representation of an object.

toString() is a method that is implicitly invoked by Java when you are trying to display an object.

public class POTF {

       String s; 

             POTF(String s) {

                      this.s = s;

              } 
public static void main(String[] args) { 

              POTF p = new POTF("Whoa!"); 

              System.out.println(p); 
         
       }
}

And you trying to print this, the Object Class will have its very own interpretation wherein it will try to call toString() method internally nevertheless and will print the address that it points to. So the result that you will get here would be:

potf.POTF@15db9742

The above is a hashcode value of the objects. Now if we want to print something that makes a little bit more sense we need to override the toString() method.

Include the following toString() method in the above code making the output more meaningful:

public String toString () {

       return s;

}

The above will now print whatever you pass as an argument for s. Here argument passed was:

Whoa!

Hence the result.

I think we have covered all the important Java String Class methods. The chapter is far from over until of course, we have seen what StringBuilder and StringBuffer are all about. We are going to do that next.

Signing off.

Scottshak

Poet. Author. Blogger. Screenwriter. Director. Editor. Software Engineer. Author of "Songs of a Ruin" and proud owner of four websites and two production houses. Also, one of the geekiest Test Automation Engineers based in Ahmedabad.

You may also like...

4 Responses

  1. June 19, 2017

    […] we had learned in the String chapter earlier that it was immutable (cannot change the instance), what if we wish to deal with a mutable […]

  2. June 20, 2017

    […] until now, we have seen string in Java up close, now it is time to understand how to format […]

  3. June 21, 2017

    […] mentioned in the String chapter before, regular expressions come in handy when you are trying to identify white spaces in a file […]

  4. June 23, 2017

    […] have covered the equals() and toString() methods in the String chapter. You can check it out from […]

Leave a Reply