Algorithm
-
Input:
- Take two strings as input, let's call them
str1
andstr2
.
- Take two strings as input, let's call them
-
Length Check:
- Compare the lengths of
str1
andstr2
. If the lengths are different, the strings are not equal.
- Compare the lengths of
-
Character Comparison:
- Iterate through each character of both strings using a loop.
- Compare the characters at the corresponding positions in the strings.
-
Equality Check:
- If at any point, you find characters that are not equal, the strings are not equal. Return false.
- If the loop completes without finding any unequal characters, the strings are equal. Return true.
-
Case Sensitivity:
- Decide whether the comparison is case-sensitive or case-insensitive based on your requirements.
- For case-sensitive comparison, use
charAt()
for individual character comparison. - For case-insensitive comparison, convert both strings (or characters) to lowercase or uppercase using
toLowerCase()
ortoUpperCase()
.
- For case-sensitive comparison, use
- Decide whether the comparison is case-sensitive or case-insensitive based on your requirements.
Code Examples
#1 Code Example- Java Programing Compare two strings
Code -
Java Programming
public class CompareStrings {
public static void main(String[] args) {
String style = "Bold";
String style2 = "Bold";
if(style == style2)
System.out.println("Equal");
else
System.out.println("Not Equal");
}
}
Copy The Code &
Try With Live Editor
Output
Equal
#2 Code Example- Java Programing Compare two strings using equals()
Code -
Java Programming
public class CompareStrings {
public static void main(String[] args) {
String style = new String("Bold");
String style2 = new String("Bold");
if(style.equals(style2))
System.out.println("Equal");
else
System.out.println("Not Equal");
}
}
Copy The Code &
Try With Live Editor
Output
Equal
#3 Code Example- Compare two string objects using == (Doesn't work)
Code -
Java Programming
public class CompareStrings {
public static void main(String[] args) {
String style = new String("Bold");
String style2 = new String("Bold");
if(style == style2)
System.out.println("Equal");
else
System.out.println("Not Equal");
}
}
Copy The Code &
Try With Live Editor
Output
Not Equal
#4 Code Example- Different ways to compare two strings
Code -
Java Programming
public class CompareStrings {
public static void main(String[] args) {
String style = new String("Bold");
String style2 = new String("Bold");
boolean result = style.equals("Bold"); // true
System.out.println(result);
result = style2 == "Bold"; // false
System.out.println(result);
result = style == style2; // false
System.out.println(result);
result = "Bold" == "Bold"; // true
System.out.println(result);
}
}
Copy The Code &
Try With Live Editor
Output
true
false
false
true
false
false
true
Demonstration
Java Programing Example to Compare Strings-DevsEnv