Missing value in Java

后端 未结 11 2742
慢半拍i
慢半拍i 2021-02-20 11:51

What is the statement that can be used in Java to represent a missing value of a variable. for instance I want to write a code:

if (a>=23)
 income = pay_rate;         


        
相关标签:
11条回答
  • 2021-02-20 12:17

    you can set income to null. Later, when you check value of income, if it is null, than treat it as missing

    Integer income = a>=53?pay_rate:null;
    
    0 讨论(0)
  • 2021-02-20 12:17
    Double income = null;
    if (a>=23) {income = pay_rate; }
    

    income would be null by default so if uninitialized

    0 讨论(0)
  • 2021-02-20 12:19

    Use throws:

    if (a>=23)
        income = pay_rate;
    else 
        throw new IllegalArgumentException("income is missing");
    
    0 讨论(0)
  • 2021-02-20 12:22

    Option type in type theory is a way to specify type of a variable that may or may not have a meaningful value. Some languages support Option type like Scala's scala.Option type. For languages that don't support the type you can use wrapper classes or boxed counterparts for primitives.

    public class Income {
      private int value;
      public Income(int value) {
        this.value = value;
      }
      public int getValue() {
         return value;
      }
      public void setValue(int value) {
        this.value = value;
      }
    }
    
    ...
    Income income = null;
    if( a >= 23)
      income = new Income(pay_rate);
    

    or simply

    Integer income = null;
    if( a >= 23)
      income = pay_rate;
    
    0 讨论(0)
  • 2021-02-20 12:24

    You are looking for a value, not for a statement, and that value is null. You cannot assign null to variables of primitive data types, such as int and double, but you can use it with their boxed counterparts -- Integer, Double, et cetera.

    When you do that, you should be careful to check your values for null before accessing them. Otherwise, an innocent-looking if (pay_rate > 100) may throw a null reference exception.

    0 讨论(0)
提交回复
热议问题