今日已更新 339 条资讯 | 累计 19899 条内容
关于我们

Equality Operators (==, !=) in Java — Part 1

Rajesh Bhola 2026年07月12日 14:15 2 次阅读 来源:Dev.to

Equality operators are among the most frequently used operators in Java. They allow us to compare two values and determine whether they are equal or not. Unlike relational operators ( < , > , <= , >= ), equality operators work with all primitive data types , including boolean , and they can also compare object references . However, many beginners get confused about how == behaves with objects, strings, and null . These concepts are also some of the most frequently asked Java interview questions. Let's understand them with simple explanations and practical examples. What Are Equality Operators? Java provides two equality operators. Operator Description == Equal to != Not equal to Both operators always return a boolean value. Example System . out . println ( 10 == 10 ); System . out . println ( 20 != 10 ); System . out . println ( 5 == 8 ); Output true true false Rule 1: Equality Operators Work with All Primitive Types Unlike relational operators, equality operators can be applied to every primitive type , including boolean . Supported primitive types include: byte short int long float double char boolean Numeric Examples System . out . println ( 10 == 20 ); Output false System . out . println ( 'a' == 'b' ); Output false System . out . println ( 'a' == 97 ); Output true Explanation 'a' = 97 (Unicode) 97 == 97 ↓ true System . out . println ( 'a' == 97.0 ); Output true Even though one operand is a char and the other is a double , Java performs numeric promotion before comparison. Boolean Example System . out . println ( true == false ); Output false System . out . println ( false == false ); Output true Unlike relational operators, equality operators fully support boolean values. Equality Operators vs Relational Operators Many beginners confuse these operators. Expression Result true == false ✅ Valid true != false ✅ Valid true > false ❌ Compile-time error true < false ❌ Compile-time error Remember: Equality operators work with boolean . Relational operators do not. Rul

本文内容来源于互联网,版权归原作者所有
查看原文