How to define an array of strings in Java?
You can define a string array in Java using the following syntax:
String[] arrayName = new String[length];
arrayName is the name of the array, while length represents the number of strings that can be stored in the array.
For example, you can define a string array with a length of 3 using the following code:
String[] names = new String[3];
This defines a string array named names that can store three strings.
In addition to using fixed-length arrays, you can also define a string array using the following syntax format:
String[] arrayName = {"string1", "string2", "string3"};
This defines an array of strings containing three elements.
Example code:
String[] names = new String[3];
names[0] = "Alice";
names[1] = "Bob";
names[2] = "Charlie";
System.out.println(names[0]); // 输出:Alice
System.out.println(names[1]); // 输出:Bob
System.out.println(names[2]); // 输出:Charlie
String[] cities = {"New York", "London", "Tokyo"};
System.out.println(cities[0]); // 输出:New York
System.out.println(cities[1]); // 输出:London
System.out.println(cities[2]); // 输出:Tokyo
The above code demonstrates how to define and access elements in a string array.