Core Java - String

Strings which are widely used in Java programming are a sequence of characters. In the Java programming language, strings are objects. The Java platform provides the String class to create and manipulate strings.

Creating Strings:
The most direct way to create a string is to write:
    String greeting ="Hello world!";

Whenever it encounters a string literal in your code, the compiler creates a String object with its value, in this case, "Hello world!'.

As with any other object, you can create String objects by using the new keyword and a constructor. The String class has eleven constructors that allow you to provide the initial value of the string using different sources, such as an array of characters:
Eg:
    public class StringDemo{
        public static void main(String args[]){
        char[] helloArray ={'h','e','l','l','o','.'};
        String helloString =new String(helloArray);
        System.out.println("String is : " +helloString);
        }
    }

Output :
String is : hello.
Note:
The String class is immutable, so that once it is created a String object cannot be changed. If there is a necessity to make a lot of modifications to Strings of characters, then you should use String Buffer & String Builder Classes.

String Length:
Methods used to obtain information about an object are known as accessor methods. One accessor method that you can use with strings is the length() method, which returns the number of characters contained in the string object.
After the following two lines of code have been executed, len equals 17:
Eg:
    public class StringDemo{
        public static void main(String args[]){
        String palindrome ="Dad this is String topic";
        int len = palindrome.length();
        System.out.println("String Length is : "+ len );
        }
    }

Output :
String length is : 24

Concatenating Strings:
The String class includes a method for concatenating two strings:
    string1.concat(string2);

This returns a new string that is string1 with string2 added to it at the end. You can also use the concat() method with string literals, as in:
    "My name is ".concat("immutable");

Strings are more commonly concatenated with the + operator, as in:
    "Hello,"+" world"+"!"

Output :
"Hello, world!"
Eg:
    public class StringDemo{
        public static void main(String args[]){
        String string1 ="saw I was ";
        System.out.println("Dad "+ string1 +"good in this topic");
        }
    }

Output :
Dad saw I was good in this topic

Creating Format Strings:
You have printf() and format() methods to print output with formatted numbers. The String class has an equivalent class method, format(), that returns a String object rather than a PrintStream object. Using String's static format() method allows you to create a formatted string that you can reuse, as opposed to a one-time print statement.
Eg:
    System.out.printf("The value of the float variable is "+ "%f, while the value of the integer "+ "variable is %d, and the string "+
    "is %s", floatVar, intVar, stringVar);

you can write:
    String fs;
    fs =String.format("The value of the float variable is "+ "%f, while the value of the integer "+ "variable is %d, and the string "+
                        "is %s", floatVar, intVar, stringVar);
    System.out.println(fs);

String Methods:

  S.NO	    Methods	                                                    Description
  ----- -------------------------------------------------   ---------------------------------------------------------
    1.	char charAt(int index)	                              Returns the character at the specified index.

    2.	int compareTo(Object o)	                              Compares this String to another Object.

    3.	int compareTo(String anotherString)                   Compares two strings lexicographically.

    4.	int compareToIgnoreCase(String str)                   Compares two strings lexicographically, ignoring case differences.

    5.	String concat(String str)                             Concatenates the specified string to the end of this string.

    6.	boolean equals(Object anObject)	                      Compares this string to the specified object.

    7.	boolean equalsIgnoreCase(String anotherString)	      Compares this String to another String, ignoring case considerations.

    8.	String toLowerCase()	                              Converts all of the characters in this String to lower case using 
                                                              the rules of the default local.

    9.	String toString()                                     This object (which is already a string!) is itself returned.

    10.	String toUpperCase()	                              Converts all of the characters in this String to upper case 
                                                              using the rules of the default local.

    11.	String replace(char oldChar, char newChar)            This method returns a new string resulting from replacing all 
                                                              occurrences of oldChar in this string with newChar.

    12.	String replaceAll(String regex, String replacement)   This method replaces each substring of this string that matches 
                                                              the given regular expression with the given replacement.

    13.	String replaceFirst(String regex, String replacement) This method replaces the first substring of this string that 
                                                              matches the given regular expression with the given replacement.
                                                              
    14.	String[] split(String regex)	                      This method has two variants and splits this string around matches 
                                                              of the given regular expression.

