当前位置:实例文章 » JAVA Web实例» [文章]Java:运算符、位运算 的运算规则与用法详解

Java:运算符、位运算 的运算规则与用法详解

发布人:shili8 发布时间:2025-01-02 08:45 阅读次数:0

**Java 运算符、位运算的运算规则与用法详解**

在 Java 中,运算符是用于执行基本运算的符号。这些运算符包括算术运算符、比较运算符、逻辑运算符、赋值运算符和位运算符等。

**1. 算术运算符**

Java 支持以下几种算术运算符:

* `+`:加法* `-`:减法* `*`:乘法* `/`:除法* `%`:取余数* `++`:自增* `--`:自减示例代码:

javapublic class ArithmeticOperator {
 public static void main(String[] args) {
 int a =10;
 int b =3;

 System.out.println("a + b = " + (a + b)); // a + b =13 System.out.println("a - b = " + (a - b)); // a - b =7 System.out.println("a * b = " + (a * b)); // a * b =30 System.out.println("a / b = " + (a / b)); // a / b =3 System.out.println("a % b = " + (a % b)); // a % b =1 System.out.println("++a = " + (++a)); // ++a =11 System.out.println("--b = " + (--b)); // --b =2 }
}

**2. 比较运算符**

Java 支持以下几种比较运算符:

* `==`:等于* `!=`:不等于* `<`:小于* `>`:大于* `<=`:小于或等于* `>=`:大于或等于示例代码:
javapublic class ComparisonOperator {
 public static void main(String[] args) {
 int a =10;
 int b =3;

 System.out.println("a == b = " + (a == b)); // a == b = false System.out.println("a != b = " + (a != b)); // a != b = true System.out.println("a < b = " + (a < b)); // a < b = false System.out.println("a > b = " + (a > b)); // a > b = true System.out.println("a <= b = " + (a <= b)); // a <= b = false System.out.println("a >= b = " + (a >= b)); // a >= b = true }
}

**3. 逻辑运算符**

Java 支持以下几种逻辑运算符:

* `&&`:与(且)
* `||`:或* `!`:非示例代码:
javapublic class LogicalOperator {
 public static void main(String[] args) {
 boolean a = true;
 boolean b = false;

 System.out.println("a && b = " + (a && b)); // a && b = false System.out.println("a || b = " + (a || b)); // a || b = true System.out.println("!a = " + (!a)); // !a = false }
}

**4. 赋值运算符**

Java 支持以下几种赋值运算符:

* `=`:等于* `+=`:加法赋值* `-=`:减法赋值* `*=`:乘法赋值* `/=`:除法赋值* `%=`:取余数赋值示例代码:
javapublic class AssignmentOperator {
 public static void main(String[] args) {
 int a =10;
 int b =3;

 System.out.println("a += b = " + (a += b)); // a += b =13 System.out.println("b -= a = " + (b -= a)); // b -= a = -10 System.out.println("a *= b = " + (a *= b)); // a *= b =39 System.out.println("a /= b = " + (a /= b)); // a /= b =13 System.out.println("b %= a = " + (b %= a)); // b %= a =1 }
}

**5. 位运算符**

Java 支持以下几种位运算符:

* `&`:与(且)
* `|`:或* `^`:异或* `~`:非* `<<`:左移* `>>`:右移示例代码:
javapublic class BitOperator {
 public static void main(String[] args) {
 int a =10; //1010 int b =3; //00011 System.out.println("a & b = " + (a & b)); // a & b =2 System.out.println("a | b = " + (a | b)); // a | b =10 System.out.println("a ^ b = " + (a ^ b)); // a ^ b =8 System.out.println("~a = " + (~a)); // ~a = -11 System.out.println("a << 1 = " + (a << 1)); // a << 1 =20 System.out.println("b >>1 = " + (b >>1)); // b >>1 =1 }
}

以上是 Java 运算符、位运算的运算规则与用法详解。

相关标签:java开发语言
其他信息

其他资源

Top