Syntactic sugar for getting into Java

1. for and for-each

1.1For and for-each concepts

The for loop is a commonly used loop structure that can control the number and range of the loop through a variable (usually i). The syntax format of the for loop is as follows:

for (初始化; 布尔表达式; 更新) {
  //代码语句
}

The for-each loop is one of the new features of Java 1.5, which can easily traverse the elements in an array or collection without using subscripts or iterators. The syntax format of the for-each loop is as follows:

for (元素类型t 元素变量x : 遍历对象obj) {
  //引用了x的java语句;
}

The efficiency and applicability of for and for-each loops depend on the data structure of the object being traversed. Generally speaking, for array-based data structures like arrays or ArrayList, using a for loop is faster because it can access elements directly by subscript without requiring additional object creation and type conversion. For linked list-based data structures like LinkedList, it is faster to use a for-each loop because it can directly obtain the value of the element without calling the get method each time to traverse.

1.2for-each advantages and disadvantages

2. Enumeration

 An enumeration is a special class used to represent a limited set of constants, such as seasons, colors, directions, etc. Enumerations can improve code readability and safety by avoiding the use of hard-coded strings or integers to represent constants. Enumeration classes are defined using the enum keyword, and each constant is separated by commas.

Java enum types
- all enum types are subclasses of Enum and also inherit corresponding methods

  1. ordinal() returns the index position of the enumeration value, starting from 0
    // 定义一个枚举类型 Season,表示四个季节
    enum Season {
      SPRING, SUMMER, AUTUMN, WINTER;
    }
    
    // 在主方法中,使用 values() 方法获取所有的枚举值,并打印出它们的 ordinal 值
    public class Main {
      public static void main(String[] args) {
        // 获取所有的枚举值
        Season[] seasons = Season.values();
        // 遍历枚举值
        for (Season s : seasons) {
          // 打印出每个枚举值的 ordinal 值
          System.out.println(s + " 的 ordinal 值是 " + s.ordinal());
        }
      }
    }
    
  2. compareTo() compares the index position size of two enumeration values
    public class Test {
        public static void main(String[] args) {
            // 定义两个枚举值
            Season s1 = Season.SPRING;
            Season s2 = Season.WINTER;
            // 使用compareTo()方法比较它们的索引位置大小
            int result = s1.compareTo(s2);
            // 输出结果
            System.out.println(result); // -3
        }
    }
    
    // 定义一个枚举类Season
    enum Season {
        SPRING, SUMMER, AUTUMN, WINTER
    }
    
  3. toString() returns the string representation of the enumeration value
    public class Test {
        public static void main(String[] args) {
            // 定义三个枚举值
            Color c1 = Color.RED;
            Color c2 = Color.GREEN;
            Color c3 = Color.BLUE;
            // 使用toString()方法获取它们的字符串表示
            System.out.println(c1.toString()); // 红色
            System.out.println(c2.toString()); // 绿色
            System.out.println(c3.toString()); // 蓝色
        }
    }
    
    // 定义一个枚举类Color,并重写toString()方法
    enum Color {
        RED, GREEN, BLUE;
    
        @Override
        public String toString() {
            switch (this) {
                case RED:
                    return "红色";
                case GREEN:
                    return "绿色";
                case BLUE:
                    return "蓝色";
                default:
                    return "未知颜色";
            }
        }
    }
    
  4. valueOf() initializes a string into an enumeration object
    public class Test {
        public static void main(String[] args) {
            // 定义一个字符串
            String s = "GREEN";
            // 使用valueOf()方法将字符串转换为枚举值
            Color c = Color.valueOf(s);
            // 输出结果
            System.out.println(c); // GREEN
        }
    }
    
    // 定义一个枚举类Color
    enum Color {
        RED, GREEN, BLUE
    }
    
  5. values() returns all enumeration values
    public class Test {
        public static void main(String[] args) {
            // 使用values()方法返回一个包含所有枚举值的数组
            Season[] seasons = Season.values();
            // 输出数组的长度和内容
            System.out.println(seasons.length); // 4
            for (Season season : seasons) {
                System.out.println(season); // SPRING, SUMMER, AUTUMN, WINTER
            }
        }
    }
    
    // 定义一个枚举类Season
    enum Season {
        SPRING, SUMMER, AUTUMN, WINTER
    }
    

