Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can i use conditional operator in java?

static class Hello{
    private String name;

    public String getName() {
      return name;
    }

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

  @GetMapping("/hello")
  @ResponseBody
  public Hello home(@RequestParam(required = false) String name){
    Hello hello = new Hello();

    if(name != null){
      hello.setName(name);
    } else{
      hello.setName("empty");
    }

    // name ? hello.setName(name) : hello.setName("empty");
    // name != null ? hello.setName(name) : hello.setName("empty");

    return hello;
  }

How can I use the commented conditional operation in java?

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

In javascript, the ternary operator does not have to be used as an expression, whereas in Java, it does, meaning it evaluates to a value, and doesn’t just perform an operation. The reason it is not working in the way you are attempting to use it here is because I’m guessing that setName is a void method, and thus doesn’t evaluate to a value.
Your first attempt (// name ? hello.setName(name) : hello.setName("empty");) also wouldn’t work because name is not a boolean value, and Java does not coerce non-boolean values to booleans in the way that javascript does.
You can use the if/else statement you have to achieve what you want, or do as @Robby Cornelissen suggested: hello.setName(name != null ? name : "empty")

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading