String array initialization

Recently, the author made a mistake in the initialization of String array due to negligence in java programming, which caused the program to run incorrectly. Now the understood String array will be explained here, and the initialization of the String array will be analyzed.

//One-dimensional array
String[] str = new String[5]; //Create a one-dimensional array of String (string) type with length 5
String[] str = new String[]{"","", "","",""};
String[] str = {"","","","",""};
//two-dimensional array
String[][] str = new String[2][ 2]; //Create a two-dimensional array with 2 rows and 2 columns

String array initialization difference
  String[] str = {"1","2","3"} and String[] str = new String[]{"1 What is the difference between ","2","3"} in memory?
  Compilation and execution results do not make any difference. It is even more impossible to allocate space on the stack as some people take for granted. Java objects are allocated space on the heap.

  The difference here is only in the code: 
String[] str = {"1","2","3"}; This form is called an Array Initializer and can only be used in the case of declarations and assignments.
  String[] str = new String[]{"1","2","3"} is a general form of assignment. The right side of the = sign is called an Array Literal. Array literals can be used in any need. An array of places (types are compatible). For example:
  String[] str = {"1","2","3"}; // correct
  String[] str = new String[]{"1","2","3"} // also correct
and
  String[] str;
  str = {"1","2","3"}; / / Compiler error
because array initializers can only be used in the case of declarations and assignments.

Change to:
  String[] str;
  str = new String[] {"1","2","3"}; // Correct again
:
  void f(String[] str) {
  }
  f({"1 ","2","3"}); //
The correct one should be:
  f(new String[] {"1","2","3"});

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326615862&siteId=291194637