Important methods of String

Here we will see the important methods which frequently used in real time development.

  • public boolean equals(Object o)

This is a very frequently used method, which is overridden in String class. It checks for content, if the content is equal it returns true else it returns false. Let’s see a simple example –

public class StringExample1 {
	public static void main(String[] args) {

		String s1 = new String("ram");
		String s2 = new String("ram");

		System.out.println(s1.equals(s2));

	}
}

Output is – true

We have a separate post related to equals() method, please visit this post for more details.

  • public boolean equalsIgnoreCase(String anotherString)

equalsIgnoreCase() will return true if all character in given String objects is the same, even an object contains the capital letters.

public class StringExample1 {
	public static void main(String[] args) {

		String s1 = "ram";
		String s2 = "RAM";

		System.out.println(s1.equalsIgnoreCase(s2));

	}
}

Output is – true

 

Let’s see another example which demonstrate difference between equals() and equalsIgnoreCase() –


public class StringExample1 {
	public static void main(String[] args) {

		String s1 = "ram";
		String s2 = "RAM";

		System.out.println("campare of String using equals() -- "+s1.equals(s2));
		System.out.println("campare of String using equalsIgnoreCase() -- "+s1.equalsIgnoreCase(s2));

	}
}

Out put is –

campare of String using equals() — false
campare of String using equalsIgnoreCase() — true

 

  • public String[] split(String regex)

split() method returns String array. We can split any string on the basis of some regex value like space, comma or hyphen(or other regex value).


splitting a string on basis of space –

public class StringExample1 {
	public static void main(String[] args) {

		String s1 = "my name is ram";

		String[] strSplitedWithSpace = s1.split(" ");
		for (String s : strSplitedWithSpace) {
			System.out.println(s);
		}
		System.out.println("--------------------------");
		String s2 = "my-name-is-ram";
		String[] strSplitedWithHyphen = s2.split("-");
		for (String str : strSplitedWithHyphen) {
			System.out.println(str);
		}
		System.out.println("---------------------------");

		String s3 = "my,name,is,ram";
		String[] strSplitedWithComma = s3.split(",");
		for (String str : strSplitedWithComma) {
			System.out.println(str);
		}
	}
}

Output is –

my
name
is
ram
————————–
my
name
is
ram
—————————
my
name
is
ram