Java中的关系运算符

在Java中,关系运算符用于比较两个变量的相等性、不相等性、大于、小于等。Java的关系运算符始终返回布尔值 – true或false。

Java中的关系运算符

Java有6个关系运算符。

    1. == 是相等运算符。如果两个操作数引用同一个对象,则返回 true,否则返回 false。

 

    1. != 是不相等运算符。如果两个操作数引用不同的对象,则返回 true,否则返回 false。

 

    1. < 是小于运算符。 > 是大于运算符。

 

    <= 是小于等于运算符。 >= 是大于等于运算符。

支持关系运算符的数据类型

  • The == and != operators can be used with any primitive data types as well as objects.
  • The <, >, <=, and >= can be used with primitive data types that can be represented in numbers. It will work with char, byte, short, int, etc. but not with boolean. These operators are not supported for objects.

关系运算符示例

package com.Olivia.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 {
}

结果:

Relational Operators Java Example
bannerAds