Latest :

Java Program Compare Strings by Characters | Java Programs

Compare Strings by Count of Character through Java Program – In this particular article, we will be talking about the code to compare whether two user-defined strings are equal in length using Java language.

Suitable examples and sample output will be provided accordingly.

  • The problem here is to check whether two given strings are equal in length.
  • The input here is two user-defined strings of either the same or different lengths.
  • The output here is a boolean value that helps determine whether the input strings are equal in length.
 

Output – 1 :

  • Solution:
  1. In the first line, a new Scanner class object is initialized and a reference variable sc is set to represent the object. This class is used to take user input in Java.
  2. Scanner class is part of the java.util package and hence the import statement, in the beginning, is stated to import the functionality of the specified class.
  3. The next line prints a statement to the console instructing the user to enter a string.
  4. The .nextLine() method is called by the Scanner object sc. This method reads a line of user input of a string value and stores it to the variable s1.
  5. This same process is repeated again to store the second string in variable s2.
  6. Within, the print statement of the last line, the method compare is called and s1 and s2 are passed in as arguments.

 

 

  1. In this method, the conditional statement checks whether the two input parameters s1 and s2 are equal in length using the .length() method which helps determine the length of a string.
  2. The method returns the boolean true if the condition is satisfied i.e. the strings are equal and returns the boolean false otherwise.
  3. This returned boolean is printed out by the print statement in the main method, thus getting the result to compare two strings character by character.

 

 

  • Here, the input strings are hello and cello. The length of each of these strings is 5
  • Thus, the conditional statement in the compare method is satisfied and the boolean true is printed out that compares Strings by Count of Characters.

 

Output – 2:

 

 

  • Here, the input strings are ddd\ and gg. The length of the first string is 4 and the second one is 2 and thus the conditional statement in the compare method is not satisfied and the boolean false is printed out.
x

Check Also

Java Program To Display Transpose Matrix | 3 Ways

Java Program to display/print the transpose of a given matrix.  The following program to print ...