Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

การใช้ Relational และ Logical Operators ใน JShell Java 9

JShell ใน Java 9 ช่วยสำรวจ ค้นพบ และทดลอง Java language features และ libraries อย่างกว้างขวาง

Relational operators (==, !=, <, >, <=, >=) ใช้สำหรับ comparison รับ operands แบบ non-boolean primitive types คืนค่า boolean JShell รองรับ Logical operators สำหรับ expressions ตัว logical operators คาดหวัง boolean operands expressions ที่เกี่ยวข้องใช้สร้าง boolean conditions ใน if, for, while statements logical operators ได้แก่: && (logical AND), || (OR), ! (NOT)

Snippet 1: Relational Operators

jshell> int i = 10;
i ==> 10

jshell> i > 10;
$2 ==> false

jshell> i >= 10;
$3 ==> true

jshell> i < 10;
$4 ==> false

jshell> i <= 10;
$5 ==> true

jshell> i == 10;
$6 ==> true

jshell> i == 20;
$7 ==> false

Snippet 2: Relational Operators กับ Compound Conditions

jshell> int i = 15;
i ==> 15

jshell> i >= 15
$1 ==> true

jshell> i <= 15
$2 ==> true

jshell> i >= 15 && i <= 25
$3 ==> true

jshell> i == 30;
$4 ==> false

jshell> i = 30;
i ==> 30

jshell> i >= 15 && i <= 25;
$5 ==> false

Snippet 3: Logical Operators

jshell> true && true
$1 ==> true

jshell> true && false
$2 ==> false

jshell> false && true
$3 ==> false

jshell> false && false
$4 ==> false

jshell> true || true
$5 ==> true

jshell> true || false
$6 ==> true

jshell> false || true
$7 ==> true

jshell> false || false
$8 ==> false

Truth Tables

A B A && B A || B !A
true true true true false
true false false true false
false true false true true
false false false false true

Operator Precedence (สูงไปต่ำ)

  1. ! (Logical NOT)
  2. && (Logical AND)
  3. || (Logical OR)
  4. ==, !=, <, >, <=, >= (Relational)
  5. =, +=, -=, ... (Assignment)

Short-Circuit Evaluation

  • && - ถ้า operand แรกเป็น false ไม่ evaluate operand ที่สอง
  • || - ถ้า operand แรกเป็น true ไม่ evaluate operand ที่สอง

jshell> false && (1/0 == 0)  // ไม่โยน ArithmeticException
$ ==> false

jshell> true || (1/0 == 0)   // ไม่โยน ArithmeticException
$ ==> true

Relational Operators กับ Objects


jshell> String s1 = "hello";
jshell> String s2 = "hello";
jshell> s1 == s2          // true (string pool)
jshell> s1.equals(s2)     // true (content)

jshell> String s3 = new String("hello");
jshell> s1 == s3          // false (different objects)
jshell> s1.equals(s3)     // true (same content)

Best Practices

  • ใช้ .equals() สำหรับเปรียบเทียบ object content
  • ใช้ Objects.equals(a, b) ป้องกัน null pointer
  • ใช้ short-circuit เพื่อประสิทธิภาพและป้องกัน error
  • ระวัง floating-point comparison - ใช้ epsilon หรือ Math.abs(a-b) < EPSILON