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

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

ตัวอย่าง: วนลูปไม่รู้จบด้วยตัวแปร non-final

class DemoExample {
    int a = 2, b = 3;
    
    void displayMsg() {
        while (a < b) {
            System.out.println("The first variable is greater than the second");
        }
        System.out.println("This is an unreachable statement"); // ไม่ถึงบรรทัดนี้
    }
}

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

ผลลัพธ์

"The first variable is greater than the second" แสดงผลวนลูปไม่รู้จบ

คำอธิบาย: ตัวแปร a และ b เป็น instance variable ที่ไม่ใช่ final ค่าไม่เปลี่ยนแปลงภายในลูป ทำให้เงื่อนไข a < b เป็นจริงตลอดเวลา ลูป while วนไม่รู้จบ บรรทัดถัดไปจึงกลายเป็น unreachable statement

ข้อสังเกต: คอมไพเลอร์ Java ไม่ จับข้อผิดพลาดนี้ได้ในขณะคอมไพล์ เพราะตัวแปร non-final อาจถูกเปลี่ยนค่าจาก thread อื่นหรือผ่าน reflection ระหว่างรันไทม์ โปรแกรมจะคอมไพล์ผ่าน แต่รันแล้วค้างที่ลูป