1Z0-811 Primitives, Strings and Operators Practice Question
A junior developer wrote the following code to compare two strings entered by a user: if (username == "admin") { grantAccess(); } else { denyAccess(); }. The code always denies access even when the user enters 'admin'. What is the most likely cause, and how should the code be fixed?
⚠ Common exam trap
Oracle Java Foundations exam often tests the distinction between reference equality (==) and value equality (.equals()) for String objects, and the trap here is that candidates may think the issue is case sensitivity or whitespace, when the fundamental problem is the use of the wrong comparison operator.
Answer choices
Why each option matters
Answer the question above first, then reveal the full breakdown to understand why each option is right or wrong.
Correct answer & explanation
✓
The strings are compared using == which checks reference equality. Use username.equals("admin") instead.
In Java, the == operator compares object references, not the actual content of strings. When comparing two String objects for logical equality, the .equals() method must be used. The code if (username == "admin") checks whether username and the string literal "admin" refer to the same memory location, which is false when username is obtained from user input (e.g., via Scanner or console), even if the characters are identical.
Answer analysis
Option-by-option breakdown
For each option: why learners choose it and why it is or isn't the right answer here.
- ✗
The input string has leading or trailing spaces. Use username.trim().equals("admin") instead.
Why it's wrong here
Possible but less likely; not the most likely cause.
- ✗
The variable username is null, causing a NullPointerException that is caught and denied access. Add a null check.
Why it's wrong here
NullPointerException would crash, not just deny.
- ✗
The strings are compared using == which is case-sensitive. Use username.equalsIgnoreCase("admin") instead.
Why it's wrong here
Case-sensitivity is not the issue.
- ✓
The strings are compared using == which checks reference equality. Use username.equals("admin") instead.
Why this is correct
equals compares content.
Go deeper
Related to this question
About these practice questions
This 1Z0-811 question is part of Courseiva's 481-question bank — original exam-style content with full explanations and wrong-answer analysis, never real exam questions or exam dumps. Learn why practice questions differ from exam dumps →
JA
Written by Johnson Ajibi, MSc IT Security
Senior Network & Security Engineer · founder of Courseiva
This 1Z0-811 practice question is part of Courseiva's free Oracle certification practice question bank. Courseiva provides original exam-style practice questions with explanations, topic-based practice, mock exams, readiness tracking, and study analytics to help learners prepare for the 1Z0-811 exam.