Thursday, 16 January 2014

String Handling

String Handling

    String Handling
    How to create string objects?
        String literal
        new keyword
    Why Java uses the concept of String literal?

String Handling provides a lot of concepts that can be performed on a string such as concatenating string, comparing string, substring etc.
In java, string is basically an immutable object. We will discuss about immutable string later. Let's first understand what is string and how we can create the string object.
String
Generally string is a sequence of characters. But in java, string is an object. String class is used to create string object.


Do You Know ?

    Why String objects are immutable ?
    How to create an immutable class ?
    What is string constant pool ?
    What code is written by the compiler if you concat any string by + (string concatenation operator) ?
    What is the difference between StringBuffer and StringBuilder class ?

How to create String object?
There are two ways to create String object:

    By string literal
    By new keyword

1) String literal:
String literal is created by double quote.For Example:

    String s="Hello";

Each time you create a string literal, the JVM checks the string constant pool first. If the string already exists in the pool, a reference to the pooled instance returns. If the string does not exist in the pool, a new String object instantiates, then is placed in the pool.For example:

    String s1="Welcome";
    String s2="Welcome";//no new object will be created

string literal
In the above example only one object will be created.First time JVM will find no string object with the name "Welcome" in string constant pool,so it will create a new object.Second time it will find the string with the name "Welcome" in string constant pool,so it will not create new object whether will return the reference to the same instance.
Note: String objects are stored in a special memory area known as string constant pool inside the Heap memory.
Why java uses concept of string literal?
To make Java more memory efficient (because no new objects are created if it exists already in string constant pool).
2) By new keyword:

    String s=new String("Welcome");//creates two objects and one reference variable

In such case, JVM will create a new String object in normal(nonpool) Heap memory and the literal "Welcome" will be placed in the string constant pool.The variable s will refer to the object in Heap(nonpool).


Basics of Java OOPs Concepts
String Handling
String Immutable String String Comparison String Concatenation Substring Methods of String class StringBuffer class StringBuilder class Creating Immutable class toString method StringTokenizer class
Exception Handling Nested Classes Multithreading Synchronization I/O Serialization Networking AWT Event Handling Swing LayoutManager Applet Reflection API Collection JDBC Java New Features RMI Internationalization
space


Immutable String:
In java, strings are immutable (unmodifiable) objects.For example

    class Simple{
     public static void main(String args[]){
    
       String s="Sachin";
       s.concat(" Tendulkar");//concat() method appends the string at the end
       System.out.println(s);//will print Sachin because strings are immutable objects
     }
    }

Output:Sachin

As you can see in the above figure that two objects will be created but no reference variable refers to "Sachin Tendulkar".But if we explicitely assign it to the reference variable, it will refer to "Sachin Tendulkar" object.For example:

    class Simple{
     public static void main(String args[]){
    
       String s="Sachin";
       s=s.concat(" Tendulkar");
       System.out.println(s);
     }
    }

Output:Sachin Tendulkar

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 "sachin".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.




string comparison in java

We can compare two given on the basis of content and reference. It is used in authentication (equals() method), sorting (compareTo() method) etc.

There are three ways to compare String objects:

    By equals() method
    By = = operator
    By compareTo() method

1) By equals() method:
equals() method compares the original content of the string.It compares values of string for equality.String class provides two methods:

    public boolean equals(Object another){} compares this string to the specified object.
    public boolean equalsIgnoreCase(String another){} compares this String to another String, ignoring case.

    //<b><i>Example of equals(Object) method</i></b>
    
    class Simple{
     public static void main(String args[]){
    
       String s1="Sachin";
       String s2="Sachin";
       String s3=new String("Sachin");
       String s4="Saurav";
    
       System.out.println(s1.equals(s2));//true
       System.out.println(s1.equals(s3));//true
       System.out.println(s1.equals(s4));//false
     }
    }

Output:true
       true
       false

    //<b><i>Example of equalsIgnoreCase(String) method</i></b>
    
    class Simple{
     public static void main(String args[]){
    
       String s1="Sachin";
       String s2="SACHIN";
    
       System.out.println(s1.equals(s2));//false
       System.out.println(s1.equalsIgnoreCase(s3));//true
     }
    }

Output:false
       true

2) By == operator:
The = = operator compares references not values.

    //<b><i>Example of == operator</i></b>
    
    class Simple{
     public static void main(String args[]){
    
       String s1="Sachin";
       String s2="Sachin";
       String s3=new String("Sachin");
    
       System.out.println(s1==s2);//true (because both refer to same instance)
       System.out.println(s1==s3);//false(because s3 refers to instance created in nonpool)
     }
    }

Output:true
       false

3) By compareTo() method:
compareTo() method compares values and returns an int which tells if the values compare less than, equal, or greater than.
Suppose s1 and s2 are two string variables.If:

    s1 == s2 :0
    s1 > s2   :positive value
    s1 < s2   :negative value

    //<b><i>Example of compareTo() method:</i></b>
    
    class Simple{
     public static void main(String args[]){
    
       String s1="Sachin";
       String s2="Sachin";
       String s3="Ratan";
    
       System.out.println(s1.compareTo(s2));//0
       System.out.println(s1.compareTo(s3));//1(because s1>s3)
       System.out.println(s3.compareTo(s1));//-1(because s3 < s1 )
     }
    }

Output:0
       1
       -1
String Concatenation in Java

Concating strings form a new string i.e. the combination of multiple strings.

There are two ways to concat string objects:

    By + (string concatenation) operator
    By concat() method

