String Handling in Java

Introduction

 
A String is a sequence of characters. In many other languages, a string is treated as a character array. But in Java, a string is treated as an object. After creating a string object you can not change it. So that is why it is said that a string is immutable. Java provides three string classes named String, StringBuffer and StringBuilder. The reason for the three-class is to reduce the problem of the mutability of the StringBuffer and StringBuilder classes; both are mutable. But in your mind, you might ask why not remove the String class. The reason is that an immutable String can be implemented more efficiently. The StringBuffer and StringBuilder classes have the same methods with one difference and that's synchronization. A StringBuffer is synchronized (which means it is thread-safe and hence you can use it when you implement threads for your methods) whereas StringBuilder is not synchronized (which implies it isn't thread-safe). So, if you aren't going to use threading then use the StringBuilder class as it will be more efficient than StringBuffer due to the absence of synchronization.
 
In this article, we describe the String class and its methods.
 

Java String class

 
The String class has several constructors (near about 13) and several methods (near about more than 60) so it's not possible to describe all of them but the important constructors and methods are described in this article.
 

Java String Constructor

  • String(): Initializes a newly created String object so that it represents an empty character sequence.
     
  • String(Char chars[]): Allocates a new String so that it represents the sequence of characters currently contained in the character array argument.
     
  • String(String strobj): Initializes a newly created String object so that it represents the same sequence of characters as the argument; in other words, the newly created string is a copy of the argument string.
     
  • String(byte[] bytes): Constructs a new String by decoding the specified array of bytes using the platform's default charset.

Java String Methods

 
Return Type Name Description
char charAt(int index) Returns the char value at the specified index.
int compareTo(String anotherString) Compares two strings lexicographically.
int compareToIgnoreCase( String str) Compares two strings lexicographically, ignoring case differences.
String concat(String str) Concatenates the specified string to the end of this string.
int indexOf(int ch) Returns the index within this string of the first occurrence of the specified character
string replace(char oldchar, char newchar) Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.
int length() Returns the length of this string.
char[] toCharArray() Converts this string to a new character array.
String trim() Returns a copy of the string, with leading and trailing whitespace omitted.
Static String valueOf(Object obj) Returns the string representation of the Object argument.
 
For example: In the following examples see carefully the corresponding output:
 
code 1
  1. public class Exp1{  
  2.    public static void main(String args[]){  
  3.       String s = "this is example of charAt() method";  
  4.       char ch = s.charAt(3);  
  5.       System.out.println(ch);  
  6.    }  
  7. }  
OUTPUT
 
Exp1.java.jpg
 
code 2
  1. public class Exp2{  
  2.    public static void main(String args[]){  
  3.       String s = "Hello";  
  4.       s = s.concat("World");  
  5.       System.out.println(s);  
  6.    }  
  7. }  
OUTPUT
 
exp2.jpg 
 
code 3
  1. public class Exp3{  
  2.    public static void main(String args[]){   
  3.       String s1 = "amit kumar gupta";  
  4.       String s2 = "amit kumar verma";  
  5.       String s3 = "AMIT KUMAR GUPTA";  
  6.       int n = s1.compareToIgnoreCase(s2);  
  7.       System.out.println(n);  
  8.            
  9.       n = s2.compareToIgnoreCase(s3);  
  10.       System.out.println(n);  
  11.           
  12.       n = s3.compareToIgnoreCase(s1);  
  13.       System.out.println(n);          
  14.        System.out.println("now compare with case sensitive");  
  15.          n = s1.compareTo(s2);  
  16.       System.out.println(n);  
  17.            
  18.       n = s2.compareTo(s3);  
  19.       System.out.println(n);  
  20.           
  21.       n = s3.compareTo(s1);  
  22.       System.out.println(n);  
  23.    }  
  24. }  
OUTPUT
 
exp3.jpg 
 
code 4
  1. import java.io.*;  
  2.  public class Exp4  
  3.        {  
  4.    public static void main(String args[])  
  5.           {  
  6.       String s = new String("string is a immutable string");  
  7.       String s1 = new String("article made by abhishek" );  
  8.       String s2 = new String("this c# corner.com site" );  
  9.       System.out.print("Index of m in string s :" );  
  10.       // use first version of indexOf method  
  11.       System.out.println(s.indexOf( 'm' ));  
  12.       System.out.print("Found Index :" );  
  13.       // use second version of indexOf method it take second argument as int  
  14.        staring search from this index  
  15.       System.out.println(s.indexOf( 'b'9 ));  
  16.       System.out.print("Found Index :" );  
  17.       // find the index nuber where the give s2 string is start  
  18.       System.out.println( s2.indexOf( s ));  
  19.       System.out.print("Found Index :" );  
  20.       System.out.println( s.indexOf( s, 10 ));  
  21.       System.out.print("Found Index :" );  
  22.       System.out.println(s.indexOf( s2 ));  
  23.    }  
  24. }  
OUTPUT
 
exp4.jpg  
 
code 5
  1. import java.io.*;  
  2. public class Exp5{  
  3.    public static void main(String args[]){  
  4.       String s = new String("c#corner.com");  
  5.       System.out.print("Return Value :" );  
  6.       System.out.println(s.replace('c''T'));  
  7.       System.out.print("Return Value :" );  
  8.       System.out.println(s.replace('o''D'));  
  9.    }  
  10. }  
OUTPUT
 
exp5.jpg  
 
code 6
  1. import java.io.*;  
  2.   public class Exp6{  
  3.    public static void main(String args[]){  
  4.       String S = new String("   Welcome to c-sharpcorner.com   ");  
  5.   
  6.       System.out.print("Return Value :" );  
  7.       System.out.println(S.trim() );  
  8.          System.out.println("length of following string");  
  9.           System.out.println(S);  
  10.    System.out.println("length="+S.length());  
  11.     
  12.    }  
  13. }  
OUTPUT
 
exp6.jpg 
 
Resources