Relational Operators in Java are used to comparing two variables for equality, non-equality, greater than, less than, etc. Java relational operator always returns a boolean value - true or false.
Java has 6 relational operators.
package com.journaldev.java;
public class RelationalOperators {
public static void main(String[] args) {
int a = 10;
int b = 20;
System.out.println(a == b);
System.out.println(a != b);
System.out.println(a > b);
System.out.println(a < b);
System.out.println(a >= b);
System.out.println(a <= b);
// objects support == and != operators
System.out.println(new Data1() == new Data1());
System.out.println(new Data1() != new Data1());
}
}
class Data1 {
}
Output:
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
Java and Python Developer for 20+ years, Open Source Enthusiast, Founder of https://www.askpython.com/, https://www.linuxfordevices.com/, and JournalDev.com (acquired by DigitalOcean). Passionate about writing technical articles and sharing knowledge with others. Love Java, Python, Unix and related technologies. Follow my X @PankajWebDev
Thank you for describing different operators in java, I’m adam from Sweden. I’m 47 years old and want to program in java. Some times the operator == does not work and I have to use .equals() ex in a nestled for-loop. https://pastebin.com/TXbWufVu
- Carl-Adam Bergund
equals is an Override method of base class Object, then equals is better for object comparison and not for primitive types
- Reynier Ramos Portieles
Hello Thanks for sharing the post. I am not able to understand how == works for primitive data type but not for objects. In the above post it was mentioned that it returns true if both the operandi refers to the same object. I understood that it dosen’t work for objects as when we use new keyword new objects are created. So it returns false. But can you please explain how does it work for primitive data types? Thanks
- Mannam
Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.
Full documentation for every DigitalOcean product.
The Wave has everything you need to know about building a business, from raising funding to marketing your product.
Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.
New accounts only. By submitting your email you agree to our Privacy Policy
Scale up as you grow — whether you're running one virtual machine or ten thousand.
Sign up and get $200 in credit for your first 60 days with DigitalOcean.*
*This promotional offer applies to new accounts only.