The above mentioned methods are explained here:

1. char charAt(int index)
Description:
This method returns the character located at the String's specified index. The string indexes start from zero.
Syntax:
    public char charAt(int index)

Parameters :
  • index : Index of the character to be returned.

  • Return Value :
  • This method Returns a char at the specified index.
  •     public class Test{
            public static void main(String args[]){
            String s ="Strings are immutable";
            char result = s.charAt(8);
            System.out.println(result);
            }
        }
    
    
    Output :
    a

    2. int compareTo(Object o)
    Description:
    There are two variants of this method. First method compares this String to another Object and second method compares two strings lexicographically.
    Syntax:
        int compareTo(Object o)
        (or)
        int compareTo(String anotherString)
    
    
    Parameters:
  • o : the Object to be compared.
  • anotherString : the String to be compared.

  • Return Value :
    The value 0 if the argument is a string lexicographically equal to this string; a value less than 0 if the argument is a string lexicographically greater than this string; and a value greater than 0 if the argument is a string lexicographically less than this string.
    Eg:
        public class Test{
            public static void main(String args[]){
            String str1 ="Strings are immutable";
            String str2 ="Strings are immutable";
            String str3 ="Integers are not immutable";
            int result = str1.compareTo( str2 );
            System.out.println(result);
             result = str2.compareTo( str3 );
            System.out.println(result);
            result = str3.compareTo( str1 );
            System.out.println(result);
            }
        }
    
    
    Output :
    0
    10
    -10

    3. int compareTo(String anotherString)
    Description:
    There are two variants of this method. First method compares this String to another Object and second method compares two strings lexicographically.
    Syntax:
        int compareTo(Object o)
        (or)
        int compareTo(String anotherString)
    
    
    Parameters:
  • o : the Object to be compared.
  • anotherString : the String to be compared.

  • Return Value :
  • The value 0 if the argument is a string lexicographically equal to this string; a value less than 0 if the argument is a string lexicographically greater than this string; and a value greater than 0 if the argument is a string lexicographically less than this string.
  • Eg:
        public class Test{
            public static void main(String args[]){
            String str1 ="Strings are immutable";
            String str2 ="Strings are immutable";
            String str3 ="Integers are not immutable";
            int result = str1.compareTo( str2 );
            System.out.println(result);
             result = str2.compareTo( str3 );
            System.out.println(result);
             result = str3.compareTo( str1 );
            System.out.println(result);
            }
        }
        
    
    Output :
    0
    10
    -10

    4. int compareToIgnoreCase(String str)
    Description:
    This method compares two strings lexicographically, ignoring case differences.
    Syntax:
        int compareToIgnoreCase(String str)
    
    
    Parameters:
  • str : the String to be compared.

  • Return Value:
  • This method returns a negative integer, zero, or a positive integer as the specified String is greater than, equal to, or less than this String, ignoring case considerations.
  • Eg:
        public class Test{
            public static void main(String args[]){
            String str1 ="Strings are immutable";
            String str2 ="Strings are immutable";
            String str3 ="Integers are not immutable";
            int result = str1.compareToIgnoreCase( str2 );
            System.out.println(result);
             result = str2.compareToIgnoreCase( str3 );
            System.out.println(result);
             result = str3.compareToIgnoreCase( str1 );
            System.out.println(result);
            }
        }
    
    
    Output :
    0
    10
    -10

    5. String concat(String str)
    Description:
    This method appends one String to the end of another. The method returns a String with the value of the String passed in to the method appended to the end of the String used to invoke this method.
    Syntax:
        public String concat(String s)
    
    
    Parameters:
  • s : the String that is concatenated to the end of this String.

  • Return Value :
  • This methods returns a string that represents the concatenation of this object's characters followed by the string argument's characters.
  • Eg:
        public class Test{
            public static void main(String args[]){
            String s ="Strings are immutable";
             s = s.concat(" all the time");
            System.out.println(s);
            }
        }
    
    
    Output :
    Strings are immutable all the time

    6. boolean equals(Object anObject)
    Description:
    This method compares this string to the specified object. The result is true if and only if the argument is not null and is a String object that represents the same sequence of characters as this object.
    Syntax:
        public boolean equals(Object anObject)
    
    
    Parameters:
  • anObject :the object to compare this String against.

  • Return Value :
  • This method returns true if the String are equal; false otherwise.
  • Eg:
        public class Test{
            public static void main(String args[]){
            String Str1=new String("This is really not immutable!!");
            String Str2=Str1;
            String Str3=new String("This is really not immutable!!");
            boolean retVal;
             retVal =Str1.equals(Str2);
            System.out.println("Returned Value : "+ retVal );
             retVal =Str1.equals(Str3);
            System.out.println("Returned Value : "+ retVal );
            }
        }
    
    
    Output :
    Returned Value : true
    Returned Value : true

    7. boolean equalsIgnoreCase(String anotherString)
    Description:
    This method compares this String to another String, ignoring case considerations. Two strings are considered equal ignoring case if they are of the same length, and corresponding characters in the two strings are equal ignoring case.
    Syntax:
        public boolean equalsIgnoreCase(String anotherString)
    
    
    Parameters:
  • anotherString : the String to compare this String against

  • Return Value:
  • This method returns true if the argument is not null and the Strings are equal, ignoring case; false otherwise.
  • Eg:
        public class Test{
            public static void main(String args[]){
            String Str1=new String("This is really not immutable!!");
            String Str2=Str1;
            String Str3=new String("This is really not immutable!!");
            String Str4=new String("This IS REALLY NOT IMMUTABLE!!");
            boolean retVal;
             retVal =Str1.equals(Str2);
            System.out.println("Returned Value : "+ retVal );
             retVal =Str1.equals(Str3);
            System.out.println("Returned Value : "+ retVal );
             retVal =Str1.equalsIgnoreCase(Str4);
            System.out.println("Returned Value : "+ retVal );
            }
        }
    
    
    Output :
    Returned Value : true
    Returned Value : true
    Returned Value : true

    8. String toLowerCase()
    Description:
    This method has two variants. First variant converts all of the characters in this String to lower case using the rules of the given Locale. This is equivalent to calling toLowerCase(Locale.getDefault()).
    Second variant takes locale as an argument to be used while converting into lower case.
    Syntax:
        public String toLowerCase()
        (or)
        public String toLowerCase(Locale locale)
    
    
    Parameters:
  • NA

  • Return Value:
  • It returns the String, converted to lowercase.
  • Eg:
        import java.io.*;
        public class Test{
            public static void main(String args[]){
            String Str=new String("Welcome to Tesdbacademy");
            System.out.print("Return Value :");
            System.out.println(Str.toLowerCase());
            }
        }
    
    
    Output :
    Return Value :welcome to tesdbacademy

    9. String toString()
    Description:
    This method returns itself a string
    Syntax:
        public String toString()
    
    
    Parameters:
  • NA

  • Return Value:
  • This method returns the string itself.
  • Eg:
        import java.io.*;
        public class Test{
            public static void main(String args[]){
            String Str=new String("Welcome to Tesdbacademy");
            System.out.print("Return Value :");
            System.out.println(Str.toString());
            }
        }
    
    
    Output :
    Return Value :Welcome to Tesdbacademy

    10. String toUpperCase()
    Description:
    This method has two variants. First variant converts all of the characters in this String to upper case using the rules of the given Locale. This is equivalent to calling toUpperCase(Locale.getDefault()).
    Second variant takes locale as an argument to be used while converting into upper case.
    Syntax:
        public String toUpperCase()
        (or)
        public String toUpperCase(Locale locale)
    
    
    Parameters:
  • NA

  • Return Value:
  • It returns the String, converted to uppercase


  • 11.String replace(char oldChar, char newChar)
    Description:
    This method returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.
    Syntax:
        public String replace(char oldChar,char newChar)
    
    
    Parameters:
  • oldChar : the old character.
  • newChar : the new character.

  • Return Value:
  • It returns a string derived from this string by replacing every occurrence of oldChar with newChar.
  • Eg:
        import java.io.*;
        public class Test{
            public static void main(String args[]){
            String Str=new String("Welcome to Tesdbacademy");
            System.out.print("Return Value :");
            System.out.println(Str.replace('o','T'));
            System.out.print("Return Value :");
            System.out.println(Str.replace('a','D'));
            }
        }
    
    
    Output :
    Return Value :WelcTme tT Tesdbacademy
    Return Value :Welcome to TesdbDcDdemy

    12. String replaceAll(String regex, String replacement)
    Description:
    This method replaces each substring of this string that matches the given regular expression with the given replacement.
    Syntax:
        public String replaceAll(String regex,String replacement)
    
    
    Parameters:
  • regex : the regular expression to which this string is to be matched.
  • replacement : the string which would replace found expression.

  • Return Value:
  • This method returns the resulting String
  • Eg:
        import java.io.*;
        public class Test{
            public static void main(String args[]){
            String Str=new String("Welcome to Sdbt");
            System.out.print("Return Value :");
            System.out.println(Str.replaceAll("(.*)Sdbt(.*)","Tesdbacademy"));
            }
        }
    
    Output :
    Return Value :Tesdbacademy

    13. String replaceFirst(String regex, String replacement)
    Description:
    This method replaces the first substring of this string that matches the given regular expression with the given replacement. Syntax:
        public String replaceFirst(String regex,String replacement)
    
    
    Parameters:
  • regex : the regular expression to which this string is to be matched.
  • replacement : the string which would replace found expression.

  • Return Value :
  • This method returns a resulting String
  • Eg:
        import java.io.*;
        public class Test{
            public static void main(String args[]){
            String Str=new String("Welcome to Sdbt");
            System.out.print("Return Value :");
            System.out.println(Str.replaceFirst("(.*)Sdbt(.*)","Sdbt"));
            System.out.print("Return Value :");
            System.out.println(Str.replaceFirst("Sdbt","Tesdbacademy"));
            }
        }
    
    
    Output :
    Return Value :Sdbt
    Return Value :Welcome to Tesdbacademy

    14. String[] split(String regex)
    Description:
    This method has two variants and splits this string around matches of the given regular expression.
    Syntax:
        public String[] split(String regex,int limit)
        (or)
        public String[] split(String regex)
    
    
    Parameters:
  • regex : the delimiting regular expression.
  • limit : the result threshold which means how many strings to be returned.

  • Return Value:
  • It returns the array of strings computed by splitting this string around matches of the given regular expression.
  •     import java.io.*;
        public class Test{
            public static void main(String args[]){
            String Str=new String("Welcome-to-Tesdbacademy");
            System.out.println("Return Value :");
            for(String val1:Str.split("-",2)){
            System.out.println(val1);
            }
            System.out.println("");
            System.out.println("Return Value :");
            for(String val2:Str.split("-",3)){
            System.out.println(val2);
            }
            System.out.println("");
            System.out.println("Return Value :");
            for(String val3:Str.split("-",0)){
            System.out.println(val3);
            }
            System.out.println("");
            System.out.println("Return Value :");
            for(String val4:Str.split("-")){
            System.out.println(val4);
            }
            }
        }
    
    
    Output :
    Return Value :
    Welcome
    to-Tesdbacademy

    Return Value :
    Welcome
    to
    Tesdbacademy

    Return Value :
    Welcome
    to
    Tesdbacademy

    Return Value :
    Welcome
    to
    Tesdbacademy

    (Core Java - Array)