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 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 wll be more efficient than StringBuffer due to the absence of synchronization.
In this article we describe the String class and its methods.

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.

Constructor summary

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.


Method Summary

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
public class Exp1{
   public static void main(String args[]){
      String s = "this is example of charAt() method";
      char ch = s.charAt(3);
      System.out.println(ch);
   }
}

OUTPUT:
Exp1.java.jpg

code-2
public class Exp2{
   public static void main(String args[]){
      String s = "Hello";
      s = s.concat("World");
      System.out.println(s);
   }
}

OUTPUT:

exp2.jpg

code-3
public class Exp3{
   public static void main(String args[]){
      String s1 = "amit kumar gupta";
      String s2 = "amit kumar verma";
      String s3 = "AMIT KUMAR GUPTA";
      int n = s1.compareToIgnoreCase(s2);
      System.out.println(n);
        
      n = s2.compareToIgnoreCase(s3);
      System.out.println(n);
        
      n = s3.compareToIgnoreCase(s1);
      System.out.println(n);        
       System.out.println("now compare with case sensitive");
         n = s1.compareTo(s2);
      System.out.println(n);
        
      n = s2.compareTo(s3);
      System.out.println(n);
        
      n = s3.compareTo(s1);
      System.out.println(n);
   }
}
OUTPUT

exp3.jpg

code-4
import java.io.*;
 
public class Exp4
       {
   public static void main(String args[])
          {
      String s = new String("string is a immutable string");
      String s1 = new String("article made by abhishek" );
      String s2 = new String("this c# corner.com site" );
      System.out.print("Index of m in string s :" );
      // use first version of indexOf method
      System.out.println(s.indexOf( 'm' ));
      System.out.print("Found Index :" );
      // use second version of indexOf method it take second argument as int
       staring search from this index
      System.out.println(s.indexOf( 'b', 9 ));
      System.out.print("Found Index :" );
      // find the index nuber where the give s2 string is start
      System.out.println( s2.indexOf( s ));
      System.out.print("Found Index :" );
      System.out.println( s.indexOf( s, 10 ));
      System.out.print("Found Index :" );
      System.out.println(s.indexOf( s2 ));
   }
}

OUTPUT

exp4.jpg

code-5
import java.io.*;
public class Exp5{
   public static void main(String args[]){
      String s = new String("c#corner.com");
      System.out.print("Return Value :" );
      System.out.println(s.replace('c', 'T'));
      System.out.print("Return Value :" );
      System.out.println(s.replace('o', 'D'));
   }
}
OUTPUT

exp5.jpg

code-6


import java.io.*;
 
public class Exp6{
   public static void main(String args[]){
      String S = new String("   Welcome to c-sharpcorner.com   ");

      System.out.print("Return Value :" );
      System.out.println(S.trim() );
         System.out.println("length of following string");
          System.out.println(S);
   System.out.println("length="+S.length());
 
   }
}

OUTPUT

exp6.jpg

Resources

Up Next
    Ebook Download
    View all
    Learn
    View all