How to create String, StringBuffer and StringBuilder in java

Most of the data transmits on Internet will be in the form of group of characters. Such group of characters are called as 'String'. JavaSoft people have created a class separately with the name of 'String' in java.lang package with all necessary methods to work with String.

          Even though, String class, it is used often in the form of a data type, as


String s = "Java";

Creating String:

          There are 3 ways to create String in java.
              • We can create a String just by assigning a group of characters to String type variable

   String s; // Declare String type variable
s = "Java"; // Assign a group of charecters to it

          Preceding two statements can be combined and written here,

String s = "Java";

          In this case JVM creates an object and stores the string: "Java" in that object. This object referenced by the string variable 's'.
              • We can create object for String class by allocating memory using new operator.

   String s2 = new String("Java");

          Here, we are doing two things first we are creating object for string class using new operator and the assigning "Hello" to it.
             • The last way creating String is by converting the character arrays into Strings.

     char arr[] = {'J','a','v','a'};

          Now create string object by passing the array object to it.

          String s3 = new String(arr);

          The String object s contains the string : "Hello". This means all the characters of the array are copied into string.

Ex: Here is the example of creating string using 3 ways:


package com.javatbrains.String;

public class StringCreation {
     public static void main(String[] args) {
          // First way of String creation
          String s1 = "Java";
         
          // Second way of String creation
          String s2 = new String("Java");
         
          // Third way of String creation
          char arr[] = {'J','a','v','a'};
          String s3 = new String(arr);
         
          System.out.println("First String is: "+s1);
          System.out.println("Second String is: "+s2);
          System.out.println("Third String is: "+s3);
     }
}
/*OutPut:
     First String is: Java
     Second String is: Java
     Third String is: Java*/

String Comparison

          The relational operators like >, >=, <, <=, == and != cannot be used to compare the Strings. On the other hand compareTo() and equals() methods should be used in String comparison.

Ex: Here is the program to compare two strings.


package com.javatbrains.String;

public class StringCompare{
     public static void main(String[] args) {
          String s1 = "Hello";
          String s2 = new String("Hello");
           if(s1==s2){
               System.out.println("Both are same");
           }else{
               System.out.println("Not same");
           }
     }
}
OutPut:
     Not same

          When an object is created by JVM, it returns the memory address of the object as a hexadecimal number, which is called 'Object reference'. When a new object is created, a new reference number is allotted to it. It means every object will have new unique reference.
The fact that string s1 and string s2 are same. We are getting wrong output in program. Let us take first statement,

String s1 = "Hello";

          When JVM executes the preceding statement, it creates an object on heap and stores "Hello" in it. A reference number(3a23e5) is allocated for this object.
          when the second statement is executed,

String s2 = new String("Hello");

          JVM creates another object and allotted to another reference(18923f) to it. When if(s1==s2) will compare these reference numbers, both are not same and hence the output will be "Not same".

Ex: Here is the example of String comparison with equals() method:

package com.javatbrains.String;

public class StringWithEquals{
     public static void main(String[] args) {
          String s1 = "Hello";
          String s2 = new String("Hello");
           if(s1.equals(s2)){
               System.out.println("Both are same");
           }else{
               System.out.println("Not same");
           }
     }
}
OutPut:
     Both are same

          In the above example, when if(s1.equals(s2)) will execute it will check both the contents. So, both the contents are same as "Hello", output is "Both are same".

String constant pool

          String constant pool is a special place where collection of String references are placed. Now, we will try to know about the String constant pool.

package com.javatbrains.String;

public class StringCompare{
     public static void main(String[] args) {
          String s1 = "Hello";
          String s2 = "Hello";
    
          if(s1 == s2){
              System.out.println("Both are same");
          }else{
              System.out.println("Not same");
          }
     }
}
OutPut:
     Both are same

String s1 = "Hello";

          Here, JVM creates a String object and stores "Hello" in it. Observe that we are not using new operator to create String. We are using assignment operator(=) for this purpose. So, after creating the String object, JVM uses a separate block of memory which is called String Constant pool and store objects there.


          When the next statement String s1= "Hello"; is executed by the JVM, it searches in the String constant poll to know weather the object with same content is already available or not. Since the same object is available there(which is s1), then JVM does not create another object. It simply creates another reference variable (s2) to the same object and copies the reference number of s1 into s2.

Immutability of String:

          We can divide objects broadly as, mutable and immutable objects.
Mutable Objects: Mutable objects are those objects whose content can be modified.

Immutable objects:

          Immutable Objects are those objects, once created can not be modified. String class objects are immutable.

          Let us see the program to test String objects are immutable or not.

package com.javatbrains.String;

public class ImmutableClass{
     public static void main(String[] args) {
          String s1 = "Hello ";
          String s2 = "world";
          //Join s1 and s2 and store it in s1
          s1 = s1+s2;
          System.out.println(s1);
     }
}
OutPut:
     Hello world

          Here you got one doubt, if String s1 is immutable that content should be not changeable. But, in the above program when s1 = s1+s2; is get executed s1 content has modified and output showed as 'Hello world'. It means String is mutable, that's wrong. String objects are immutable,

          s1 is definitely immutable. In the program JVM creates two objects s1 and s2 separately as shown in the diagram. When the s1+s2 is done JVM creates a new object and assigns Helloworld to it. But, it does not modifies the content of the String s1. After creating the new object, the reference s1 is adjusted to refer to the new object.
          The point we should observe here the content of the s1 is not modified. This is the reason, strings are immutable. The old object that contains "Hello " has lost its reference. So it is called "unreferenced object" and garbage collector will remove it from memory.

