Pavan
Pavan

Reputation: 77

How to set a default Value in case of Empty when using Optional

I have got an Emp Object , if the name is empty or null , I want to have a default value

I have tried setting default value to Mark , but this is not working ,seeing blank only

This is my program

import java.util.Optional;

public class Test {

    public static void main(String[] args) {

        String str = "";

        Emp emp = new Emp();
        emp.setName(str);

        String value = Optional.ofNullable(emp).map(e -> e.getName()).orElse("Mark");

        System.out.println(value);

    }

}

class Emp {

    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}

Upvotes: 0

Views: 1489

Answers (1)

Amin Alian
Amin Alian

Reputation: 11

When you create you Emp, you set the name in the next row with emp.setName(str).

Here you have already set the string to a blank string by using String str = "";

Therefore the name of the Emp is no longer null, it is "" (a blank String).

By not setting the name it will remain null and will thereby be named "Mark" when the code is run.

Upvotes: 1

Related Questions