Java: Check whether the first two characters present at the end of a given string
Java String: Exercise-63 with Solution
Write a Java program to check whether the first two characters appear at the end of a given string.
Visual Presentation:
Sample Solution:
Java Code:
import java.util.*;
// Define a class named Main
public class Main {
// Method to check if the first two characters of a string appear at the end of the string
public boolean firstInLast(String str) {
if (str.length() < 2) // If the length of the string is less than 2, return false
return false;
else if (str.substring(0, 2).equals(str.substring(str.length() - 2, str.length())))
// If the substring of the first two characters is equal to the substring of the last two characters, return true
return true;
else
return false; // Otherwise, return false
}
// Main method to execute the program
public static void main(String[] args) {
Main m = new Main(); // Create an instance of the Main class
String str1 = "educated"; // Input string
// Display the given string and whether the first two characters appear at the end of the string using firstInLast method
System.out.println("The given strings is: " + str1);
System.out.println("The first two characters appear in the last: " + m.firstInLast(str1));
}
}
Sample Output:
The given strings is: educated The first two characters appear in the last is: true
Flowchart:
Java Code Editor:
Improve this sample solution and post your code through Disqus
Previous: Write a Java program to read a string and return true if "good" appears starting at index 0 or 1 in the given string.
Next: Write a Java program to read a string and if a substring of length two appears at both its beginning and end,return a string without the substring at the beginning otherwise, return the original string unchanged.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/java-exercises/string/java-string-exercise-63.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics