0
0
Javaprogramming~15 mins

String comparison in Java - Step-by-Step Execution

Choose your learning style8 modes available
flowchartConcept Flow - String comparison
Start
Create two strings
Compare strings using equals()
If true
Print "Strings are equal"
If false
Print "Strings are not equal"
Compare strings using ==
If true
Print "References are equal"
If false
Print "References are not equal"
End
This flow shows creating two strings, comparing their content with equals(), then comparing their references with ==, and printing results accordingly.
code_blocksExecution Sample
Java
String s1 = new String("hello");
String s2 = new String("hello");
if (s1.equals(s2)) {
    System.out.println("Strings are equal");
} else {
    System.out.println("Strings are not equal");
}
if (s1 == s2) {
    System.out.println("References are equal");
} else {
    System.out.println("References are not equal");
}
This code compares two different String objects with the same content using equals() and ==, printing the results.
data_tableExecution Table
StepActionEvaluationResultOutput
1Create s1s1 = new String("hello")s1 points to new String object with "hello"
2Create s2s2 = new String("hello")s2 points to different new String object with "hello"
3Compare s1.equals(s2)s1.equals(s2) checks content equalitytrueStrings are equal
4Compare s1 == s2s1 == s2 checks reference equalityfalseReferences are not equal
5EndNo more code
💡 Execution stops after printing both comparison results.
search_insightsVariable Tracker
VariableStartAfter Step 1After Step 2Final
s1nullReference to String object "hello"Reference to String object "hello"Reference to String object "hello"
s2nullnullReference to different String object "hello"Reference to different String object "hello"
keyKey Moments - 2 Insights
Why does s1.equals(s2) return true but s1 == s2 return false?
What would happen if we used String s1 = "hello"; and String s2 = "hello"; instead?
psychologyVisual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the result of s1.equals(s2) at step 3?
Afalse
Btrue
Cnull
Dthrows error
photo_cameraConcept Snapshot
String comparison in Java:
- Use equals() to compare text content.
- Use == to compare if two variables point to the same object.
- new String() creates new objects, so == is usually false.
- String literals may share references, making == true.
- Always use equals() to check string equality.
contractFull Transcript
This example shows how Java compares strings. Two strings s1 and s2 are created with the same text but as different objects. Using equals() compares their text and returns true, so the program prints "Strings are equal". Using == compares if they are the same object, which they are not, so it prints "References are not equal". This teaches that equals() checks content, while == checks references. If s2 was assigned s1, then both would point to the same object and both comparisons would be true.