METHODS OF STRING CLASS

Methods of String Class


    The following are some of the methods in String class

    1. concat():

    • By using concat () method we can append the two String objects. It works same as a ‘+’ operator . As a java developer using ‘+’ operator is not advisible.Why because inorder to achive 100% OOP’S in java program we should use only in terms of class,objects and methods by avoiding the using operators.

    • By using this method second parameter value is added at the end of first parameter value.

    • Syntax:

    • public String concat(String str);

      Example 1:

       
                      
                       public class Concate
                       {
                           public static void main(String[] args)
                           {
                               String s1="abc";
                               String s2="xyz";
                               String s3=s1.concat(s2);
                               String s4=new String("123");
                               String s5="456".concat(s4);
                               System.out.println(s1);
                               System.out.println(s3);
                               System.out.println(s5);
                           }
                       }                

         Output:

      abc abcxyz 456123
      javapadho
      Heap memory by manage by String class

    2. trim():

    • The trim () method is one of the important method in string class.

    • If we want to store some data in database the space should be given between the data values.
        Eg: " abc xyz "

    • In the above example space was given in the starting, middle and ending of the word. Starting space is called as leading space and ending space is called as tailing space.

    • If we want to delete empty space(i.e. leading and tailing spaces) automatically for a particular string ,the sun people came up with one method in string class with the name of trim ( ).

    • Syntax:

    • public String trim( )
      {

      }
    • The return type should be string.

    • Example 2:

       
                      
                       public class TrimSpace
                       {
                           public static void main(String[] args)
                           {
                               System.out.println("Trim method");
                               String s="  abc    ";
                               System.out.println(s);
                               String s1=s.trim();
                               System.out.println(s1);
                               System.out.println(s);
                           }
                       }                

         Output:

      E:\lab\sdjbatch\src>java TrimSpace Trim method abc abc abc
      javapadho
      Heap memory by manage by String class
    • By using trim( ) method we can delete spaces from first and last spaces and it is not possible in the middle.

    • In string class the toString( ), equals( ) and hashCode( ) methods is already overloaded.

    3. charAt( ):

    • The charAt( ) method is one of the method in string class.

    • This method will take character index as input value and it returns corresponding index value as output.

    • It takes integer type as input value and returns output as charcter value.

    • charAt( ) will return one character from string object with specified location.

    • Syntax:

    • public char charAt(int indexvalue)
      {
       ---------
      }
    • The return type should be char.

    • Example 3:


      String s1=”welcome to SDJ”;
    • The index value starts with zero and ends with length-1.

    • In the above example index value of ‘w ‘ starts 0,1,2,3…….. and ends with 14 including spaces also takes index values.

    •  
                      
                       public class CharAt
                       {
                           public static void main(String[] args) 
                           {
                               String s1="welcome to SDJ";
                               System.out.println(s1.charAt(6));
                               char c1=s1.charAt(9);
                               System.out.println(c1);
                               /*   System.out.println(s1.charAt(20));   */ 
                               /*   In this line one Runtime exception will raise   */
                               /*   i.e String Index Out Of Bound Exception     */ 
                               /*   Why because there is no character or  String  */
                               /*   for that value i.e(20).*/     
                           }
                       }                

         Output:

         e
         o
         

    • If we want to give index value other than in between the given string at that time one exception will raise i.e String Index Of exception.

    4. indexOf( ):

    • The indexOf( ) is one of the important method in string class.

    • If we want to find out any index value in any string object we use this method.

    • The indexOf( ) method will takes input parameter as character (or) string and output as integer value for specified character in string object.

    • The return type of indexOf( ) should be int.

    • Syntax:

    • public int indexOf(char c);
      public int indexOf(String s);
      public int indexOf(char chi, into start Index);
      public into indexOf(char chi, into start Index);
      Note
      • IndexOf( ) will return index value for specified character or string from the string object. It will search characters from left to right or first to last from the starting of given string object.

      • If we have any character more than one time we will get first position character index value.

      • If we give entire string it will takes first character as output.

      • The start index value searching begins with given index.

      • If that string object is not contain specified character or string then the indexOf( ) method will return -1 as output.

      Example 4:

       
                      
                       package com.sdj.pack1;
                       public class IndexOf
                       {
                           public static void main(String[] args)
                           {
                               String s1 ;
                               s1= 'we Are Two But Our Goal Is One';
                               System.out.println(s1.indexOf('T'));
                               int s2=s1.indexOf('o');
                               System.out.println(s2);
                               System.out.println(s1.indexOf(' '));
                               System.out.println(s1.indexOf('V'));
                               System.out.println(s1.indexOf('o'));
                               System.out.println(s1.indexOf('o',14) );
                               System.out.println(s1.indexOf(“Our”,13);
                           }
                       }                

         Output:

      7 9 2 -1 9 20 15

      Explanation:

      • In line 10 the character ‘v’ is not contained in the given string object thats why it gives output as -1.

      • In line numbers 7 and 11 we will give ‘o’ as input character. Even though we will give two inputs with same character it will takes first character only.

      • In line 12 even we will give same character (i.e zero) it gives output value as 20 why because based on the given start index value it begins searching from the string object.

    5. lastIndexOf( ):

    • If we want to search the string object from last to first (or) right to left.

    • The lastIndexOf( ) method is same as indexOf( ) method but there is only one difference the lastIndexOf( ) will start from last to first from the string object.

    • The lastIndexOf( )will take input parameter as character (or) string and gives output as integer value.

    • If we will give string parameter for searching it takes last character as output for a given specified string.

    • Syntax:

    • public into lastIndexOf(char chi);
      public int lastIndexOf(String s);
      public int lastIndexOf(char chi, into LastIndex);
      public into indexOf(String s, int LastIndex);
    • The return type should be int.

    • The lastIndex value searching starts at end of given index.

    • The lastIndexof( ) method returns last index of specified substring if it found, else it will return -1.

    • Example 5:

       
                      
                       public class IndexOf
                       {
                           public static void main(String[] args)
                           {
                               String s1 ;
                               s1="we Are Two But Our Goal Is One";
                               System.out.println(s1.indexOf("T"));
                               int s2=s1.indexOf("o");
                               System.out.println(s2);
                               System.out.println(s1.lastIndexOf(" "));
                               System.out.println(s1.lastIndexOf("V"));
                               System.out.println(s1.lastIndexOf("o"));
                               System.out.println(s1.lastIndexOf("o",14) );
                               System.out.println(s1.lastIndexOf("Our",13));
                           }
                       }                

         Output:

      9 26 -1 20 9 -1

    6. length( ):

    • The length( ) method is one of the important method in string class.

    • Return type of length( ) method should be int.

    • The length( ) method returns number of characters inside the string object in integer format .

    • The length( ) method takes input as string object and displays number of characters as output in integer format with the given specified string object.

    • Syntax:

    • public int length();
      {
       ------------
      }
    • The maximum index of the string is length-1.

    • The length of the string starts from 1 and index value starts from 0 (i.e length-1).

    • Example 6:

       
                      
                       import java.util.Scanner;
                       public class LengthMethod
                       {
                           public static void main(String[] args)
                           {
                               String s1="Welcome to SDJ";
                               String s2="We Are Two But Our Goal Is One";
                               Scanner sc=new Scanner(System.in);
                               System.out.println("Enter any string");
                               String s3=sc.nextLine();
                               System.out.println("length of s1:" +s1.length());
                               System.out.println("length of s2:"+s2.length());
                               System.out.println("string length is:" +s3.length());
                           }
                       }                

         Output:

      Enter any string Praveen Kumar Chandaliya length of s1:14 length of s2:30 length of s3:24

    7. substring( ):

    • The substring( ) is a string ,we use substring( ) method for selecting a string from a paragraph or some portion of string.

    • Syntax 1:

    • public String subString(int startindex);
      Note

      It will returns entire remaining string starting from specified index.


    • Syntax 2:

    • public String subString(int startindex, int endindex);
      Note
      • It will returns sub string between the starting index to ending index from specified string object. In this start Index is included & end Index is excluded.

      • The return type for substring should be string type only.

      Example 7:

       
                      
                       package com.sdj.pack1;
                       public class SubString 
                       {
                           public static void main(String[] args)
                           {
                               String s="Welcome to SDJ";
                               System.out.println(s.length());
                               String s1=s.substring(8);
                               System.out.println("string s1 is:"+s1);
                               String s2=s.substring(11, 14);
                               System.out.println("string s2 is:"+s2);
                               String s3=new String(s.substring(0,7));
                               System.out.println("String s3 is:"+s3);
                               String s4="Praveen "+s.substring(11);
                               System.out.println("string s4 is:"+s4);
                               /*   String s5=s.substring(12, 17);   */
                           }
                       }                
      javapadho
      Heap memory by manage by String class

         Output:

         string s1 is : to SDJ
         string s2 is : SDJ
         String s3 is : Welcome
         string s4 is : Praveen SDJ
         At line number 15 this exception will raise
         
         
         
         

      Note
      • In substring method for every string operation ,it should not create new object but it will point to the value from existing object based on substring operation.

      • The following figure shows how object is created and how it is points to the existing object for substring method.

    • When String objects are created?

    • 1. Through pure literals.
      2. Through New operator.
      3. If we modify any existing object at that time new object will be created.


    8. Split( ):

    • The split ( ) method is important method in string class. sun people came up with this method to split the string objects based on given splitting character (or) delimiter character.

    • Syntax:

    • public String[] split(String)
      {
      --------
      }

    9. EqualsIgnoreCase( ):

    • In equals( ) method it will compare (i.e here it will compare based on the ascii key code), but here it compares based on the content but not based on the ascii code.

    • It is available to string class but doesn’t override in object class.

    • Example

      String s1=”abc”; String s2=”ABC”; s1.equals(s2); //false
      javapadho
      Heap memory by manage by String class

      Example 8:

       
                      
                       public class Hello 
                       {
                           public static void main(String[] args)
                           {
                               String s1 = "abc";
                               String s2 = "ABC";
                               String s3 = "Abc";
                               System.out.println(s1.equals(s2));
                               System.out.println(s1.equalsIgnoreCase(s2));
                               System.out.println(s1.equals(s3));
                               System.out.println(s1.equalsIgnoreCase(s3));
                               System.out.println(s2.equals(s3));
                               System.out.println(s2.equalsIgnoreCase(s3));
                           }
                       }                

         Output:

      False true false true false true

    10. replace( ):

    • if we want to replace existing character with new character this method is used.

    • Syntax:

    • public String replace(char Existingchar, char new char);
    • if we want to replace existing string with new string this method is used.

    • Syntax:

    • public String replace(String Existing string, String new String);

      Example 9:

       
                      
                       public class ExistingCharacter
                       {
                           public static void main(String[] args)
                           {
                               String s1 = "Hello world";
                               System.out.println(s1);
                               String s11 = "Welcome To sdj";
                               String s2 = s1.replace("H", "h");
                               System.out.println(s2);
                               String s22 = s11.replace("T", "t");
                               System.out.println(s22);
                               s2 = s1.replace("Hello", "Hi");
                               System.out.println(s2);
                               s22 = s11.replace("To", "2");
                               System.out.println(s22);
                               s2 = s1.replace(" ", "_");
                               System.out.println(s2);
                           }
                       }                

         Output:

      Hello world hello world Welcome to SDJ Hi world Welcome 2 SDJ Hello_world