3. Indefinite parameters

Java indefinite parameters are a method that can accept an uncertain number of parameters of the same type. It can be used to simplify method overloading and array passing. The syntax of an indefinite parameter is to add three dots (...) after the parameter type, indicating that the parameter can accept zero to multiple values, and the compiler will encapsulate these values ​​into an array and pass them to the method.

//定义一个不定项参数的方法,用于求和
public static int sum (int... nums) {
    int total = 0;
    for (int num : nums) {
        total += num;
    }
    return total;
}

//调用不定项参数的方法,可以传入任意个数的int值
System.out.println (sum ()); //输出0
System.out.println (sum (1)); //输出1
System.out.println (sum (1, 2, 3)); //输出6
System.out.println (sum (new int [] {4, 5, 6})); //输出15,也可以直接传入一个数组

4. Static import 

Static import is a new feature introduced in Java 5, which allows you to directly access static member variables and methods in a class without using the class name. The syntax for static import is:

import static package.ClassName.fieldName|methodName;

or

import static package.ClassName.*;

The first syntax can import a certain static member variable or method in the specified class, and the second syntax can import all static member variables and methods in the specified class. For example, if you want to use the PI constants and sqrt method from the Math class, you can use static imports:

import static java.lang.Math.PI;
import static java.lang.Math.sqrt;

 5. Automatic packing and unboxing

Autoboxing and unboxing is a feature in Java that allows automatic conversion between basic data types and corresponding wrapper classes. For example, the int type can be automatically converted to an Integer object, and the Integer object can be automatically converted to an int value. This makes it easy to switch between object-oriented and basic types, simplifying code writing.

6. Multiple anomalies juxtaposed

Multi-exception concatenation is a feature introduced in Java 7 that allows you to catch multiple exceptions of different types in a catch block and handle them in the same way. This avoids duplication of code and logic and simplifies the exception handling process.

When using multiple exceptions in parallel, please pay attention to the following points:

  • There can only be one exception object in a catch block, and it cannot be written in the form of catch (ExceptionType1 e1 | ExceptionType2 e2 | ... e3).
  • There cannot be an inheritance relationship between multiple exception types, otherwise it will cause compilation errors. For example, you cannot write catch (IOException | FileNotFoundException e) because FileNotFoundException is a subclass of IOException.
  • If there are multiple catch blocks, the catch blocks with multiple exceptions should be placed at the front, otherwise they will be covered by other catch blocks. For example, you cannot write catch (Exception e) {…} catch (NumberFormatException | ArithmeticException e) {…} because Exception is the parent class of all exceptions.
public class Test {
    public static void main(String[] args) {
        try {
            int a = Integer.parseInt("abc"); //可能抛出NumberFormatException
            int b = 10 / 0; //可能抛出ArithmeticException
        } catch (NumberFormatException | ArithmeticException e) {
            //这个catch块可以捕获两种异常,并统一处理
            System.out.println("发生了数学错误:" + e.getMessage());
        } catch (Exception e) {
            //这个catch块可以捕获其他类型的异常,并单独处理
            System.out.println("发生了其他错误:" + e.getMessage());
        }
    }
}

 In the above code, the first catch block uses multiple exception syntax, which can capture NumberFormatException and ArithmeticException at the same time and output their information. The second catch block can catch other types of exceptions and output their information. This avoids duplication of code and logic and simplifies the exception handling process.

If you reverse the order of the two catch blocks, it will cause a compilation error, because the first catch block will catch all types of exceptions, including NumberFormatException and ArithmeticException, then the second catch block will never be executed. This violates the rules of polymorphism and overloading, so the compiler will prompt an error.

