Java String.endsWith() 方法

2025 年 7 月 9 日 | 阅读 3 分钟

Java String 类 endsWith() 方法用于检查此字符串是否以给定的后缀结尾。如果此字符串以给定的后缀结尾,则返回 true;否则返回 false。

签名

参数

suffix:字符序列

返回值:true 或 false

内部实现

内部实现表明,endsWith() 方法依赖于 String 类的 startsWith() 方法。

示例-1:String.endsWith() 方法

示例

编译并运行

输出

false
false

示例-2:String.endsWith() 方法

由于 endsWith() 方法返回布尔值,因此该方法也可以在 if 语句中使用。请观察以下程序。

示例

编译并运行

输出

false
String ends with .com

示例-3:String.endsWith() 方法

endsWith() 方法会考虑字符串中字符的区分大小写。以下程序展示了这一点。

示例

编译并运行

输出

false
false
true

示例-4:String.endsWith() 方法

当向 endsWith() 方法的参数中传递空字符串时,该方法始终返回 true。原因是,当我们在字符串后面追加一个空字符串时,字符串本身不会改变。例如,考虑以下语句。

该语句

结果是

因此,我们可以说 Java 中的任何字符串都以空字符串 ("") 结尾。考虑以下程序。

示例

编译并运行

输出

true
false

示例-5:String.endsWith() 方法

如果将 null 作为参数传递给 endsWith() 方法,该方法会抛出 NullPointerException。以下示例展示了这一点。

示例

编译并运行

输出

Exception in thread "main" java.lang.NullPointerException
	at java.base/java.lang.String.endsWith(String.java:1506)
	at Main.main(Main.java:6)

示例-6:String.endsWith() 方法

字符串字面量也可以调用 endsWith() 方法。以下程序展示了这一点。

示例

编译并运行

输出

Inside the if block
Inside the else block
Inside the else block