String in Java

String

     Sequence of the character is called as String. String is keyword. String is an object in Java, String Class is used to create the String Object. In Java String are Immutable* i.e can't use the String object once we assigned.

The character

      char c={'s','a','t','h','i','s','h'};
      String s=new String(c);          //new is a keyword used to allocate memory.

                            or String s="sathish";  //both are same

Why string objects are immutable in java?

       Because java uses the concept of string literal.Suppose there are 5 reference variables,all referes to one object "sathish" if one reference variable changes the value of the object, it will be affected to all the reference variables. That is why string objects are immutable in java.

Two types to create the String.

  1. String Literal
  2. By using "new" keyword

String Literal

Ex. String s="hello world";

By using new-keyword
   
Ex. String s= new String("hello world");

Immutable Example Program



public class Immutable
   {
       public static void main(String args[])
         {
             String s=new String("Immutable");
             s.concat("In Java"); //Line 6
             System.out.println(+s);
           }
      }
Output:
          Immutable

Note: We can use String object only once so, .Line 6 was rejected by the JVM.

How to make String as Mutable??

Two more concepts introduced in Java

  1. StringBuffer
  2. StringBuilder
________________________________________________________________________
StringBuffer                                         vs                                       StringBuilder
________________________________________________________________________
                    Both are used to change the String as Mutable in Java
________________________________________________________________________
Slow Execution-Taking more time to              Fast Execution-Less time to Execute
Execute
Thread Safe are Available                                Thread Safe not Available.

________________________________________________________________________

          
Example for StringBuffer

public class Immutable
   {
       public static void main(String args[])
         {
             StringBuffer s=new StringBuffer("Immutable");
             s.append("In");
             s.append("Java");
             System.out.println(+s);
           }
      }
Output:

ImmutaleInJava

Example for StringBuilder

public class Immutable
   {
       public static void main(String args[])
         {
             StringBuilder s=new StringBuilder("Immutable");
             s.append("In");
             s.append("Java");
             System.out.println(+s);
           }
      }
Output:

ImmutaleInJava



No comments:

Post a Comment