7. Integer types are represented in binary

7.1 Binary

7.2 Underline

 8. Interface

8.1 Default methods of interfaces

The default method of an interface is a new feature introduced in Java 8, which allows the interface to define some methods with specific implementations without the need for implementation classes to implement these methods. This makes it easy to add new functions to the interface without affecting existing implementation classes. The syntax of the default method of the interface is to add the default keyword in front of the method name.

public interface MyInterface {
    // 普通的抽象方法
    void abstractMethod();
    // 默认方法
    default void defaultMethod() {
        System.out.println("这是一个默认方法");
    }
}

 The default methods of the interface have the following functions:

  • Compatibility: The default methods of an interface allow the interface to add new methods backwards compatible without breaking existing code. In this way, there is no need to modify all classes that implement the interface, but only need to override or call the default method where needed.
  • Multiple inheritance: The default method of an interface allows a class to implement multiple interfaces without worrying about the same method signatures between interfaces. If a class implements multiple interfaces and these interfaces have the same default method, then the class must override this default method, or use the super keyword to specify which interface's default method to call.
  • Extensibility: The default method of an interface allows the interface to provide some common functions without the need to repeatedly write the same code in each implementation class. For example, the List interface provides a sort method, which can sort the list without requiring each list class to implement its own sorting algorithm.

8.2 Static methods of interfaces

The static method of the interface is a new feature introduced in Java 8, which allows the interface to define some static methods with specific implementations without the need for the implementation class to call these methods. This can easily provide the interface with some interface-related tool methods or some common logic. The syntax of the static method of the interface is to add the static keyword in front of the method name, for example:

public interface MyInterface {
    // 普通的抽象方法
    void abstractMethod();
    // 静态方法
    static void staticMethod() {
        System.out.println("这是一个静态方法");
    }
}

The static methods of interfaces have the following characteristics:

  • Static methods of an interface can only be called through the interface name, not through the implementation class or the object of the implementation class. For example, MyInterface.staticMethod(); can call a static method, but MyClass.staticMethod(); or new MyClass().staticMethod(); will report an error.
  • The static methods of an interface cannot be inherited or overridden by the implementation class, nor can they be inherited or overridden by sub-interfaces. If the implementation class or sub-interface defines a method with the same signature as the static method in the interface, then this method has nothing to do with the static method in the interface and is just an ordinary method.
  • Static methods of an interface can access constants defined in the interface, but cannot access abstract methods and default methods defined in the interface. If you need to call an abstract method or default method in a static method, you can do so by passing in an object of the implementation class as a parameter.

8.3 Private methods of interfaces

Private methods of interfaces are a new feature introduced in Java 9, which allow the interface to define some private methods with specific implementations without requiring the implementation class to implement or call these methods. This can easily provide the interface with some interface-related tool methods or some common logic. The syntax of a private method of an interface is to add the private keyword in front of the method name, for example:

public interface MyInterface {
    // 普通的抽象方法
    void abstractMethod();
    // 私有方法
    private void privateMethod() {
        System.out.println("这是一个私有方法");
    }
}

The private methods of the interface have the following functions:

  • Encapsulation: Private methods of an interface can hide some details or auxiliary functions in the interface without exposing them to the outside world. This protects the internal logic of the interface from misuse or abuse.
  • Reusability: The private methods of the interface can allow some repeated or similar code in the interface to be extracted without having to write it repeatedly in each default method or static method. This improves code reusability and maintainability.
  • Flexibility: The private methods of an interface can make the default methods or static methods in the interface more flexible and concise without containing too much code or logic. This improves code readability and scalability.

8.4 Interfaces and abstract classes

 Supplement: abstract class

A Java abstract class is a class that cannot be instantiated. Its function is to be inherited by other classes and implement its abstract methods. An abstract method is a method that is only declared but not implemented. It needs to be overridden in a subclass. An abstract class can contain non-abstract methods and properties, but it must have at least one abstract method. In Java, abstract classes are modified with the abstract keyword, for example:

