How to string width with specific char in java Program

class StringEndwith {
  public static void main(String args[]) {
    String s1 = "java by TechSarvam";
    System.out.println(s1.endsWith("r")); //true
    System.out.println(s1.endsWith("Sarvam")); //true System.out.println(s1.endsWith("Sarvam"));//false
  }
}

Step-by-Step Breakdown:

1.  Class and Main Method Declaration:

class StringEndwith 

{

            public static void main(String args[]) 

{

  • The program declares a class StringEndwith.
  • The main method is the entry point where the execution of the program begins.

2. Declaration of the String

String s1 = “java by TechSarvam”;

The variable s1 is declared and initialized with the string “java by TechSarvam”.

3. Use of endsWith() Method:

The endsWith() method is called three times with varying suffixes and the results are printed using System.out.println()

First Call

System.out.println(s1.endsWith(“r”));

  • endsWith(“r”): It will check whether the string s1 is ending with the character  “r”.
  • The string s1 = “java by TechSarvam” and the last character is  “r”.
  • As it is ending with  “r”, the method returns true

Output:  true

Second Call:

System.out.println(s1.endsWith(“Sarvam”));

  • endsWith(“Sarvam”): It will check whether the string s1 is ending with the suffix  “Sarvam”.
  • The string s1 = “java by TechSarvam”, and it is actually ending with  “Sarvam”.
  • Since it ends with  “Sarvam”, the method returns true

Output: true

Third Call:

System.out.println(s1.endsWith(“Sarvam”));

  • The endsWith(“Sarvam”) checks if the string s1 ends with the suffix \”Sarvam\”.
  • The string s1 = “java by TechSarvam” ends with “Sarvam”, but the suffix being checked is “Sarvam” (note the lowercase “l”).
  • Java’s endsWith() method is case-sensitive, so it does not match.
  • Since the case does not match, the method returns false

Output: false

4. Program Output:

true

true

false

Final Output:

true

true

false

Summary:

  • First endsWith(“r”): Returns true because the string ends with the character  “r”.
  • Second endsWith(“Sarvam”): Returns true because the string ends with the substring  “Sarvam”.
  • Third endsWith(“Sarvam”): It will return false as it checks case sensitive, and the string actually ends with  “Sarvam”, not  “Sarvam”.

Important Points:

  • The endsWith() method determines if a string ends with a specified suffix.
  • This method is case sensitive so “Sarvam” is not equal to “Sarvam”.
  • The value returned from this method is of boolean; if the input string ends with the suffix then true else false.

Leave a Comment

Your email address will not be published. Required fields are marked *