How to check if a variable holds any value in if condition?

Viewed 89

I was working on a problem, and I wanted to know how we can check if a variable holds any value inside the if condition in Java. Like in JavaScript, if we simply do like

Javascript code

let amount;
let discount;
if(amount){
    discount=10;
}

I can simply check here if amount holds a value or not in JavaScript.

This is the code I need help in:

case: if I want to check if a variable holds a value in it?

class Shop {
    private double amount;
    private int discount;

    public int getDiscount(){
        if(amount){  // err: cannot convert double to bool
           this.discount=10;
        }
        else{
          this.discount=0;
        }
        return this.discount;
    }

    public static void main(String[] args) {
       Shop s1= new Shop s2;
       System.out.println("Discount="+ s1.getDiscount());
    }
2 Answers

Java does not have undefined and null as Javascript has. Java has only null value.

In Java primitive variables like double when used as fields in some class, they are initialized to their default value (double uses the default 0.0) if you don't provide any initial value.

But if you use the relative wrapped object like Double as class field it will not be initialized in default value (0.0) but null.

So you can use the wrapped object Double and check if it is null, since this will happen when no value is assigned to that field.

   class Shop {
    private Double amount;
    private int discount;
    
    public int getDiscount(){
        if(amount == null){ 
           this.discount=10;
        } 

Java is a strongly typed programming language because every variable must be declared with a data type. A variable cannot start off life without knowing the range of values it can hold, and once it is declared, the data type of the variable cannot change. From here

This does not apply to javascript, that is why it can have the thruthy/falsey checks. In OOP languages you usually make null checks for objects (or look up NullObjectPattern) or in your case a default value check. Check if amount is the default double value.

Related