Java Basics:String Methods

 

Java String replace()

The Java String replace() method replaces each matching occurrences of the old character/text in the string with the new character/text

The syntax of the replace() method is either

string.replace(char oldChar, char newChar)

or

string.replace(CharSequence oldText, CharSequence newText)

Here, string is an object of the String class.


replace() Parameters

To replace a single character, the replace() method takes these two parameters:

  • oldChar - the character to be replaced in the string
  • newChar - matching characters are replaced with this character

To replace a substring, the replace() method takes these two parameters:

  • oldText - the substring to be replaced in the string
  • newText - matching substrings are replaced with this string

replace() Return Value

  • The replace() method returns a new string where each occurrence of the matching character/text is replaced with the new character/text.

Example 1: Java String replace() Characters

class Main {
    public static void main(String[] args) {
        String str1 = "abc cba";

        // all occurrences of 'a' is replaced with 'z'
        System.out.println(str1.replace('a', 'z')); // zbc cbz

        // all occurences of 'L' is replaced with 'J'
        System.out.println("Lava".replace('L', 'J')); // Java

        // character not in the string
        System.out.println("Hello".replace('4', 'J')); // Hello
    }
}

Note: If the character to be replaced is not in the string, replace() returns the original string.


Example 2: Java String replace() Substrings

class Main {
    public static void main(String[] args) {
        String str1 = "C++ Programming";

        // all occurrences of "C++" is replaced with "Java"
        System.out.println(str1.replace("C++", "Java")); // Java Programming

        // all occurences of "aa" is replaced with "zz"
        System.out.println("aa bb aa zz".replace("aa", "zz")); // zz bb zz zz

        // substring not in the string
        System.out.println("Java".replace("C++", "C")); // Java
    }
}

Note: If the substring to be replaced is not in the string, replace() returns the original string.


It is important to note that the replace() method replaces substrings starting from the start to the end. For example,

"zzz".replace("zz", "x") // xz

The output of the above code is xz, not zx. It's because the replace() method replaced the first zz with x.

_______________________________________________________________________

Java String replaceAll()

The Java String replaceAll() method replaces each substring that matches the regex of the string with the specified text.The syntax of the replaceAll() method is:

string.replaceAll(String regex, String replacement)

Here, string is an object of the String class.


replaceAll() Parameters

The replaceAll() method takes two parameters.

  • regex - a regex (can be a typical string) that is to be replaced
  • replacement - matching substrings are replaced with this string

replaceAll() Return Value

  • The replaceAll() method returns a new string where each occurrence of the matching substring is replaced with the replacement string.

Example 1: Java String replaceAll()

class Main {
    public static void main(String[] args) {
        String str1 = "aabbaaac";
        String str2 = "Learn223Java55@";

        // regex for sequence of digits
        String regex = "\\d+";

        // all occurrences of "aa" is replaceAll with "zz"
        System.out.println(str1.replaceAll("aa", "zz")); // zzbbzzac

        // replace a digit or sequence of digits with a whitespace
        System.out.println(str2.replaceAll(regex, " ")); // Learn Java @

    }
}

In the above example, "\\d+" is a regular expression that matches one or more digits. To learn more, visit Java regex.


Escaping Characters in replaceAll()

The replaceAll() method can take a regex or a typical string as the first argument. It is because a typical string in itself is a regex.

In regex, there are characters that have special meaning. These metacharacters are:

\ ^ $ . | ? * + {} [] ()

If you need to match substring containing these metacharacters, you can either escape these characters using \ or use the replace() method.

// Program to replace the + character
class Main {
    public static void main(String[] args) {
        String str1 = "+a-+b";
        String str2 = "Learn223Java55@";
        String regex = "\\+";

        // replace "+" with "#" using replaceAll()
        // need to espace "+"
        System.out.println(str1.replaceAll("\\+", "#")); // #a-#b


        // replace "+" with "#" using replace() 
        System.out.println(str1.replace("+", "#")); // #a-#b
    }
}

As you can see, when we use the replace() method, we do not need to escape metacharacters. 

_______________________________________

Java String substring()

The Java String substring() method extracts a substring from the string and returns it.

The syntax of the substring() method is:

string.substring(int startIndex, int endIndex)

Here, string is an object of the String class.


substring() Parameters

The substring() method takes two parameters.

  • startIndex - the begining index
  • endIndex (optional) - the ending index

substring() Return Value

The substring() method returns a substring from the given string.

  • The substring begins with the character at the startIndex and extends to the character at index endIndex - 1.
  • If the endIndex is not passed, the substring begins with the character at the specified index and extends to the end of the string.
Working of Java String substring() method
Working of Java String substring() method

Note: You will get an error if,

  • startIndex/endIndex is negative or greater than string's length
  • startIndex is greater than endIndex

 


Example 1: Java substring() Without End Index

