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 :
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")