Java:如果结果为null,如何分配给变量?

时间:2012-12-18 09:48:45

标签: java null

这有效:

String address1 = HtmlUtil.escape(rs.getString("address1"));

...但我不想显示“null”。所以我尝试了这个,这不起作用:

String address1 = HtmlUtil.escape(rs.getString("address1") || "");

是使用它的最佳选择:?

String address1 = HtmlUtil.escape(rs.getString("address1"));
if (address1 == null) address1 = "";

7 个答案:

答案 0 :(得分:6)

使用三元运算符,您可以使用单行代码分配值:

String address1 = (rs.getString("address1") != null) ?
                  HtmlUtil.escape(rs.getString("address1")) : "";

答案 1 :(得分:4)

String address1 = HtmlUtil.escape(rs.getString("address1"));
if (address1 == null || address1.equals("null")) {
    address1 = "";
}

答案 2 :(得分:1)

String address1 = HtmlUtil.escape(rs.getString("address1")) == null ? "" : HtmlUtil.escape(rs.getString("address1")); 

如果你想要丑陋的单行: - )

答案 3 :(得分:1)

使用temp变量仅调用HtmlUtil.escape一次。然后检查null并分配给address1

String tempAddress =  HtmlUtil.escape(rs.getString("address1"));
String address1 = tempAddress != null ? tempAddress : "";

答案 4 :(得分:1)

解决方案:

 String address1 = HtmlUtil.escape(rs.getString("address1"));
 if (address1 == null) address1 = "";

答案 5 :(得分:0)

尝试这样的事情

<c:when test="${empty rs.getString("address1")}">
  ...
</c:when>
<c:otherwise>
   .....
</c:otherwise>

答案 6 :(得分:0)

你可以试试这个:

String address1 = "";
if(HtmlUtil.escape(rs.getString("address1") != null && !(HtmlUtil.escape(rs.getString("address1").equalsIgnoreCase("null"))){
address1 = HtmlUtil.escape(rs.getString("address1"));
}