String methods – isEmpty() and lastIndexof

In this post, we will discuss about 2 methods which are isEmpty and lastIndexOf.

Let’s understand them with examples.

boolean isEmpty():

Returns true , if length of the string is 0.

public class StringMethodsEx {

	public static void main(String[] args)   {
		
		String val1 = "TESTINGPOOL.COM";  
		System.out.println(val1.isEmpty()); // return false
		System.out.println(("").isEmpty());  // returns true

	}
}

lastIndexOf():

This method finds out the index of last occurrence of a char/sub-string in a particular String.

It has 4 types of implementations.

int lastIndexOf(int ch): It returns the last occurrence of character ch in the particular String.

int lastIndexOf(int ch, int fromIndex): It returns the last occurrence of ch, starting searching backward from the specified index “fromIndex”.

int lastIndexOf(String str): Returns the last occurrence of str in a String.

int lastIndexOf(String str, int fromIndex): Returns the last occurrence of str, starting searching backward from the specified index “fromIndex”.

public class StringMethodsEx {

	public static void main(String[] args)   {
		
		String val1 = "TESTINGPOOL.COM";  

		System.out.println("Last occurence of string COM :"+val1.lastIndexOf("COM")); //last occurrence of string
		System.out.println("Last occurence of char C :"+val1.lastIndexOf("C"));  // last occurrence of char
		System.out.println("Last occurence of char G, index start from 10 :"+val1.lastIndexOf("G", 10)); //lastIndexOf(int ch, int fromIndex)
		System.out.println("Last occurence of string Pool,index starts from 10 :"+val1.lastIndexOf("POOL", 10));  //lastIndexOf(String str, int fromIndex)

	}
}
Output: Last occurence of string COM :12
Last occurence of char C :12
Last occurence of char G, index start from 10 :6
Last occurence of string Pool,index starts from 10 :7
Ask Question
Have any question or suggestion for us?Please feel free to post in Q&A Forum
Avatar photo

Shekhar Sharma

Shekhar Sharma is founder of testingpool.com. This website is his window to the world. He believes that ,"Knowledge increases by sharing but not by saving".

You may also like...