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

Unreachable Statement ด้วยตัวแปร final ใน Java

Unreachable Statement คืออะไร?

คำสั่งที่ไม่เคยถูกดำเนินการระหว่างรันโปรแกรม สาเหตุหลักมี 3 อย่าง:

  • มีคำสั่ง return ก่อนบรรทัดนั้น
  • มีลูปไม่รู้จบ (infinite loop)
  • การทำงานถูกบังคับหยุดก่อนถึงบรรทัดนั้น

ตัวอย่าง: คอมไพเลอร์จับได้ด้วยตัวแปร final

class DemoExample {
    final int a = 56, b = 99;
    
    void funcSample() {
        while (a < b) {
            System.out.println("The first value is less than the second.");
        }
        System.out.println("This is an unreachable statement"); // compile error
    }
}

public class Demo {
    public static void main(String[] args) {
        DemoExample myInstance = new DemoExample();
        myInstance.funcSample();
    }
}

ผลลัพธ์ (Compile Error)

/Demo.java:11: error: unreachable statement
    System.out.println("This is an unreachable statement");
    ^
1 error

คำอธิบาย: ตัวแปร a และ b เป็น final (ค่าคงที่) คอมไพเลอร์รู้แน่ชัดว่า a < b เป็นจริงตลอดเวลา และไม่มีทางเปลี่ยนแปลง ลูป while จึงเป็น infinite loop แน่นอน คอมไพเลอร์จึงรายงาน error: unreachable statement ทันที

ความแตกต่างจาก non-final: ตัวแปร final ให้คอมไพเลอร์ทำ static analysis ได้แม่นยำ จับ unreachable code ได้ในขณะคอมไพล์ ในขณะที่ non-final จับไม่ได้ (ดูบทความก่อนหน้า)