abstract class Animal { public abstract void eat(); // Abstract method public void sleep() { // Non-abstract method System.out.println(“Animal is sleeping”); } }

If all methods of a class are not implemented, then the class is considered an interface.

九、try-with-resources

try-with-resources is a feature introduced in Java 7 that allows you to declare one or more resources that need to be closed in a try statement, such as files, streams, sockets, etc. The try-with-resources statement ensures that each resource will be automatically closed after the statement ends, regardless of whether an exception occurs. This avoids the trouble of manually closing resources and avoids the risk of resource leaks.

The syntax of the try-with-resources statement is:

try (ResourceType resource = new ResourceType(...)) {
    // 使用资源的代码
} catch (ExceptionType e) {
    // 处理异常的代码
}

Among them, ResourceType is the type of resource to be closed. It must implement the AutoCloseable interface. This interface has only one method, close(), which is used to release resources. resource is the object of the resource to be closed, it must be declared and initialized in the try statement. You can declare multiple resources in a try statement, just separate them with semicolons. For example:

try (BufferedReader br = new BufferedReader(new FileReader("input.txt"));
     PrintWriter pw = new PrintWriter(new FileWriter("output.txt"))) {
    // 读写文件的代码
} catch (IOException e) {
    // 处理异常的代码
}

In this way, regardless of whether the code for reading and writing files is executed normally, br and pw will be automatically closed.

十、ResourceBundle

ResourceBundle is a class in Java that can be used to implement internationalization (i18n) functions, which means that the program can display different information according to different languages ​​and regions. ResourceBundle can load language and region-related data from different files, such as properties files (.properties) or Java class files (.java). ResourceBundle can automatically select appropriate files based on the user's Locale (language and region), or you can manually specify the files to be loaded. ResourceBundle can store and obtain data through key-value pairs, or through subscripts. ResourceBundle has two commonly used subclasses: PropertyResourceBundle and ListResourceBundle, which correspond to property files and Java class files respectively. 

10.1Multi-language support

A common way to implement multi-language support in Java programs is to use the ResourceBundle class, which can load language and region-related data from different files, such as properties files (.properties) or Java class files (.java). The ResourceBundle class can automatically select appropriate files based on the user's Locale (language and region), or you can manually specify the files to be loaded. The ResourceBundle class can store and obtain data through key-value pairs, or through subscripts.

To use the ResourceBundle class, you need to follow these steps:

  • The first step is to create one or more resource files. Each resource file has a base name and an additional part of local information. For example, messages_zh_CN.properties represents a property file with the base name of messages and the local information of zh_CN (Simplified Chinese). Each resource file defines some key-value pairs to store text information in different languages. For example:
username=用户名
password=密码
  • The second step is to create a ResourceBundle object, use the getBundle method to load the resource file, and pass in the base name and Locale object. For example:
Locale locale = Locale.getDefault(); // 获取默认的语言和地区
ResourceBundle bundle = ResourceBundle.getBundle("messages", locale); // 加载资源文件
  • The third step is to use the getString method of the ResourceBundle object to obtain the value corresponding to the specified key and display it in the program. For example:
String username = bundle.getString("username"); // 获取用户名对应的文本
String password = bundle.getString("password"); // 获取密码对应的文本
System.out.println(username + ": " + password); // 输出文本

11. var type

The var type is a feature introduced in Java 10. It allows you to declare local variables without explicitly specifying the type of the variable. Instead, the compiler infers the type of the variable based on the initial value of the variable. The var type can simplify code writing, avoid repeated type names, and can also be used to handle anonymous types or complex expressions. However, the var type also has some restrictions and precautions. For example, it can only be used for local variables and cannot be used for member variables of a class. It must be assigned an initial value when declaring, cannot be assigned a null value, cannot be used for the declaration of multiple variables, etc. .

12. Switch

Guess you like

Origin blog.csdn.net/qq_62377885/article/details/132910233