1) By + (string concatenation) operator
String concatenation operator is used to add strings.For Example:

    //Example of string concatenation operator
    
    class Simple{
     public static void main(String args[]){
    
       String s="Sachin"+" Tendulkar";
       System.out.println(s);//Sachin Tendulkar
     }
    }

Output:Sachin Tendulkar

The compiler transforms this to:

    String s=(new StringBuilder()).append("Sachin").append(" Tendulkar).toString();

String concatenation is implemented through the StringBuilder(or StringBuffer) class and its append method.String concatenation operator produces a new string by appending the second operand onto the end of the first operand.The string concatenation operator can concat not only string but primitive values also.For Example:

    class Simple{
     public static void main(String args[]){
    
       String s=50+30+"Sachin"+40+40;
       System.out.println(s);//80Sachin4040
     }
    }

Output:80Sachin4040

Note:If either operand is a string, the resulting operation will be string concatenation. If both operands are numbers, the operator will perform an addition.
2) By concat() method
concat() method concatenates the specified string to the end of current string.
Syntax:public String concat(String another){}

    //<b><i>Example of concat(String) method</i></b>
    
    class Simple{
     public static void main(String args[]){
    
       String s1="Sachin ";
       String s2="Tendulkar";
    
       String s3=s1.concat(s2);
    
       System.out.println(s3);//Sachin Tendulkar
      }
    }

Output:Sachin Tendulker



Substring in Java


A part of string is called substring. In other words, substring is a subset of another string.

In case of substring startIndex starts from 0 and endIndex starts from 1 or startIndex is inclusive and endIndex is exclusive.

You can get substring from the given String object by one of the two methods:

    public String substring(int startIndex): This method returns new String object containing the substring of the given string from specified startIndex (inclusive).
    public String substring(int startIndex,int endIndex): This method returns new String object containing the substring of the given string from specified startIndex to endIndex.

In case of string:

    startIndex:starts from index 0(inclusive).
    endIndex:starts from index 1(exclusive).

Example of java substring

    //Example of substring() method
    
    class Simple{
     public static void main(String args[]){
    
       String s="Sachin Tendulkar";
       System.out.println(s.substring(6));//Tendulkar
       System.out.println(s.substring(0,6));//Sachin
     }
    }

Output:Tendulkar
              Sachin

Methods of String class

java.lang.String class provides a lot of methods to work on string. Let's see the commonly used methods of String class.
Method Description
1)public boolean equals(Object anObject) Compares this string to the specified object.
2)public boolean equalsIgnoreCase(String another) Compares this String to another String, ignoring case.
3)public String concat(String str) Concatenates the specified string to the end of this string.
4)public int compareTo(String str) Compares two strings and returns int
5)public int compareToIgnoreCase(String str) Compares two strings, ignoring case differences.
6)public String substring(int beginIndex) Returns a new string that is a substring of this string.
7)public String substring(int beginIndex,int endIndex) Returns a new string that is a substring of this string.
8)public String toUpperCase() Converts all of the characters in this String to upper case
9)public String toLowerCase() Converts all of the characters in this String to lower case.
10)public String trim() Returns a copy of the string, with leading and trailing whitespace omitted.
11)public boolean startsWith(String prefix) Tests if this string starts with the specified prefix.
12)public boolean endsWith(String suffix) Tests if this string ends with the specified suffix.
13)public char charAt(int index) Returns the char value at the specified index.
14)public int length() Returns the length of this string.
15)public String intern() Returns a canonical representation for the string object.

First seven methods have already been discussed.Now Let's take the example of other methods:
toUpperCase() and toLowerCase() method

    //<b><i>Example of toUpperCase() and toLowerCase() method</i></b>
    
    class Simple{
     public static void main(String args[]){
    
       String s="Sachin";
       System.out.println(s.toUpperCase());//SACHIN
       System.out.println(s.toLowerCase());//sachin
       System.out.println(s);//Sachin(no change in original)
     }
    }

Output:SACHIN
       sachin
       Sachin

trim() method

    //<b><i>Example of trim() method</i></b>
    
    class Simple{
     public static void main(String args[]){
    
       String s="  Sachin  ";
       System.out.println(s);//  Sachin  
       System.out.println(s.trim());//Sachin
     }
    }

Output:  Sachin
       Sachin

startsWith() and endsWith() method

    //<b><i>Example of startsWith() and endsWith() method</i></b>
    
    class Simple{
     public static void main(String args[]){
    
       String s="Sachin";
       System.out.println(s.startsWith("Sa"));//true
       System.out.println(s.startsWith("n"));//true
     }
    }

Output:true
       true

charAt() method

    //<b><i>Example of charAt() method</i></b>
    
    class Simple{
     public static void main(String args[]){
    
       String s="Sachin";
       System.out.println(s.charAt(0));//S
       System.out.println(s.charAt(3));//h
     }
    }

Output:S
       h

length() method

    //<b><i>Example of length() method</i></b>
    
    class Simple{
     public static void main(String args[]){
    
       String s="Sachin";
       System.out.println(s.length());//6
      }
    }

Output:6

intern() method
A pool of strings, initially empty, is maintained privately by the class String.
When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned.

    //<b><i>Example of length() method</i></b>
    
    class Simple{
     public static void main(String args[]){
    
       String s=new String("Sachin");
       String s2=s.intern();
       System.out.println(s2);//Sachin
      }
    }

Output:Sachin

No comments:

Post a Comment