1.

In Java, how can two strings be compared?

Answer»

In Java, there are several ways for comparing two strings. The following are a few of them:

  • String Equals Method: In this method, the strings are compared based on the values within them. If the values of the two strings are the same, it returns true; otherwise, it returns false. This method is case-sensitive.

Syntax:

str1.equals(STR2);

For example: 

Input 1= ScalerInput 2= InterviewBitOutput= falseInput 1= ScalerInput 2= ScalerOutput= trueInput 1= ScalerInput 2= scalerOutput= false
  • String Equals Ignore Case: By USING this method, the two strings are compared without taking into account the case (upper or lower). It returns true if the two values are the same and not null.

    Syntax:
str1.equalsIgnoreCase(str2);

For Example:

Input 1= ScalerInput 2= InterviewBitOutput= falseInput 1= ScalerInput 2= ScalerOutput= trueInput 1= ScalerInput 2= scalerOutput= true
  • Object Equals Method: The method returns true if its arguments are equal, otherwise, it returns false. Accordingly, if both arguments are null, the RESULT is true, and if just one argument is null, the result is false.

Syntax: 

Object.equals(str1, str2)

For example: 

Input 1= ScalerInput 2= InterviewBitOutput= falseInput 1= ScalerInput 2= ScalerOutput= trueInput 1= ScalerInput 2= nullOutput= falseInput 1= nullInput 2= nullOutput= True
  • String Compare To Method: This method compares input strings with each other. Upon comparison, the following VALUE is RETURNED:
  1. If (str1>str2), a positive value is returned.
  2. If (str1==str2), 0 is returned.
  3. If (str1<str2), a negative value is returned.

Syntax:

str1.compareTo(str2)

Example: 

Input 1= InterviewBitInput 2= ScalerOutput= -10Input 1= ScalerInput 2= ScalerOutput= 0Input 1= ScalerInput 2= InterviewBitOutput= 10


Discussion

No Comment Found