Java String startsWith() Method

Java String startsWith

Well, previously, we had seen some methods to see whether our string ends with some string. Well, this method finds whether or not our string starts with some string. Let’s have an example to understand the same –

public class StringMethods {
public static void main(String[] args) {
String str1 = “Welcome to GyaniPandit”;
System.out.println(str1.startsWith(“Welcome”));
}
}

Well, if you execute the above program, the output is true. But remember that this thing is case-sensitive. If you try changing the argument to ”welcome”, ”WELCOME” or ”WelCome” or something like that, you would straightaway get an output as false. So, either you can do is that before you search for something, convert your input string into lowercase, and then always search with lowercase. This is to be done because of the fact that users may have the freedom to input in any way, like ”WElcome”, or ”WELCome”, or anything. So we first better convert anything that the user inputs either to uppercase or lowercase and then perform the search for startsWith, so that our program runs better.