Comparison of two methods of Java variable initialization and their advantages and disadvantages

The first initialization method: (preferred)

String fileRename = null; 

File fileToSave = null; 

This approach limits the scope of the variables outside the loop, making them available throughout the entire block of code. An initial value of null means that the variable has no specific value at the beginning.

The reasons this approach is better are:

  • This avoids repeated definition of variables and saves memory space.

  • When using the same variable name inside a loop, you can avoid logical errors caused by repeated assignment of variables.

The second initialization method: (not recommended)

List<String> fileUrls = new ArrayList<String>(); 

This method limits the scope of the variable to the inside of the loop, that is, the variable can only be used inside the loop. The initial value is an ArrayList instance, which means that the variable has been initialized to an empty List at the beginning.

If you want to change the second initialization method to the first initialization method, you need to move the definition of the variable outside the loop and add an initial value of null. It can be modified as follows:

List<String> fileUrls = null;

 Move all variable definitions outside the loop and initialize them to null. This can clearly express that the variable does not have a specific value at the beginning, and facilitates subsequent code logic processing. The difference between the two initialization methods is the scope and initial value.

If you declare a variable named fileUrls somewhere in your code and initialize it to , then you need to pay attention to the NullPointerException issue when subsequently referencing this variable. List<String>null

You should check if it is empty before usingfileUrls. You can use conditional statements (such as the if statement) to check whether the variable is null and then process it accordingly.

if (fileUrls != null) { 
  // 在这里可以安全地使用 fileUrls 变量 
  // 例如,可以调用 fileUrls 的方法或迭代它的元素 // 示例:遍历并输出每个文件URL 
    for (String url : fileUrls) { 
        System.out.println(url); 
    } 
    } else { 
     // 如果 fileUrls 为 null,可以根据需求做出相应的处理 // 示例:打印出提示信息         
     System.out.println("fileUrls 是 null");
}

In the above code, first check whether fileUrls is null, if not null, execute the corresponding action, otherwise execute the alternative.

Remember that any potentially null variable should be checked for null before use to make your code more robust and reliable.

        Of course, in addition to initializing variables of type List<String> to null, there are many other ways to initialize them. The following are several common initialization methods:

  1. Initialize with an empty list:

    CodeList<String> fileUrls = new ArrayList<>();
  2. Add elements to initialize when creating the list:

    CodeList<String> fileUrls = Arrays.asList("url1", "url2", "url3");
  3. Initialize using a static initialization block:

    CodeList<String> fileUrls;
    {
        fileUrls = new ArrayList<>();
        fileUrls.add("url1");
        fileUrls.add("url2");
        fileUrls.add("url3");
    }

  4. Initialization using Java 8’s Stream API:

    CodeList<String> fileUrls = Stream.of("url1", "url2", "url3")
                                   .collect(Collectors.toList());
  5. Use Double Brace Initialization:

    CodeList<String> fileUrls = new ArrayList<String>() {
         
         {
        add("url1");
        add("url2");
        add("url3");
    }};

Replenish:

Variable assignment
Initializing a variable means assigning a clear initial value to the variable. There are two ways to initialize variables: one is to assign values ​​directly when declaring, and the other is to declare first and then assign values. The following code initializes variables in two ways.

char usersex='女'; // 直接赋值

or

String username; // 先声明
username ="琪琪"; // 后赋值

In addition, multiple variables of the same type can be defined or initialized at the same time, but multiple variables must be separated by commas and semicolons at the end of the declaration.

String username,address,phone,tel; // 声明多个变量
int num1=12,num2=23,result=35; // 声明并初始化多个变量

When initializing variables in Java, you need to pay attention to the following:

A variable is a field in a class or structure. If not explicitly initialized, the variable is created by default and has a default initial value of 0.
The variable in the method must be explicitly initialized, otherwise an error will occur when using the variable

In fact, regarding the methods of variable initialization, Java provides four methods of variable initialization.

        All variables in Java have a default value. This default value depends on the type of the variable, not the variable name or specific value. If a variable is not assigned an initial value, the system will automatically initialize it to the default value of the corresponding type.

Initialize variables with default values

        Among the basic data types of Java, the default value of numeric type is 0, the default value of Boolean type is false, and the default value of reference data type is null. For example:

int num;
boolean flag;
String str; 

System.out.println(num); //输出0
System.out.println(flag); //输出false
System.out.println(str); //输出null 

Direct assignment to initialize variables

Direct assignment means directly assigning a specific value to the variable when creating the variable. This method is the most common. For example:

​​​​​​​int num = 10;
String str = "hello";
double pi = 3.1415926;

This method is the most common and easiest to understand. Just assign the variable to the required value directly.

Initialize variables via constructor

        ​​​​The way to initialize variables through the constructor is similar to direct assignment, except that this method initializes the variables through the constructor of the class. For example:

public class Person {    
    private String name;    
    private int age;
}


public Person() {        
    name = "张三";        
    age = 18;    
   }
} 

In this example code, the constructor in the Person class initializes two variables, name and age. The variables are initialized to their default values ​​when the Person class object is created.

Initialize variables through static blocks

Java also provides a way to initialize variables through static blocks. Static blocks are executed when the class is loaded, taking precedence over the execution of the constructor method. Static blocks will only be executed once, and when a class is loaded multiple times, static blocks will only be executed once. For example:

public class Person { 
  private static String nation;
}

static{        
    nation = "China";    
 }
} 

In the above code, the static block in class Person initializes the variable nation, which will be initialized to "China" when the class is loaded.

        These four methods can be used to initialize variables. Which method to use depends on the specific situation. Default value initialization is the most basic way, but it may not be suitable for all situations. Direct assignment and initializing variables through constructors are the most common methods, and they are relatively simple to use. Initializing variables through static blocks is more suitable for situations where variables need to be initialized in a static environment.

Guess you like

Origin blog.csdn.net/weixin_49171365/article/details/134324480