三元运算符判断字符串是否为空

有一个变量String userId;

判断是否为null,如果为null,就赋值为空串;否则就不变;

用if条件写是

if (null == userId) {
    userId = "";
}


想用三元运算符写,常见错误写法

userId == null ? "" : userId;

这样是错误的,会报Type mismatch: cannot convert from null to boolean


正确写法:

userId = (userId == null) ? "" : userId;


三元运算符与if语句相比的优点是,美化代码,让代码更简洁;

缺点是,需要熟悉三元运算符的语法才能读懂,不如if语句那样逻辑清晰,易于阅读和理解;

各有优劣,按需使用。

猜你喜欢

转载自blog.csdn.net/qq_33236248/article/details/80176058
今日推荐