回字有四种写法,构建字符串也有四种方式。
用+号最快,第二第三种可读性好,第四种是log4j自有的。下面请见代码:
package logbackCfg; import java.text.MessageFormat; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; public class StringContructor {
private final static Logger logger = LoggerFactory.getLogger(StringContructor.class); public static void main(String[] arges) {
int count=5;
String city="Dalian"; // 1.Traditional and fastest String construction pattern
System.out.println("There are "+count+" million people live in "+city+"."); // 2.String.format pattern
System.out.println(String.format("There are %d million people live in %s.", count,city)); // 3.MessageFormat pattern
String raw="There are {0} million people live in {1}.";
Object[] arr={String.valueOf(count),city};
String result=MessageFormat.format(raw, arr);
System.out.println(result); // 4.log4j/logback built-in pattern
logger.info("There are {} million people live in {}.",count,city);
}
}
输出:
There are 5 million people live in Dalian.
There are 5 million people live in Dalian.
There are 5 million people live in Dalian.
2020-03-06 16:51:25.394 [main] INFO logbackCfg.StringContructor -There are 5 million people live in Dalian.
--2020-03-06--