113.java基础22(java12&13新特性回顾)

1.java11 witch表达式

1.传统switch的弊端
传统的switch声明语句(switch statement)在使用中有一些问题:
匹配是自上而下的,如果忘记写break, 后面的case语句不论匹配与否都会执行;
所有的case语句共用一个块范围,在不同的case语句定义的变量名不能重复;
不能在一个case里写多个执行结果一致的条件;
整个switch不能作为表达式返回值;
    
package com.atguigu.java;
import org.junit.Test;
/**
 * @author shkstart
 * @create 2019 下午 3:13
 */
public class SwitchTest1 {
    //java 12的新特性
    @Test
    public void testSwitch1(){
        Fruit fruit = Fruit.APPLE;
        switch(fruit) {
            case PEAR -> System.out.println("4");
            case APPLE,GRAPE,MANGO -> System.out.println("5");
            case ORANGE,PAPAYA -> System.out.println("6");
            default -> throw new IllegalStateException("No Such Fruit:" + fruit);
        }
    }

    @Test
    public void testSwitch2(){
        int numberOfLetters;
        Fruit fruit = Fruit.APPLE;
        numberOfLetters = switch(fruit) {
            case PEAR -> 4;
            case APPLE,GRAPE,MANGO -> 5;
            case ORANGE,PAPAYA -> 6;
            default -> throw new IllegalStateException("No Such Fruit:" + fruit);
        };
        System.out.println(numberOfLetters);
    }
}

2.java11 JVM 常量 API:

 package com.atguigu.java;
import java.util.Optional;
/**
 * @author shkstart
 * @create 2019 下午 5:18
 */
public class StringConstantTest {
    private static void testDescribeConstable() {
        System.out.println("======test java 12 describeConstable======");
        String name = "尚硅谷Java高级工程师";
        Optional<String> optional = name.describeConstable();
        System.out.println(optional.get());
    }
    public static void main(String[] args) {
        testDescribeConstable();
    }
}

3.java11 支持压缩数字格式化:

@Test public void testCompactNumberFormat(){ var cnf = NumberFormat.getCompactNumberInstance(Locale.CHINA, NumberFormat.Style.SHORT); System.out.println(cnf.format(1_0000)); System.out.println(cnf.format(1_9200)); System.out.println(cnf.format(1_000_000)); System.out.println(cnf.format(1L << 30)); System.out.println(cnf.format(1L << 40)); System.out.println(cnf.format(1L << 50)); }

输出:
	1万
    2万
    100万 
    11亿 
    1兆
    1126兆

4.java11 String新增方法:

package com.atguigu.java;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author shkstart
 * @create 2019 下午 8:19
 */
public class StringTest {
    @Test
    public void testTransform(){
        String info1 = "  hello".transform(info -> info + "world  ");
        System.out.println(info1);
    }
    //   hello --> helloworld   -->   HELLOWORLD   --> HELLOWORLD
    //映射:java 8 中 Stream API :map() 
educe()
    @Test
    public void testTransform1(){
        var info1 = "hello".transform(info -> info + "world").transform(String::toUpperCase).transform(String::trim);
        System.out.println(info1);
    }

    @Test
    public void testTransform2(){
        System.out.println("======test java 12 transform======");
        List<String> list1 = List.of("Java", " Python", " C++ ");
        List<String> list2 = new ArrayList<>();
        list1.forEach(element -> list2.add(element.transform(String::strip)
                .transform(String::toUpperCase)
                .transform(e -> "Hi," + e))
        );
        list2.forEach(System.out::println);
    }

    @Test
    public void testTransform3(){
        System.out.println("======test java 12 transform======");
        List<String> list1 = List.of("Java", " Python", " C++ ");
        Stream<String> strStream = list1.stream().map(word -> word.strip()).map(String::toUpperCase).map(word -> "hello," + word);
        List<String> list2 = strStream.collect(Collectors.toList());
        list2.forEach(System.out::println);
    }

    //String中的indent()
    @Test
    public void testIndent() {
        System.out.println("======test java 12 indent======");
        String result = "Java
 Python
C++".indent(3); //如果没有换行在行首补上3个空格,如果存在换行在每行的行首补上3个空格
        System.out.println(result);
    }
}

5.java11 Files新增mismatch方法:

//比较两个文件的对应行,如果所有行都相同返回0, 否则返回行编号默认从0开始
package com.atguigu.java;
import org.junit.Test;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
/**
 * @author shkstart
 * @create 2019 下午 8:46
 */
public class FilesTest {
    //使用IDEA的单元测试方法,默认的相对路径是在当前module下
    //IO : File
    //NIO 2 : Files操作本地文件的工具类  ; Path:替换原有的File ; Paths :实例化Path
    @Test
    public void testFilesMismatch() throws IOException {
        FileWriter fileWriter = new FileWriter("tmp\a.txt");
        fileWriter.write("a");
        fileWriter.write("b");
        fileWriter.write("c");
        fileWriter.close();
        FileWriter fileWriterB = new FileWriter("tmp\b.txt");
        fileWriterB.write("a");
        fileWriterB.write("b");
        fileWriterB.write("c");
        fileWriterB.close();
        System.out.println(Files.mismatch(Path.of("tmp/a.txt"),Path.of("tmp/b.txt")));
    }
}

6.java13 switch表达式(预览):