class Main {
    public static void main(String[] args) {
        String str1 = "program";

        // from the first character to the end
        System.out.println(str1.substring(0));  // program

        // from the 4th character to the end
        System.out.println(str1.substring(3));  // gram
    }
}

Example 2: Java substring() With End Index

class Main {
    public static void main(String[] args) {
        String str1 = "program";

        // from 1st to the 7th  character
        System.out.println(str1.substring(0, 7));  // program

        // from 1st to the 5th  character
        System.out.println(str1.substring(0, 5));  // progr

        // from 4th to the 5th character
        System.out.println(str1.substring(3, 5));  // gr
    }
}

_______________________________

Java String equals()

The Java String equals() method returns true if two strings are equal. If not, equals() returns false.

The syntax of the String equals() method is:

string.equals(String str)

Here, string is an object of the String class.


equals() Parameters

The equals() method takes a single parameter.

  • str - the string to be compared

equals() Return Value

  • returns true if the strings are equal
  • returns false if the strings are not equal
  • returns false if the str argument is null

Example: Java String equals()

class Main {
    public static void main(String[] args) {
        String str1 = "Learn Java";
        String str2 = "Learn Java";
        String str3 = "Learn Kolin";
        Boolean result;

        // comparing str1 with str2
        result = str1.equals(str2);
        System.out.println(result); // true

        // comparing str1 with str3
        result = str1.equals(str3);
        System.out.println(result); // false

        // comparing str3 with str1
        result = str3.equals(str1);
        System.out.println(result); // false
    }
}
Here,

  • str1 and str2 are equal. Hence, str1.equals(str2) returns true.
  • str1 and str3 are not equal. Hence, str1.equals(str3) and str3.equals(str1) returns false.

Example 2: Check if Two Strings are Equal

class Main {
    public static void main(String[] args) {
        String str1 = "Learn Python";
        String str2 = "Learn Java";
        
        // if str1 and str2 are equal, the result is true
        if (str1.equals(str2)) {
            System.out.println("str1 and str2 are equal");
        }
        else {
            System.out.println("str1 and str2 are not equal");
        }
    }
}

Output

str1 and str2 are not equal

The equals() method takes the letter case (uppercase and lowercase) into consideration.

Example 3: equals() With Case

class Main {
    public static void main(String[] args) {
        String str1 = "Learn Java";
        String str2 = "learn Java";
        Boolean result;

        // comparing str1 with str2
        result = str1.equals(str2);
        System.out.println(result); // false
    }
}

When "Learn Java" is compared to "learn Java", we get false. It is because equals() takes the letter case into consideration.

Notes:

  • If you need to compare two strings ignoring case differences, use the Java String compareToIgnoreCase() method.
  • The equals() method is available for all Java objects (not only Strings). It is because the equals() method is also defined in the Object class (which is the superclass of all Java classes).

______________________________________

Java String equalsIgnoreCase()

The Java String equalsIgnoreCase() method compares two strings, ignoring case differences. If the strings are equal, equalsIgnoreCase() returns true. If not, it returns false.

The syntax of the string equalsIgnoreCase() method is:

string.equalsIgnoreCase(String str)

Here, string is an object of the String class.


equalsIgnoreCase() Parameters

The string equalsIgnoreCase() method takes a single parameter.

  • str - the string to be compared

equalsToIgnoreCase() Return Value

  • returns true if the strings are equal, ignoring case considerations
  • returns false if the strings are not equal
  • returns false if the str argument is null

Example 1: Java String equalsIgnoreCase()

class Main {
    public static void main(String[] args) {
        String str1 = "Learn Java";
        String str2 = "learn java";
        String str3 = "Learn Kolin";
        Boolean result;

        // comparing str1 with str2
        result = str1.equalsIgnoreCase(str2);
        System.out.println(result); // true

        // comparing str1 with str3
        result = str1.equalsIgnoreCase(str3);
        System.out.println(result); // false

        // comparing str3 with str1
        result = str3.equalsIgnoreCase(str1);
        System.out.println(result); // false
    }
}

Here,

  • str1 and str2 are equal if you do not consider case differences. Hence, str1.equalsIgnoreCase(str2) returns true.
  • str1 and str3 are not equal. Hence, str1.equalsIgnoreCase(str3) and str3.equalsIgnoreCase(str1) returns false.

Example 2: Check if Two Strings are Equal

class Main {
    public static void main(String[] args) {
        String str1 = "LEARN JAVA";
        String str2 = "Learn Java";
        
        // if str1 and str2 are equal (ignoring case differences),
        // the result is true
        if (str1.equalsIgnoreCase(str2)) {
            System.out.println("str1 and str2 are equal");
        }
        else {
            System.out.println("str1 and str2 are not equal");
        }
    }
}

Output

str1 and str2 are equal
  • _____________________________

Comments

Popular posts from this blog

Java OOPS:OOPS Concepts Overview

Java OOPS: OOPS in Selenium