Java String Endswith Method
Well, the name of this method says it all. We are checking whether the given string ends with some specified string. This is like we are saying – hey… take the string, and tell me whether that string ends with the given string? We get the answer as yes or no (true or false).
If you feel confused, let’s take an example here. Consider that we have a string str1 = ”Welcome to GyaniPandit”.
We try this instruction – str1.endsWith(”GyaniPandit”);
Well, we are just asking here that – hey… does the string referred by str1 end with the string GyaniPandit? So, what do you think should be the answer? Well, I think you made the guess, and it’s true because it does end with GyaniPandit!
So, now, with this, lets try implementing a program, to see the method working practically –
public class StringMethods {
public static void main(String[] args) {
String str1 = “Welcome to GyaniPandit”;
String str2 = “GyaniPandit”;
System.out.println(str1.endsWith(str2));
}
}
So, executing the above program, we can be comfortable seeing that the output is true since we know that the string literal pointed by str1 ends with GyaniPandit. You can also try putting Pandit, or dit, or it, or even t, or anything that’s in the end.
You will find that the output now comes out to be true. You can try running the program for the changed string inputs. Remember that this thing is case-sensitive.
So, if you try searching for something does the string end with ‘T’? well, it does end with ‘t’ but a lowercase one, and we are searching for an uppercase one, which is why it will give the output as false. Have a look at the program –
public class StringMethods {
public static void main(String[] args) {
String str1 = “Welcome to GyaniPandit”;
String str2 = “T”;
System.out.println(str1.endsWith(str2));
}
}
So, what would be the solution to it? Well, just imagine that the ‘T’ here is the user input. Now the user can input in any way, right? In caps or small or in capitalize or in some random way, but it would be hectic for us to create cases or conditions for every possible thing.
One thing is that we can take the user input, and just convert it to something more convenient, like let’s say, the user enters the input in all uppercase, we can convert that user input into lowercase, and then do the searches and all so that the program does not misbehave just because of the user inputs. If not now, you will understand it later on.