1Z0-803 · Question #140
Given: class Lang { private String category = "procedura1"; public static void main (String[] args) { Lang obj1 = new Lang(); Lang obj2 = new Lang(); if (obj1.category == obj2.category) { System.out.p
The correct answer is C. Equal. The code compares two String instance fields, category, initialized with the same string literal, using both the == operator and the equals() method.
Question
Given:
class Lang { private String category = "procedura1"; public static void main (String[] args) { Lang obj1 = new Lang(); Lang obj2 = new Lang(); if (obj1.category == obj2.category) { System.out.println("Equal"); } else { System.out.println("Not equal"); } if (obj1.category.equals(obj2.category)) { System.out.println("Equal"); } else { System.out.println("Not equal"); } } } What is the result?
Options
- AEqual
- BNot equal
- CEqual
- DNot equal
How the community answered
(40 responses)- A3% (1)
- B5% (2)
- C78% (31)
- D15% (6)
Why each option
The code compares two `String` instance fields, `category`, initialized with the same string literal, using both the `==` operator and the `equals()` method.
This option suggests only the first comparison results in 'Equal', which is incomplete as the second comparison also prints 'Equal'.
This option is incorrect because both `==` and `equals()` comparisons for the given string literals will evaluate to true, leading to 'Equal' being printed.
Both comparisons in the code will result in 'Equal'. The `==` operator returns true because identical string literals assigned to instance fields are typically interned and refer to the same object in the String pool. The `equals()` method also returns true as it compares the character sequences, which are identical for both string objects.
This option is incorrect because both `==` and `equals()` comparisons correctly identify the strings as equal, resulting in 'Equal' being printed.
Concept tested: String comparison operators and methods
Source: https://docs.oracle.com/javase/tutorial/java/data/strings.html
Topics
Community Discussion
No community discussion yet for this question.