Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
Check if Two Integers are Equal or Not in Java
Next article icon

Equality (==) operator in Java with Examples

Last Updated : 24 Jan, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

== operator is a type of Relational Operator in Java used to check for relations of equality. It returns a boolean result after the comparison and is extensively used in looping statements and conditional if-else statements. 

Syntax: 

LHS value == RHS value

But, while comparing these values, three cases arise generally:

Case 1: When both LHS and RHS values are primitive 

This is the most simple among the cases. As primitive data is stored in the stack memory, in this case, the actual value of both sides is fetched from the stack memory and compared. It returns true if they both are equal, else false is returned.

Syntax: 

Actual value == Actual value

Example: 

Java




// Java program for using == operator
 
import java.io.*;
 
public class GFG {
    public static void main(String[] args)
    {
        // Declaring primitive values
        int a = 4;
        int b = 4;
        int c = 5;
 
        // Comparing a and b using == operator
        System.out.println("Are " + a + " and " + b
                           + " equal? " + (a == b));
 
        // Comparing b and c using == operator
        System.out.println("Are " + b + " and " + c
                           + " equal? " + (b == c));
    }
}
 
 
Output
Are 4 and 4 equal? true Are 4 and 5 equal? false

Case 2: When one of the LHS and RHS values is primitive, and the other is a reference 

In this scenario, for the primitive side, the actual value is taken for comparison from the stack memory. But for the reference side, when an array is declared and initialized, the data is stored in the heap memory and the reference pointer in the stack memory. So all that is in the stack memory is the memory address. 

Syntax: 

Actual value == Address value     OR Address value == Actual value

So when the comparison between a primitive value and a reference value is taken, the program doesn’t compile and throws an error:

Compilation Error in java code:- 

prog.java:20: error: incomparable types: int and int[]                            + (a == b));                                 ^ 1 error

This is because the value for the primitive side is easily fetched from the stack memory, but for the reference side, the value cannot be fetched as the value is in heap memory. Hence the error.

Example: 

Java




// Java program for using == operator
 
import java.io.*;
 
public class GFG {
    public static void main(String[] args)
    {
 
        // Declaring primitive value
        int a = 4;
 
        // Declaring reference value
        int[] b = { 1, 2, 3, 4 };
 
        // Comparing a and b using == operator
        System.out.println("Are " + a + " and " + b
                           + " equal? " + (a == b));
    }
}
 
 
prog.java:17: error: bad operand types for binary operator '=='                            + " equal? " + (a == b));                                              ^   first type:  int   second type: int[] 1 error

Case 3: When both of the LHS and RHS values are reference 

In this scenario, for both sides, when an array is declared and initialized, the data is stored in the heap memory and the reference pointer in the stack memory. So both the variables, their address is checked. If both the variables point to the same memory address, this operator returns true. Else it returns false.

Syntax: 

Address value == Address value

Example: 

Java




// Java program for using == operator
 
import java.io.*;
 
public class GFG {
    public static void main(String[] args)
    {
 
        // Declaring reference value
        int[] a = { 1, 2, 3, 4 };
        int[] b = { 1, 2, 3, 4 };
        int[] c = b;
 
        // Comparing a and b using == operator
        // Though they both have the same value
        // the output will be false because
        // they both have a different address in the memory
        System.out.println("Are a and b equal? "
                           + (a == b));
 
        // Comparing b and c using == operator
        // Though they both have the same value
        // the output will be true because
        // they both have same address in the memory
        System.out.println("Are b and c equal? "
                           + (b == c));
    }
}
 
 
Output
Are a and b equal? false Are b and c equal? true


Next Article
Check if Two Integers are Equal or Not in Java

S

ShivendraPorwal
Improve
Article Tags :
  • Java
  • Java Programs
  • Java-Operators
Practice Tags :
  • Java
  • Java-Operators

Similar Reads

  • EnumMap equals() Method in Java with Examples
    The Java.util.EnumMap.equals(obj) in Java is used to compare the passed object with this EnumMap for the equality. It must be kept in mind that the object passed must be a map of the same type as the EnumMap.Syntax: boolean equals(Object obj) Parameter: The method takes one parameter obj of Object t
    2 min read
  • Java String equals() Method
    String equals() method in Java compares the content of two strings. It compares the value's character by character, irrespective of whether two strings are stored in the same memory location. The String equals() method overrides the equals() method of the object class. false if any of the characters
    2 min read
  • Check if Two Integers are Equal or Not in Java
    Checking two integers equal or not in Java is done by various approaches. Arithmetic operatorComparison OperatorsString functionsXOR operatorComplement (~) and bit-wise (&) operator Example Input: FirstNumber = 15 SecondNumber= 15 Output: Numbers are same Input: FirstNumber = 15 SecondNumber= 25
    3 min read
  • Java Program to Compare two Boolean Arrays
    Two arrays are equal if they contain the same elements in the same order. In java, we can compare two Boolean Arrays in 2 ways: By using Java built-in method that is .equals() method.By using the Naive approach. Examples: Input : A = [true , true , false] A1 = [true, true, false] Output: Both the ar
    3 min read
  • Comparing two ArrayList In Java
    Java provides a method for comparing two Array List. The ArrayList.equals() is the method used for comparing two Array List. It compares the Array lists as, both Array lists should have the same size, and all corresponding pairs of elements in the two Array lists are equal. Example: Input : ArrayLis
    2 min read
  • Java Programs - Java Programming Examples
    In this article, we will learn and prepare for Interviews using Java Programming Examples. From basic Java programs like the Fibonacci series, Prime numbers, Factorial numbers, and Palindrome numbers to advanced Java programs. Java is one of the most popular programming languages today because of it
    8 min read
  • equals() and deepEquals() Method to Compare two Arrays in Java
    Arrays. equals() method does not compare recursively if an array contains another array on other hand Arrays. deepEquals() method compare recursively if an array contains another array. Arrays.equals(Object[], Object[]) Syntax : public static boolean equals(int[] a, int[] a2) Parameters : a - one ar
    3 min read
  • Java Program to Compare Two Objects
    An object is an instance of a class that has its state and behavior. In java, being object-oriented, it is always dynamically created and automatically destroyed by the garbage collector as the scope of the object is over. Illustration: An example to illustrate an object of a class: Furniture chair=
    7 min read
  • Java Program to Check if a Given Integer is Positive or Negative
    Here, the task is to check whether the given integer number is positive or negative. Below are some basic properties of a number. If the Integer is greater than zero then it is a positive integer.If the number is less than zero then it is a negative integer.If the number is equal to zero then it is
    4 min read
  • & Operator in Java with Examples
    The & operator in Java has two definite functions: As a Relational Operator: & is used as a relational operator to check a conditional statement just like && operator. Both even give the same result, i.e. true if all conditions are true, false if any one condition is false. However,
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences