Find Last Occurrence of Character in String Java

Find Last Occurrence of Character in String Java | In this section, we aim to find the last occurrence of the character present in the string. In java to do this, we can use the built-in method available in the java library java.lang package as this package is the default package there is no need to import this. Also see:- Find Second Occurrence of Character in String Java

The lastIndexOf() is the method used to find the last occurrence of the character. This method returns a last index of the specified character. If the specified character is not found then it returns -1. This method is a variation of the indexOf() method which returns the first occurrence of the given character.

Method Syntax:- public String lastIndexOf(char ch)

  • Parameter:- character ch
  • Returns:- index of the ch

Now let us see the example lastIndexOf(ch) method:-

String str = "Java Programming";
System.out.println(str.lastIndexOf('g'));

Output:-

15

The last occurrence of the character ‘g’ is in the index of 15 which is the last occurrence of ‘g’ is present in the 15th position.

Example-2 Find Last Occurrence of Character in String Java:-

String str = "Java Programming";
System.out.println(str.lastIndexOf('a'));

Output:-

10

The last occurrence of the character ‘a’ is in the index of 10 which is the last occurrence of ‘a’ is present in the 10th position.

Program to Find Last Occurrence of Character in String Java

public class Main {
   public static void main(String[] args) {
      String str = "Know Program";
      System.out.println(str.lastIndexOf('r'));
   }
}

Output:-

9

In the word “Know Program” the character ‘r’ is repeated twice and the last occurrence of ‘r’ is in position 9.

If the given character is not found this method returns -1. See the below code for the demonstration. The lastIndexOf() method is case sensitive, observe the code we have specified ‘A’  and there is ‘a’ present in the string hence it is case sensitive the code returns -1. 

public class Main {
   public static void main(String[] args) {
      String str = "Know Program";
      System.out.println(s.lastIndexOf('A'));
   }
}

Output:-

-1

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

Your email address will not be published.