Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does java have a default value return like javascript?

Tags:

java

i was wondering if java have a "default value assignation" (i really don't know how to call it) like what you can do in javascript or python.

For example in js you can do this:

var myVar = variable || "default value";

and if variable contains a value, myVar will have the value of variable otherwise myVar will be the string "default value".

Also in python you can do this:

a = "hello" 
b = a or "good bye" 
print b #this will print "hello" 
a = None
b = a or "good bye" 
print b #this will print "good bye"

Can you do this something similar in java? Usually when i have to do this in Java, I do something like this:

String a = b != null ? b : "default value";

But I think what you can do in js or python it's much more readable. Also can you tell me what's the "name" of this ? I know the || symbol it's an or operator, but how it's called when you do this "defaultvalue" thing. Thanks

like image 448
agmezr Avatar asked Sep 19 '25 12:09

agmezr


2 Answers

Since Java is more statically typed than JavaScript or Python, I'm afraid not. Considering this example:

myVar = variable || "default value";

In order for this to be executed at all in Java, variable and "default value" would have to be Booleans, since they're being used in a boolean logic conditional operator. And the result (myVar) would also be a Boolean.

Since the types have to be more statically explicit in Java, the full comparison expression needs to be defined:

myVar = (variable != null) ? variable : "default value";

In this case the boolean expression is the condition being examined, and variable and "default value" need to be of the same type. Which will also be the resulting type of myVar.

In JavaScript (as well as just about any dynamic type system I've used), pretty much anything can be examined as a boolean value. (Anything can be "truthy".) In statically typed languages like Java or C#, however, that's generally not the case.

like image 189
David Avatar answered Sep 21 '25 02:09

David


No, there is no default value for method return types in Java.

In plain old Java, you would write something like:

if (value != null) {
  return value;
else {
  return "default";
}

or you could simplify that to

return value != null ? value : "default";

In Java8, there is the possibility to use Optional<T>. That means, you can hold a value, or not. This would look like this:

Optional<String> optionalVal = Optional.ofNullable(null); // or Optional.of("Foo");
return optionalVal.getOrElse("default");
like image 38
Martin Seeler Avatar answered Sep 21 '25 03:09

Martin Seeler