- 旧的写法:在java代码⾥⾯编写多⾏源码带有特殊字符则需要转义,如HTML,sql等
# 案例1
public class Main{
public static void main(String [] ags){
String html = "<html>\n" +
" <body>\n" +
" <p>Hello, world</p>\n" +
" </body>\n" +
"</html>\n";
}
}
# 案例2
public class Main{
public static void main(String [] ags){
String query = "SELECT `EMP_ID`, `LAST_NAME` FROM `EMPLOYEE_TB`\n" +
"WHERE `CITY` = 'INDIANAPOLIS'\n" +
"ORDER BY `EMP_ID`, `LAST_NAME`;\n";
}
}
- 新的写法:原⽣字符串⽂字(raw string literals),它可以跨多⾏源码⽽不对转义字符进⾏转义
# 案例1
public class Main{
public static void main(String [] ags){
String html = """
<html>
<body>
<p>Hello, world</p>
</body>
</html>
""";
}
}
# 案例2
public class Main{
public static void main(String [] ags){
String query = """
SELECT `EMP_ID`, `LAST_NAME` FROM `EMPLOYEE_TB`
WHERE `CITY` = 'INDIANAPOLIS'
ORDER BY `EMP_ID`, `LAST_NAME`;
""";
}
}
# 开启新版⽀持
jshell --enable-preview
# 错误写法
"""line 1
line 2
line 3
"""
# 正确写法1
"""
line 1
line 2
line 3"""
# 正确写法2
"""
line 1
line 2
line 3
"""