package com.atguigu.java;
import org.junit.Test;
/**
 * @author shkstart
 * @create 2019 下午 9:12
 */
public class SwitchTest {
    @org.junit.Test
    public void testSwitch1(){
        String x = "1";
        int i;
        switch (x) {
            case "1":
                i=1;
                break;
            case "2":
                i=2;
                break;
            default:
                i = x.length();
                break;
        }
        System.out.println(i);
    }
    //java 13:switch中引入yield,可以返回值给相应的变量
    @Test
    public void testSwitch2(){
        String x = "1";
        int i = switch(x){
            case "1" -> 5;
            case "2" -> 6;
            default -> {
                yield 7;
            }
        };
        System.out.println(i);
    }
    @Test
    public void testSwitch3(){
        String x = "3";
        int i = switch(x){
            case "1" : yield 5;
            case "2" : yield 6;
            default : yield 7;
        };
        System.out.println(i);
    }
    //yield 和 return
    //yield:结束switch结构
    //return:结束方法
}

7. java13 文本块:

package com.atguigu.java;
import org.junit.Test;

import java.util.Objects;

/**
 * java 13新特性:TextBlock (预览)
 * @author shkstart
 * @create 2019 下午 3:00
 */
public class TextBlockTest {
    @Test
    public void test1(){
        String html = "<html>
" +
                "  <body>
" +
                "      <p>Hello, 尚硅谷</p>
" +
                "  </body>
" +
                "</html>";
        System.out.println(html);
        System.out.println();
        String html1 = """
<html>
  <body>
      <p>Hello, 尚硅谷</p>
  </body>
</html>
""";
        System.out.println(html1);
    }
    @Test
    public void test2(){
        String sql = "select employee_id,last_name,salary,department_id
" +
                "from employees
" +
                "where department_id in (40,50,60)
" +
                "order by department_id asc";
        System.out.println(sql);
        String sql1 = """
select employee_id,last_name,salary,department_id
from employees
where department_id in (40,50,60)
order by department_id asc
""";
        System.out.println(sql1);
    }
//////////////////////////////////////////////////////////////////////////
    //关于TextBlock的基本使用
    @Test
    public void test3(){
        //以开始分隔符的行终止符后的第一个字符开始
        //以结束分隔符的第一个双引号之前的最后一个字符结束
        String text1 = """
abc""";
        String text2 = "abc";
        System.out.println(text1 == text2);//text1和text2都指向了字符串常量池中唯一定义的abc字面量
        String text3 = """
abc
""";
        System.out.println(text1.length());//3
        System.out.println(text3.length());//4 test3后面还有一个换行符
    }
    //空字符串的表示
    @Test
    public void test4(){
        String text1 = "";
        System.out.println(text1.length()); //1
        String text2 = """
""";
        System.out.println(text2.length()); //1
        System.out.println(test1 == test2); //true
    }
    //错误的写法
    @Test
    public void text5(){
//        String a = """""";   // 开始分隔符后没有行终止符
//        String b = """ """;  // 开始分隔符后没有行终止符
//        String c = """
//           ";        // 没有结束分隔符
//String d = """
//        abc  def
//        """;      // 含有未转义的反斜线(请参阅下面的转义处理)
//
//        String e = "abc  def";
    }
    //编译器在编译时会删除掉这些多余的空格(结尾会直接去掉,但是前面的空格比较特殊,会和结束分隔符进行相应的比较,如果是和结束分隔符对齐的则去电,去个不是对齐的则不去掉:如下)
    @Test
    public void test6(){
        String text1 = """
    abc
    """;
        System.out.println(text1.length());//4
        
        String text2 = """
      abc  //这里我加了两个空格
    """;
        System.out.println(text1.length());//6
        
                String text2 = """
      abc  //这里我加了两个空格
      """; //这里我也加了两个空格
        System.out.println(text1.length());//4
    }
    // 转义字符
    @Test
    public void test7(){
        String html = """
              <html>
                  <body>

                      <p>Hello, world</p>

                  </body>

              </html>

              """;
        System.out.println(html);
    }
    //在文本块内自由使用"是合法的
    @Test
    public void test8(){
        String story = """
    "When I use a word," Humpty Dumpty said,
    in rather a scornful tone, "it means just what I
    choose it to mean - neither more nor less."
    "The question is," said Alice, "whether you
    can make words mean so many different things."
    "The question is," said Humpty Dumpty,
    "which is to be master - that's all."
""";
        System.out.println(story);
        String code =
                """
    String text = """
        A text block inside a text block
    """;
    """;
        System.out.println(code);
    }
    //文本块连接
    @Test
    public void test9(){
        String type = "String";
        String code = """
              public void print(""" + type + """
               o) {
                  System.out.println(Objects.toString(o));
              }
              """;
        System.out.println(code);
        //改进:可读性更好  ---方式1
        String code1 = """
              public void print($type o) {
                  System.out.println(Objects.toString(o));
              }
              """.replace("$type", type);
        System.out.println(code1);
        //方式2
        String code2 = String.format("""
              public void print(%s o) {
                  System.out.println(Objects.toString(o));
              }
              """, type);
        System.out.println(code2);
        //方式3
        String code3 = """
                public void print(%s object) {
                    System.out.println(Objects.toString(object));
                }
                """.formatted(type);
        System.out.println(code3);
    }
}
原文地址:https://www.cnblogs.com/liuzhanghao/p/13958329.html