在写之前,我们先来看看未简写的代码:
public class Demo { public static void main(String[] args) { String str = null; for (int i = 0; i < 5; i++) { if (str == null) str = i + ""; else str = str + i; } System.out.println("First:" + str); }
运行结果:
First:01234
简写以后:
public class Abbreviate { public static void main(String[] args) { String str = null; for (int i = 0; i < 5; i++) str = str == null ? i + "" : str + i; System.out.println("Second:" + str); } }
str = str == null ? i + “” : str + i;表示如果str等于null,则str等于str+i,否则str等于i+””
运行结果:
Second:01234
评论前必须登录!
注册