exampracticeonline.com
String endsWith()

Java String endsWith()

As method name suggested endsWith() is used to check if this string ends with given suffix string. It returns boolean true or false. If this string ends with given suffix returns true else returns false.

Internal method implementation

You can see this internal implementation in String.class provided in java.lang package.

/**
     * Tests if this string ends with the specified suffix.
     *
     * @param   suffix   the suffix.
     * @return  {@code true} if the character sequence represented by the
     *          argument is a suffix of the character sequence represented by
     *          this object; {@code false} otherwise. Note that the
     *          result will be {@code true} if the argument is the
     *          empty string or is equal to this {@code String} object
     *          as determined by the {@link #equals(Object)} method.
     */
    public boolean endsWith(String suffix) {
        return startsWith(suffix, value.length - suffix.value.length);
    }

Method Syntax

public boolean endsWith(String suffix)  

Method Parameter

suffix : Sequence of character or a sub String

Method Returns

Java String endsWith() method returns boolean value true or false.

1. Example - Java String endsWith() method

package com.examples;

public class StringEndsWithExample {

	public static void main(String args[]) {
		
		String str = "hello java";
		System.out.println("str ends with java : "+str.endsWith("java"));
		System.out.println("str ends with a : "+str.endsWith("a"));
		System.out.println("str ends with hello : "+str.endsWith("hello"));
		System.out.println("str ends with h : "+str.endsWith("h"));
		
	}
}

Output:

str ends with java : true
str ends with a : true
str ends with hello : false
str ends with h : false

2. Example - Java String endsWith() method

package com.examples;

public class StringEndsWithExample {

        public static void main(String args[]) {

                String str = "Java learning";
                if(str.endsWith("learning")) {
                        System.out.println("Yes str ends with learning");
                } else {
                        System.out.println("No str ends with learning");
                }

        }
}

Output: 

Yes str ends with learning

3. Example - Java String endsWith() method

NOTEString endsWith() method is case senstive.

package com.examples;

public class StringEndsWithExample {

        public static void main(String args[]) {
                
                String str = "Java learning";
                if(str.endsWith("Learning")) {
                        System.out.println("Yes str ends with Learning");
                } else {
                        System.out.println("No str ends with Learning");
                }
                
        }
}

Output:

No str ends with Learning