Nhiều sự thật thú vị về toán tử tăng/giảm trong Java. Thảo luận một vài với ví dụ:
- Toán tử tăng/giảm không dùng được với biến
final. Do biếnfinalkhông thể thay đổi.
Ví dụ
public class Demo{
public static void main(String[] args){
final int my_val = 34;
int my_val_2 = ++my_val;
System.out.println("Giá trị là: ");
System.out.println(my_val_2);
}
}
Kết quả
/Demo.java:6: error: cannot assign a value to final variable my_val int my_val_2 = ++my_val; ^ 1 error
- Lồng (nesting)
++và--không thể hoặc không cho phép.
Ví dụ
public class Demo{
public static void main(String[] args){
int my_val_1 = 99;
int my_val_2 = ++(++my_val_1);
System.out.println("Giá trị là: ");
System.out.println(my_val_2);
}
}
Kết quả
/Demo.java:6: error: unexpected type int my_val_2 = ++(++my_val_1); ^ required: variable found: value 1 error