Reputation: 235
I'm not really sure what this is called so it's hard to look it up and it is best if I show you what I'm trying to do.
I want to create a condional variable of sorts
String fileName = (if (this.filename != null) { return this.filename; }
else { return "default value"; });
This should be pretty clear on what I'm trying to do. I want to use some sort of condition to set this variable based on another variables input, in this case whether or not it equals null or not.
Upvotes: 0
Views: 429
Reputation: 12809
Use the ternary operator. In my opinion, this is one of strategy in defensive programming.
String fileName = (this.filename != null? this.filename : "default value");
Upvotes: 7
Reputation: 15729
Or, more verbose but (perhaps) easier to understand
String aFilename;
if (this.filename != null)
aFilename = this.filename;
else
aFilename = "Default Value";
return aFilename;
I prefer Careal's code but YMMV. Some find the ? operator complicated (especially in messy cases)
Also, when stepping though with the debugger this code will be way easier to see what happened.
Upvotes: 1
Reputation: 18569
You can use ternary operator: boolean expression ? value1 : value2
String fileName = fileName == null ? "Default value" : this.filename;
Upvotes: 0
Reputation: 202
String fileName = this.filename != null ? this.filename : "default value";
Upvotes: 5