w3resource

Java: Read a string and return true if it ends with a specified string of length 2

Java String: Exercise-58 with Solution

Write a Java program to read a string and return true if it ends with a specified string of length 2.

Visual Presentation:

Java String Exercises: Read a string and return true if it ends with a specified string of length 2.

Sample Solution:

Java Code:

import java.util.*;

// Define a class named Main
public class Main {

    // Method to check if the string ends with 'ng'
    public boolean endsNg(String str) {
        int len = str.length(); // Calculate the length of the input string
        String ng = "ng"; // Define the string 'ng'

        // If the length of the input string is less than 2 characters, return false
        if (len < 2)
            return false;
        // If the last two characters of the input string match 'ng', return true
        else if (ng.equals(str.substring(len - 2, len)))
            return true;
        // Otherwise, return false
        else
            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

        // Define a string to check if it ends with 'ng'
        String str1 = "string";

        // Display the given string and whether it contains 'ng' at the end using the endsNg method
        System.out.println("The given string is: " + str1);
        System.out.println("Does the string contain 'ng' at the end? " + m.endsNg(str1));
    }
}

Sample Output:

The given strings is: string
The string containing ng at last: true

The given strings is: strign
The string containing ng at last: false

Flowchart:

Flowchart: Java String Exercises - Read a string and return true if it ends with a specified string of length 2.

Java Code Editor:

Improve this sample solution and post your code through Disqus

Previous: Write a Java program to create a new string from a given string swapping the last two characters of the given string. The length of the given string must be two or more.
Next: Write a Java program to read a string, if the string begins with "red" or "black" return that color string, otherwise return the empty string.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

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://www.w3resource.com/java-exercises/string/java-string-exercise-58.php