Java startsWith() vs substring(): Key Differences

startsWith() and substring() are two methods used for manipulating strings in Java.

The startsWith() method is used to check if a string begins with a specified prefix. It returns true if it does, otherwise it returns false. Its usage is as follows:

String str = "Hello World";
boolean result = str.startsWith("Hello");
System.out.println(result); // true

The substring() method is used to extract a portion of a string by specifying the starting and ending positions. The syntax is as follows:

String str = "Hello World";
String subStr = str.substring(6); // 从位置6开始截取到末尾
System.out.println(subStr); // World

String subStr2 = str.substring(0, 5); // 从位置0开始截取到位置5(不包括5)
System.out.println(subStr2); // Hello

Therefore, startsWith() is primarily used to check if a string’s prefix matches, while substring() is mainly used to retrieve a substring of a string. They have distinct differences in functionality.

bannerAds