Strings

Strings
  • Strings in java are objects of class string.
  • The String class is a standard class that comes with Java.
  • String class is defined in java.lang package.
  • A String literal is a sequence of characters in double quotes.
    • Example : "Smell Tea for a better taste".
  • Like for characters which cannot be entered directly from keyboard we use escape sequences in String Literals as well.
  • Strings are stored internally as Unicode characters.
Creating String Objects
    • A string variable only stores a reference to the object of class String.
      • String mystring="This is a main String".
    • This creates a String object with reference to mystring and initialises the same with "This is a maiden String".
    • String objects are immutable i.e. they cannot be changed.This means that you cannot extend or otherwise modify the String that an object of type String represents.
    • Whenever we perform operation on existing String objects we end up creating a new String object out of the same.
    • If characters are represented as surrogates they may occupy 4 bytes in a String per character.
    • You cannot leave a String variable only declared you must define it to a value if you do not want to use it now define it to "Null".
      • String anyString;  //Will give you an error.
      • String anyString=null;  //Will not give you an error.
    • Literal "Null" is an object reference value that does not refer to anything.
    • We can test weather a String variable refers to anything or not by a statement such as 
      • if(anyString==null)
      • {
      • System.out.println("This has no reference");
      • }
    • To discard a String object simply refer it to null
    Array of Strings
    • String[] names=new String[5];
    • This statement creates an array of String objects.
    • We have seen earlier that how argument of the main method an array of Strings takes arguments from console.
    Operations on Strings

    Joining Strings
    • We use "+" operator  to  join 2 strings and form a new String.
    • This operation generates a completely new String Object that is separate from the two original String objects.
    • If any operand is String the compiler converts the other operand into String and performs the merge operation.
    • If a String object contains "null" then it is converted into String "null".
    • The conversion of values of the basic types to type String is actually done by a static method "toString()".
    • String class contains a method called as valueOf() which converts a primitive type to String.This is again a static method.
    Comparing Strings
      • The expression String 1 == String 2 checks whether 2 String variables refer to same String.
      • To Compare two String variables we use equals method.
        • Example string1.equals(string2) compares 2 objects of type String and check whether they are equal or not.
      • To check equality of 2 String ignoring case of String characters, we use equalsIgnoreCase().
      String Interning
      • String interning ensures that no two String objects encapsulate the same String.So all String objects encapsulate unique Strings.
      • This means that if two String variables refer to Strings that are identical, the reference must be identical too.
      • Whenever we create a new String we just call the intern() method.
      • intern() method checks the String of caller object against all the String objects currently in existence.If a reference exists then current String object is discarded and caller object will contain reference to existing object encapsulating same String.
      • All the String constants and constant String expressions are automatically interned.
      • Any String object explicitly defined is automatically interned.Only String expressions involving reference to String variables need to be interned.
        • String str4="This is a cat"; - will be automatically interned.
        • String myString3=myString2.substring(0,23); - needs to be interned.
      Checking the Start and End of a String
        • startsWith()
          • str4.startsWith("This");
          • checks whether the String starts with a sequence.
          • is case sensitive
        • endsWith()
          • str4.endsWith("Cat");
        Sequencing Strings
        • compareTo()-checks weather one String is greater than or less than another.
          • Compares the String object for which it is called to a String argument and returns an integer.
          • It is negative if String object is less than argument.
          • It is positive if String object is greater than argument.
          • It is zero if String object is equal to the argument.
          • It compares the String by comparing successive corresponding characters starting with each character in String.
          • Characters are compared by comparing their Unicode representations.
          • One String is greater than another if the first character that differs from the corresponding character in the other String is greater than the character in corresponding String.
        Accessing String Characters
        • Extracting String characters is done using charAt();
          • Accepts integer argument that is the offset of the character position from the beginning of the String.
          • If the index is less than zero or greater than the index for last the last position in the String an exception is thrown
            • "StringIndexOutOfBoundsException"
        Searching Strings for characters
        • Two methods
          • indexOf();
          • lastIndexOf();
        • Searching character - indexOf() will search the contents of String text from the beginning and return the index position of the first occurrence of character from beginning of String.
          • If String is not found - 1 is returned
        • If we want to find the last occurrence of a character in String we use method lastIndexOf();
          • This method searches the String backward starting with last character in String.
        • To find the index of another character of first character use the following
          • bIndex=text.indexOf("b",++aIndex);
          • where aIndex is the Index of occurrence of first character.
          • You must check for a Index to be not equal to -1 in this case.
        • Count the occurance of Character in String can be accomplished using
          • while((aIndex=text.indexOf('a',++aIndex))>-1){++count;}
        Searching for Substrings
          1. The indexOf() and lastIndexOf() methods also come in versions that accept a string as the first argument, which will search this String rather than a single character.
          Extracting Substrings
          1. Substring() method is used to extract a substring from a string.
            1. String place = "Java Implant".
            2. String lastWord=place.substring(5);
            3. This will return the last word "Implant".
            4. Substring(5,1) will return characters that starts from 5th position till 1st position from this position.
            5. An exception is thrown if index is outside the bounds of the String.
          Tokenizing a String
          1. Split method is for splitting a String into tokens.
          2. Regular Expressions are used for splitting a String.
          3. The split() method expects two arguments.
            1. The first argument is a String object that specifies a pattern for delimiter.
            2. The second argument is an integer value that is an integer value that is a count of the maximum number of times the pattern can be applied to find tokens.
              1. This affects the maximum number of tokens that can be found.
          4. The tokens returned by String method are an array of type String[].
          Modifying String Objects
          1. String objects are immutable so each of its member functions provide or return a new String object.
          Replacing characters in a String
          1. replace() - replace() function replaces a character throughout a String with another.
            1. String newtext=text.replace(' ','/');
              1. first argument specifies character to be replaced.
              2. Second argument specifies character to be substituted.
            2. The object returned is a new String object.
          2. trim() - removes whitespaces from end and beginning of a String.
          Creating a character Array from String 
            1. toCharArray() - creates a character array from a String object.
            2. returns an array of characters that constituted String in sequential order.
            3. We can also extract substring as an array of characters using the method getChars();
              1. Four arguments are
                1. the index position of first character
                2. the index position of last character
                3. Name of the array to hold characters extracted(type char[])
                4. index of the array to hold the first character(type int)
                  1. text.getChars(9,12,textArray,0);
                5. Text Array must be large enough to hold the characters.
            Using collection based for loop with String
              1. We can iterate a String using chars in a collection based for loop.
                1. for(char ch:str.toCharArray()){}
                  1. Here str is a string.
              Obtaining the characters in a String as an Array of Bytes
              1. getBytes() is used to get the characters in a String as Array of bytes.
                1. byte[] textArray=text.getBytes();
              Creating String Objects from character Arrays
              1. copyValueOf() method is used to create String object from an array of characters.
              2. This is a static method and can be used as 
                1. String text=String.copyValueof(textArray);
              3. This can also be achieved by creating a new String object and initialising the same using an array of characters.
                1. String text = new String(textArray);
              4. copyValueOf function can also be used as 
                1. String text=String.copyValueOf(textArray,9,3);
              5. Similarly we can use constructor
                1. String text=new String(textArray,9,3);
              Mutable Strings
              1. There are two classes for Mutable Strings
                1. String Builder
                2. String Buffer
              2. Strings that can be changed are called as mutable strings.
              3. String Buffer class is used internally to perform many operations on Strings.Once we have the required String we convert it to object of type String.
              4. String Buffer objects are safe for use by multiple threads, where as String Builder objects are not.
              5. Threads are independent execution processes within a program that can execute concurrently.
                1. e.g. an application that involves acquiring data from several remote sites could implement data transfer from each remote site as a separate thread.
                2. For concurrent thread operations we use String Buffer class object i.e. where one thread is trying to access object while other is trying to modify the same.
                3. If our mutable String object will be accessed by only a single thread then we should use String Builder Objects.
              Creating String Buffer Objects
              1. StringBuffer aString=new StringBuffer("Golden Eggs");
              2. We cannot directly initialise a String Buffer object as in case of String.
              3. We can also create a String Buffer object using a reference stored in variable of type String.
                1. StringBuffer buffer =new StringBuffer(String object);
              4. To set a String Buffer object to null use
                1. StringBuffer obj=null;
              Capacity of a String Buffer Object
              1. StringBuffer contains a block of memory called as "buffer".
                1. This may or may not contain String
              2. So the length of the String a StringBuffer object contains is different from the length of the buffer that the object contains.
              3. The length of the buffer is referred to as the capacity of the String Buffer object.
              4. Once you create a StringBuffer object, you can find the length of the String it contains, by using length() method.
              5. When we create a StringBuffer object the capacity is the length of the String + 16 bytes.
              6. The capacity grows automatically as we add to the String to accommodate a String of any length.
              7. You can also specify an initial capacity when we create an object e.g. 
                1. StringBuffer newString=new StringBuffer(50);
              8. The default capacity of String Buffer object is 16 characters.
              9. To find out capacity of a String Buffer object at any given time use capacity() method.
              10. Ensure capacity() enables you to change the default capacity of a StringBuffer object.
              Changing the String Length for a String Buffer object
              1. We can change the length of a String Buffer using setLength();
              2. If the length is reduced the letters chopped off are lost.
              3. If we set the length greater than capacity is increased to a value twice the original capacity plus two.If the length is still greater than the new capacity will be same as length you set.
              4. If you specify a negative length we get a StringIndexOutOfBoundsException().
              Adding to StringBuffer object
              1. String aString=new StringBuffer("Time is rare");
                1. aString.append("don't spare");
              2. .append() method enables you to add a String to the end of the existing String stored in StringBuffer object.
              3. The length of the String contained in StringBuffer object is increased by the length of the String that you add.
              4. The capacity is automatically increased whenever we try to accommodate a longer String.
              5. append("") method returns reference to an extended StringBuffer object.
              Appending a Substring
                1. Another version of the append() method adds part of a String object to a StringBuffer object.
                2. This version of append() requires you to specify two additional arguments
                  1. Index position of first character in String object that is to be appended.
                  2. Total number of characters to be appended.
                    1. StringBuffer buf=new StringBuffer("Ok");
                    2. String sappend="Then its fine";
                    3. buf.append(append,0,4);
                3. The capacity of StringBuffer object is automatically increased by the length of the appended Substring.
                Appending Basic Types
                1. We have set of versions of append() method that will enable you to append the String equivalent of values of following primitive types: boolean, char,byte,short,int,long,float and double.
                2. In each case the value is converted to a String equivalent which is then appended to the object.
                3. Append may take boolean which is appended as "True" or "False".
                4. Append may take char array the contents of array are appended to the String Buffer object as a String.
                Finding position of a Substring
                1. lastIndexOf() method - The simpler of the two versions of this method requires just 1 argument i.e. String we are looking for.
                2. This method returns the last position of the occurrence of String you are searching for as a value of type Int.
                3. method returns -1 if substring is not found.
                4. second version is 
                  1. position=str.lastIndexOf("substr",3);
                  2. This statement starts teaching from position 3.
                Replacing a Substring in buffer
                1. replace() method is used
                2. 3 arguments are required
                  1. first 2 are of type int and specify the start index in the buffer and one beyond the end index of the substring to be replaced.
                  2. The third argument is of type String and is the String to be inserted.
                Inserting Strings
                1. insert() method of the object is used to insert String into a StringBuffer object.
                  1. First argument specifies the index position of the object where first character needs too be inserted.
                  2. Second argument specifies the text to be inserted.
                Extracting characters from a mutable String
                1. Two methods can be used for this purpose
                  1. charAt()
                  2. getchars()
                2. Both these methods work in the same way as methods of String class.
                Inserting/Deleting characters
                1. buf.setCharAt(3,'Z');
                2. buf.deleteCharAt(10);
                3. buf.delete(5,9)
                  1. deletes characters between the first argument and (last argument -1) positions.
                Reverse a String
                1. Reverse function reverses a String.
                Creating a String object from a String Buffer Object
                1. toString() - this method of StringBuffer class returns a String() object.
                  1. String saying=proverb.toString)();
                Example of String:
                 public class stringOps   
                 {  
                      public void checkNull(String str)  
                      {  
                           if(str==null)  
                           {  
                                System.out.println("This has no reference");  
                           }  
                      }  
                      public void traceArray(String[] arr)  
                      {  
                           System.out.println("Players in Team are : ");  
                           for(String str:arr)  
                           {  
                                System.out.println(str);  
                           }  
                      }  
                      public void joinStrings(String str1,String str2)  
                      {  
                           System.out.println(str1+" "+str2);  
                      }  
                      public void compareStrings(String str1,String str2)  
                      {  
                           if(str1==str2)  
                           {  
                                System.out.println("Both Strings are same and belong to same object");  
                           }  
                           else  
                           {  
                                if(str1.equals(str2))   
                                {  
                                     System.out.println("Both Strings are same but belong to different objects");  
                                }  
                                else  
                                {  
                                     System.out.println("Both Strings are different");  
                                }  
                           }  
                      }  
                      public int checkCharacterOccurance(String str,char c)  
                      {  
                           int aIndex=-1;  
                           int count=0;  
                           while((aIndex=str.indexOf(c,++aIndex))>-1)  
                           {  
                                ++count;  
                           }  
                           return count;  
                      }  
                      public static void main(String args[])  
                      {  
                           String myString="This is a maiden String"; //A reference to a new String is created  
                           String nullString=null;  
                           stringOps s1=new stringOps();  
                           s1.checkNull(nullString);  
                           //Array of Strings  
                           String []players={"RG Sharma","S Dhawan","RR Pant","SK Raina","MK Pandey","KD Karthik","V Shankar","Washington Sundar","SN Thakur","JD Unadkat","YS Chahal"};  
                           s1.traceArray(players);  
                           String str1="Empty in String is represented as";  
                           // Null String  
                           s1.joinStrings(str1,nullString);  
                           String myString1="This is a maiden String"; //A reference to a new String is created  
                           String myString2="This is a maiden String copy";  
                           String myString3=myString2.substring(0,23);  
                           // compare Strings  
                           s1.compareStrings(myString, myString1);  
                           s1.compareStrings(myString, myString2);  
                           s1.compareStrings(myString, myString3);  
                           // Intern Example  
                           myString3=myString3.intern();  
                           s1.compareStrings(myString, myString3);  
                           //Starts With  
                           if(myString.startsWith("An"))  
                           {  
                                System.out.println("Second letter starts with a vowel");  
                           }  
                           else  
                           {  
                                System.out.println("Second letter does not start with a vowel");  
                           }  
                           //Ends With  
                           if(myString2.endsWith("copy"))  
                           {  
                                System.out.println("Ends With Copy");  
                           }  
                           //character At   
                           int pos=3;  
                           char ch=myString1.charAt(pos);  
                           System.out.println("Character at position "+pos+" is "+ch);  
                           //Index of  
                           ch='s';  
                           pos=myString1.indexOf(ch);  
                           int lpos=myString1.lastIndexOf(ch);  
                           System.out.println("Position of "+ch+" is "+pos);  
                           System.out.println("Last Position of "+ch+" is "+lpos);  
                           //check Character Occurance  
                           int inl=s1.checkCharacterOccurance(myString,'i');  
                           System.out.println("Occurance of character is "+inl);  
                           //Substring  
                           String name="Java Implant";  
                           String substr1=name.substring(5);  
                           System.out.println(substr1);  
                           String substr=myString.substring(10,16);  
                           System.out.println(substr);  
                           //Tokenizing a String  
                           String [] nameArr=name.split(" ");  
                           for(String str:nameArr)  
                           {  
                                System.out.println(str);  
                           }  
                           nameArr=myString.split(" ",3);  
                           for(String str:nameArr)  
                           {  
                                System.out.println(str);  
                           }  
                           //Replacing characters  
                           String text="There are a boy";  
                           System.out.println(text);  
                           text=text.replace("are","is");  
                           System.out.println(text);  
                           //Trim  
                           String text1="  These whitespaces in a sentence needs to be removed   ";  
                           System.out.println(text1);  
                           text1=text1.trim();  
                           System.out.println(text1);  
                           //Character Array  
                           char [] textArray=new char[30];  
                           textArray=text1.toCharArray();  
                           for(char ch1:textArray)  
                           {  
                                System.out.println(ch1);  
                           }  
                           System.out.println("=================>");  
                           char [] textArray1=new char[12];  
                           text1.getChars(6,17,textArray1,0);  
                           for(char ch1:textArray1)  
                           {  
                                System.out.println(ch1);  
                           }  
                           //String from array of chars  
                           String halfString=new String(textArray1);       
                           System.out.println(halfString);  
                           //Array of Bytes from String  
                           byte[] byteArray=halfString.getBytes();  
                           for(byte b1:byteArray)  
                           {  
                                System.out.println(b1);  
                           }  
                           //StringBuffer  
                           StringBuffer buffStr=new StringBuffer("Golden Eggs");  
                           int len=buffStr.length();  
                           int cap=buffStr.capacity();  
                           System.out.println(len+" is length amd capacity is adding 16 to it i.e. "+cap);  
                           //Increasing length of StringBuffer.  
                           buffStr.setLength(40);  
                           len=buffStr.length();  
                           cap=buffStr.capacity();  
                           System.out.println(len+" is length amd capacity is adding 16 to it i.e. "+cap);  
                      }  
                 }  
                
                Output :

                No comments:

                Post a Comment