Strings in Java

String in java is an Object that represents a sequence of characters for e.g. “Programmer” is a string of 10 characters.

In java, string is also an immutable object which means it cannot be changed once it has been created.

Syntax to Create a String

In 2 Ways:

  1. Using String Literals:
    String str1 = “Hello”;
    String str2 = “Hello”;
  2. Using new Keyword:
    String str1 = new String(“Hello”);
    String str2 = new String(“Hello”);

Using String Literals:

As you see in the above example, Two String references are created (str1 & str2). We know that Objects are created using new keyword But here we see that only 2 references are created and assigned a value “Hello” and we read above that String is an Object so how is literal creating object ?

Here the compiler does it for us automatically. The compiler creates the String Object and assigns it to the String reference str1.

Now what happens with str2 ? Does the compiler create another Object for that ? The answer is no ! Here since the Object “Hello” already exists in memory hence it is also assigned to any other reference String variables which are having the same value.

Benefit of above strategy : JVM manages memory very efficiently by not creating the same String Objects again and referencing the same Object to other variables. This is the reason JVM is having seperate memory area for String Objects created via String literals called the String Constant Pool.

The memory area where this Object is first created is called the String Constant Pool.

Using new Literals:

Seeing the above example, In this case the JVM creates 2 seperate Objects each with the same value.

Moreover, when we do String s = new String(“programmer”);

Then, inside the memory area 2 objects are created , one in the Heap area because of the new operator and one in the String Constant Pool area so that a new reference if created and assigned the same value, can point to that Object.

Other String related Classes

1. StringBuffer Class:

While String is a fixed length, immutable character sequence, StringBuffer represents a growable and writable character sequence.

StringBuffer s = new StringBuffer(“ProgrammerToday”);

2. StringBuilder Class:

It represents a mutable sequence of characters i.e it can be modified.

StringBuilder str = new StringBuilder();
str.append(“ProgrammerToday”);

3. StringTokenizer Class:

Is used to break a string into tokens.

//seperate by whitespaces	
StringTokenizer st = new StringTokenizer("Welcome programmer to this website"," ");  
    while (st.hasMoreTokens()) {  
        System.out.println(st.nextToken());  
    }  
}  

OUTPUT

Welcome
programmer
to 
this
website

Few methods of String Class:

Java String class provides a lot of methods to perform operations on strings. Few of them are : compare(), concat(), equals(), split(), length(), replace(), compareTo(), intern(), substring() etc.

String replace methods: 2 types

There are two type of replace methods in java string.

  • public String replace(char oldChar, char newChar) :
    To replace a character with another one.
  • public String replace(CharSequence target, CharSequence replacement) :
    To replace a string with another one.

Examples:

1.)

public class ReplaceExample1{  

  public static void main(String args[]){  
  String s1="Welcome to programmer today";  
  String replaceString=s1.replace('o','e');//replaces all occurrences of 'a' to 'e'  
  System.out.println(replaceString);  

}}
              

OUTPUT

Welceme te pregrammer teday
              

2.)

public class ReplaceExample1{  

  public static void main(String args[]){  
  String s1="Welcome to programmer today";  
  String replaceString=s1.replace('to','buddy at');
  //replaces all occurrences of 'a' to 'e'  
  System.out.println(replaceString);  

}} 
              

OUTPUT

Welcome buddy at programmer today
              

Why is String Immutable in java ?

Consider a situation like below :

There is one String :

String s1 = “programmer”;

We see that there is a reference variable with “programmer” as its value.

now take another reference variable s2 :

String s2 = s1.concat(“today”);
String s3 = s1;

If String was not immutable then it would have modified the value of s1 to “programmertoday” and all the other references pointing to it would have also changed.

To avoid this, String is made immutable in java and string literal concept is introduced.

Summary

In this article we learnt about the Strings in java, ways to make a String, its some very useful methods and why String is immutable.
Hope you liked the article !


Leave a Comment