nerdexam
Oracle

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.

Working with Selected Classes from the Java API

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)
  • A
    3% (1)
  • B
    5% (2)
  • C
    78% (31)
  • D
    15% (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.

AEqual

This option suggests only the first comparison results in 'Equal', which is incomplete as the second comparison also prints 'Equal'.

BNot equal

This option is incorrect because both `==` and `equals()` comparisons for the given string literals will evaluate to true, leading to 'Equal' being printed.

CEqualCorrect

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.

DNot equal

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

#string literals#string pool#object equality#equals method#reference comparison

Community Discussion

No community discussion yet for this question.

Full 1Z0-803 Practice