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.
Use the ternary operator. In my opinion, this is one of strategy in defensive programming.
String fileName = (this.filename != null? this.filename : "default value");
String fileName = this.filename != null ? this.filename : "default value";
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.
You can use ternary operator: boolean expression ? value1 : value2
String fileName = fileName == null ? "Default value" : this.filename;
Related
Please find my below code that am checking for null using ternary operator before am setting the value to my bean class attributes.
doc.setCatalog_description(sourceAsMap != null && sourceAsMap.get("catalog_description") != null ? sourceAsMap.get("catalog_description").toString() : null);
Is there anyother way to simplify this code like below., Am just exploring by using org.apache.commons.lang3.ObjectUtils; methods. But am not sure that it is correct or not.
doc.setCatalog_description(ObjectUtils.identityToString(sourceAsMap.get("catalog_description")));
I think you are looking for the method ObjectUtils.toString(Object).
if (sourceAsMap != null) {
final String description = ObjectUtils.toString(sourceAsMap.get("catalog_description"));
doc.setCatalog_description(description);
}
If you are using jdk7 or higher, you can replace the method by java.util.Objects.toString(Object).
if (sourceAsMap != null) {
final String description = Objects.toString(sourceAsMap.get("catalog_description"));
doc.setCatalog_description(description);
}
I don't know if sourceAsMap can be null, but if you are setting several parameters, you should check if it is null just once.
In the interest of readability and clarity I would suggest just extracting this bit of functionality into its own method:
String getDescOrNull(Map<String, Object> sourceAsMap) {
final String key = "catalog_description";
if (sourceAsMap == null || !sourceAsMap.containsKey(key)) {
return null;
}
return sourceAsMap.get(key);
}
then:
doc.setCatalog_description(getDescOrNull(sourceAsMap));
am checking for null using ternary operator before am setting the value to my bean class attributes
So I think you need to set multiple bean attributes from the map.
Best and simple solution will be to check null condition on sourceMap for once and then use ternary operator for setting attributes.
if(sourceAsMap != null){
doc.setCatalog_description(sourceAsMap.get("catalog_description") != null ? sourceAsMap.get("catalog_description").toString() : null);
doc.setAnother_description(sourceAsMap.get("another_description") != null ? sourceAsMap.get("another_description").toString() : null);
}
I have a doubt regarding checking null condition.For eg :
if(some conditon)
value1= value; //value1 is string type
else
value1= "";
Similarly some 4 other string value has similar condition.
What i need is i want to check whether all those 5 string value is null or not,Inorder to do some other specific part.
i did it like this
if(value1 == null)
{
}
but the pgm control didnot entered the loop eventhough value1="".
then i tried
if(value1 ==""){
}
this also didnt worked.
Cant we check null and "" value as same??
can anyone help me??
If you want to check is a String is null, you use
if (s == null)
If you want to check if a string is the empty string, you use
if (s.equals(""))
or
if (s.length() == 0)
or
if (s.isEmpty())
An empty string is an empty string. It's not null. And == must never be used to compare string contents. == tests if two variables refere to the same object instance. Not if they contain the same characters.
To check both "is not null" and "is not empty" on a String, use the static
TextUtils.isEmpty(stringVariableToTest)
It looks like you want to check wether a String is empty or not.
if (string.isEmpty())
You can't check that by doing if (string == "") because you are comparing the String objects. They are never the same, because you have two different objects. To compare strings, use string.equals().
When you are working on String always use .equals.
equals() function is a method of Object class which should be overridden by programmer.
If you want to check the string is null then if (string.isEmpty()) else you can also try if (string.equals(null))
You can use:
we can check if a string is empty in 2 ways:
if(s != null && s.length() == 0)
if(("").equals(s))
prefer below.
String str;
if(str.length() > 0)
{
Log.d("log","str is not empty");
}
else
{
Log.d("log","str is empty");
}
this is my first so I'll try to add as much info as possible so I don't get yelled at. :-)
What I am trying to do is I have 2 variables that grab text from 2 fields and take only the first character from each and assign it to those values.
This is the code that I use to get the strings. They are 2 separate calls as you would.
try { var_ContactSurname = var_ContactSurname.substring(0,1);
}
catch (Exception e){
}
I have the above again with a different variable. Now to this point it does what I want. It grabs the first letter from the fields and assigns it to the variables.
So at this point I have two variables (say with an example charater of D and R).
var_ContactSurname = R
var_ContactLicenceNumber = D
What I want to do is compare those two variables and if they match I want to return a value of TRUE, else FALSE if they don't match.
That value has to be a string as well and be assigned to a new variable called var_ContactValidate.
if (var_ContactLicenceNumber.toLowerCase().equals()var_ContactSurname.toLowerCase()){
var_ContactValidate == "TRUE";
}
else {
var_ContactValidate == "FALSE";
}
No you may notice that there might be some code missing. I am using a rules engine that does a lot of the functions for me. I can use raw Java code to do other things (like this compare)...but that's the compare that I am having a problem with.
Any ideas for that compare would be greatly appreciated.
Thanks.
i would use the String method equalsIgnoreCase()
to assign a value to a field, use a single =, not double (==).
if (var_ContactLicenceNumber.equalsIgnoreCase(var_ContactSurname){
var_ContactValidate = "TRUE";
}
else {
var_ContactValidate = "FALSE";
}
check it
In addition to what already said - a simpler & more elegant version (without the if condition) could be:
var_ContactValidate = Boolean.toString(
var_ContactLicenceNumber.equalsIgnoreCase(var_ContactSurname))
.toUpperCase();
Change your whole piece of code to:
if (var_ContactLicenceNumber.equalsIgnoreCase(var_ContactSurname)){
var_ContactValidate == "TRUE";
}
else {
var_ContactValidate == "FALSE";
}
This combines the case insensitivity that you want, and passes through the second string as an argument of the .equalsIgnoreCase function.
Also, I am not sure what you are trying to do with the line:
var_ContactValidate == "TRUE";
If you want to assign var_ContactValidate to "TRUE" then use a single equals sign '=' as a double equals '==' compares the values instead. You may also considering using a boolean rather than a string in this case.
Here is an implementation that also checks for null values and empty Strings:
public class SurnameAndLicenseValidator {
public static void main(String[] args) {
// FALSE
validateSurnameAndLicense(null, "jb78hq");
validateSurnameAndLicense("Johnson", null);
validateSurnameAndLicense(null, null);
validateSurnameAndLicense("", "jb78hq");
validateSurnameAndLicense("Johnson", "");
validateSurnameAndLicense("", "");
validateSurnameAndLicense("johnson", "xb78hq");
// TRUE
validateSurnameAndLicense("Johnson", "jb78hq");
validateSurnameAndLicense("johnson", "jb78hq");
}
private static String validateSurnameAndLicense(String surname,
String license) {
String result;
if (surname != null
&& surname.length() > 0
&& license != null
&& license.length() > 0
&& Character.toUpperCase(surname.charAt(0)) == Character
.toUpperCase(license.charAt(0))) {
result = "TRUE";
} else {
result = "FALSE";
}
System.out.println(surname + " " + license + " " + result);
return result;
}
}
The main method is used as a unit test here. You might want to extract a real JUnit test from it, if you are into that kind of thing.
I have a function that concatenate a set of strings like this:
StringBuffer sb = new StringBuffer();
sb.append(fct1());
sb.append(fct2());
sb.append(fct3());
Where fct1(), fct2() and fct3() should return a String.
The problem is that I must test the returned values like this :
sb.append(fct1() == null ? "" : fct1());
because I get an exception if the value is null.
The problem is that I have many instructions like this and, above all, I can't modify these functions that return the strings(fct1, fct2 and fct3).
Is there a solution that will "sanitize" automatically my strings?
Thank you.
PS: I created a function that can do it:
public String testNullity(String aString){
aString == null ? "" : aString;
}
so that I can call it like this:
sb.append(testNullity(fct1));
sb.append(testNullity(fct2));
...
Another alternative might be
public class SafeStringBuilder {
private StringBuilder builder = new StringBuilder();
public SafeStringBuilder append(String s) {
if (s != null)
builder.append(s);
return this;
}
}
If you don't mind introducing a dependency, use Guava's Joiner instead of StringBuffer:
Joiner j = Joiner.on("").skipNulls();
StringBuilder sb = new StringBuilder();
j.appendTo(sb, fct1());
j.appendTo(sb, fct2());
j.appendTo(sb, fct3());
String result = sb.toString();
// or even just
Joiner j = Joiner.on("").skipNulls();
String result = j.join(fct1(), fct2(), fct3());
N.B. In general, unless you need StringBuffer's thread safety, you should use StringBuilder instead. Same API, better performance.
There is nothing whatsoever you can do to make this solution simpler except shortening the method name. (There might be a solution using aspect-oriented programming, but on the whole I don't really consider that simpler.)
Unfortunately your solution with testNullity() is the best you can get with Java (consider better naming though). In fact, there is already a method that does that: StringUtils.html#defaultString.
You can create your own wrapper around StringBuffer:
class MyStringBuffer {
StringBuffer _sb = new StringBuffer();
public boolean append(String s) {
_sb.append(s==null ? "" : s);
return s == null;
}
public String toString() { return _sb.toString(); }
}
There is no such function in the standard API, though some methods (which do other things) have it built in.
For example, System.getProperty() has a variant which takes a default value, and if it can't find the given property, it will not return null, but the given default value. You might think of providing your fct* methods with such a "default" argument, if it makes sence.
I think C# has a ?? operator which does about what you want (you would call sb.append(fct2() ?? "")), but I suppose Java will not add any new operators soon.
A better variant of your checking function would be this:
public void appendIfNotNull(StringBuffer sb, String s) {
if(s != null) {
sb.append(s);
}
}
This avoids the superfluous append call with an empty string if there is nothing to append.
So I'm not going for maintainability or elegance here.. looking for a way to cut down on the total tokens in a method just for fun. The method is comprised of a long nested if-else construct and I've found that (I think) the way to do it with the fewest tokens is the ternary operator. Essentially, I translate this:
String method(param) {
if (param == null)
return error0;
else if (param.equals(foo1))
if (condition)
return bar1;
else
return error1;
else if (param.equals(foo2))
if (condition)
return bar2;
else
return error1;
...
else
return error;
}
to this:
String method(param) {
return
param == null ?
error0 :
param.equals(foo1) ?
condition ?
bar1 :
error1 :
param.equals(foo2) ?
condition ?
bar2 :
error2 :
...
error
}
However, there are a couple cases where in addition to returning a value I also want to change a field or call a method; e.g.,
else if (param.equals(foo3))
if (condition) {
field = value;
return bar3;
}
else
return error3;
What would be the cheapest way to do this token-wise? What I'm doing now is ugly but doesn't waste too many tokens (here the field is a String):
param.equals(foo3) && (field = value) instanceOf String ?
condition ?
bar2 :
error2 :
Again, the point is not good coding, I'm just looking for hacks to decrease the token count. If there's a shorter way to write the entire thing I'm open to that as well. Thanks for any suggestions.
Edit: Each word and punctuation mark counts as one token. So, for example, "instanceOf String" is two tokens, but "!= null" is three. The main things I can see for possible improvement are the "&&" and the parentheses. Is there a way to put "field = value" somewhere besides the conditional, and if not is there a construct that makes "field = value" a boolean without the need for parentheses?
(field = value) instanceof String
Assuming that it already satisfies your needs (and it thus includes returning false when value is null), a shorter alternative would then have been
(field = value) != null
Or if you actually overlooked that and want to make null return true as well, then use
(field = value) == value
This can be made much shorter if you use 1-letter variable names.
Further I don't see other ways and I agree with most of us that this all is somewhat nasty ;)
if param is null, return 0
Then make a case/switch/select statement on the parameter. That's clean .