String Buffer

          In the above you learnt about the Strings, Strings are immutable and cannot be modified. To overcome this problem we have another class called StringBuffer, which represents Strings, such objects data can be modified. It means StringBuffer class objects are mutable. There are methods provided in StringBuffer class which directly manupulate the data inside the object.

Creating StringBuffer Objects:
          There are two ways to create a StringBuffer object, and fill the object with a String.

              •  We can create StringBuffer object by using new operator and pass the String to the object.

StringBuffer sb = new StringBuffer("Hello");

          Here, we are passing string "Hello" to StringBuffer object sb. So, a statement like,

System.out.println(sb);

                   will display "Hello"

               • Another way of creating StringBuffer object is to first allocate memory for StringBuffer object by using new operator and later storing string into it.

StringBuffer sb = new StringBuffer();

          Here, I am creating StringBuffer object, and I am not passing any String to it. In such cases JVM will create sb object and by defaultly it allocates 16 charecters space in 'Heap memory'.

StringBuffer sb = new StringBuffer(50);

          Here, I am creating a StringBuffer object with empty with the capacity of 50. This is not a fixed size, even we can add morethan 50 charecters, because StringBuffer objects are mutable it will expand dynamically in the memory. For storing the charecters into 'sb' we can use 'append()' method or 'insert()' methods.

sb.append("Hello");     //Add Hello to sb
sb.insert(0,"Hello"); //Insert "Hello" from 0th position in sb

String Builder
          StringBuilder class has been added in JDK 1.5 which has same features like StringBuffer class. StringBuilder class objects are also mutable as are the StringBuffer objects. For creating StringBuilder class object we can use any of the following statements.

StringBuilder sb = new StringBuilder();
StringBuilder sb = new StringBuilder("Hello");
StringBuilder sb = new StringBuilder(50);
           
          The main difference between StringBuilder and StringBuffer  Classes is that the StringBuffer class is synchronized by default and StringBuilder class is not.                                        
          It is recommended that when a programmer wants to use a single thread as is the case generally, he should use StringBuilder                                                              
class instead of StringBuffer class, to get faster execution.

StringBuffer/StringBuilder class methods:.
There are same methods in StringBuffer and StringBuilder classes,

               • StringBuffer/StringBuilder append(x): X may be boolean,byte..any of the type. It will be added to the StringBuffer/StringBuilder class object.

              •  StringBuffer/StringBuilder insert(int i,x):X will be inserted into the StringBuffer/StringBuilder at the position of i.

              • StringBuffer/StringBuilder delete(int i,int j): It removes charecters from i'th position to till j-1 position.

              • StringBuffer/StringBuilder reverse(): This reverses charecter sequence in the StringBuffer/StringBuilder contains "abc", it becomes "cba".

              • StringBuffer/StringBuilder replace(int i,int j,String str): This replaces the charecters from i to j-1, by the String str.

               • String toString(): This converts StringBuffer/StringBuilder object into String. This will enables us to use String class method on StringBuffer/StringBuilder object, after its conversion.

               • String subString(int i): This retrieves a String from StringBuffer/StringBuilder object starting from i'th position to till the end.

               •  String subString(int i,int j): This extracts a String from the StringBuffor/StringBuilder starting from i'th position to j-1'th position.

               • int lenght(): This returns the no.of charecters in the object.

               •  int indexOf(String str): This returns the first occurance of substring str in the object.

               • int lastIndexOf(String str): This return the last occurance of substring str in the object.

Ex: Write a program to learn how to use some of the StringBuffer/StringBuilder class methods by entering input at the time of running through command prompt.

package com.javatbrains.String;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class StringBufferMethods {

     public static void main(String[] args) throws IOException {
          //Create empty StringBuffer object
          StringBuffer sb = new StringBuffer();
          //to accept data from keyboard
          BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
          //accept sur name
          System.out.println("Enter sur name: ");
          String sur = br.readLine();
          //accept first name
          System.out.println("Enter first name: ");
          String first = br.readLine();
          //accept last name
          System.out.println("Enter last name: ");
          String last = br.readLine();
          //append sur name to sb
          sb.append(sur);
          //append last name to sb
          sb.append(last);
          //display the name till now
          System.out.println("Name: "+sb);
          int n = sur.length();/*n represents no.of chars in sur name*/
          sb.insert(n, first);/*insert first name after the nth char*/
          //display full name
          System.out.println("Full name: "+sb);
          //Reverse and display the name
          System.out.println("In reverse = "+sb.reverse());
     }

}
OutPut:
     Enter sur name:
          Java
     Enter first name:
          T
     Enter last name:
          Brains
     Name: JavaBrains
     Full name: JavaTBrains
     In reverse = sniarBTavaJ

Popular posts from this blog

how to count the page views by using JSP

Exception in thread "main" java.lang.NoClassDefFoundError: javax/transaction/SystemException

Multithreading in java with example