☰ Topics

String Handling

Many other language that implement string as characters arrays, Java implements String as object of type String. When we create a string object, we are creating a string that cannot be changed i.e once a string object has been created, we cannot change the characters that comprise that string. When we write any string under double quotes it makes by literal object in constant pool. The java.lang.String class provides a lot of methods to work on String. By the help of these methods we can perform operations on strings such as trimmimng, concatenating, comparing, replacing etc. Few of the functions of String are given below:

  1. charAt(): It returns the single character at the specifed index. It is used in linked list. The index number starts from 0. Eg: s1.charAt(3);

  2. getBytes(): It returns the byte array of the string. In other words, it returns the ASCII value of the given string.

  3. equals(): It belongs to String class. It compares two given Strings based on the contents of the string. If all characters are matched, it returns 1 or true. It is case-sensitive & is used for reference type comparision. == in java compares primitive datatype & is used for value type comparision, in abstract datatype it compares the address where data is stored. Eg: (a.equals(b))

  4. equalsIgnoreCase(): It works the same as equals() function but does a case insensitive comparision.

  5. startsWith(): It checks if the string starts with given prefix. It returns true if this string starts with given prefix else returning false.

  6. endsWith(): It checks if the string ends with given suffix. It returns true if this string ends with given suffix else returns false.

  7. getChars(): It is used to extract more than one character at a time. Syntax:
    getChars(sourcestart, sourceend, target, targetstart);

  8. substring(): It returns extracted part of the string. We need to pass starting position and ending position in the java substring method where start index is inclusive and end index is exclusive. If end index is not given it will consider the whole string till the end.

  9. concat(): It combines specified string at the end of this string and returns a combined string. It is like appending another string. + is also used for concatination and it can concatenate infinite number of strings whereas concat() can concatenate only two strings at a time.

  10. replace(): It returns a string replacing all the old character to new character.

  11. split(): It splits the string against given regular expression and returns a character array. It is also called as tokenizer.

  12. toLowerCase(): It converts all the characters of the string into lower case.

  13. toUpperCase(): It converts all characters of the string into upper case letters.

  14. trim(): It eliminates leading and trailing spaces. It doesn't omits middle spaces. It is used in the coding of password field.

  15. toString(): It converts the given object or value to string.

  16. contains(): It searches the sequence of characters in the string. It returns true if sequence of char values are found.

  17. indexOf(): It returns the first occurence of given character value or substring. If it is not found, it returns -1. Its return type is integer.

  18. isEmpty(): It checks if the string is empty. It returns true, if length of string is 0.

  19. lastIndexOf(): It returns the last occurence of the given character value. If it is not found, it returns -1.

  20. length(): It returns the count of total number of characters.

  21. toCharArray(): It converts the string into character array. Its length is similar to the string.

  22. compareTo(): It compares the given string with current string. It returns positive number, negative number or 0.

  23. valueOf(): It is used for value type conversions. It converts different types of values into String. It is similar to toString() function but toString() is a non-static function (calls with the help of object) whereas, valueOf() is a static function (calls with the help of class) belongs to String class.


class exFun
    {
        public static void main(String[] args)
        {
            String s="Praveen";
            System.out.println(s);
            char t = charAt(4);
            System.out.println(t);
            byte[] b = s.getBytes();
            System.out.println(b[3]);
            String s1 = new String(b);
            System.out.println(s1);
            if(s.equals(s1))
                System.out.println("True");
            else
                System.out.println("False");
            String empcode = "hr1001";
            System.out.println(empcode.startsWith("hr"));
            System.out.println(s.substring(2));
            System.out.println(s.substring(2,4));
        }
    }
    
OUTPUT:-

Praveen
e
118
Praveen
True
True
raveen
av

Mutable and Immutable Strings: String class is immutable which means its growth is not possible or unmodifiable or unchangeable. String is a special datatype, we can create its literal as well as object. It is slow & consumes more memory when we concat too many strings because everytime it creates new instance (or variable).

StringBuffer class: It represents growable and writeable character sequences. It is a peer class of string that provides much of the functionality of strings. On concatenating the string grows, it is not recreated. Therefore, it is fast and less memory consuming. It is not a special datatype. In buffer class, we can concatenate in backward direction also.

Both String and StringBuffer classes are defined in java.lang.*. Thus, they are available to all programs automatically.