1. Declare string array
In Java, when declaring a string array, you need to specify the size of the array or usenew
Keyword allocates memory.
demo:
public class StringArrayDeclaration { public static void main(String[] args) { // Declare an array of strings, no size specified String[] stringArray; // Declare and allocate memory, for example, create a string array of length 5 stringArray = new String[5]; } }
2. Initialization of string arrays
String arrays can be initialized while declared. Each element can be initialized separately, or the entire array can be initialized using array literals.
demo:
public class StringArrayInitialization { public static void main(String[] args) { // Initialize an array of strings using array literals String[] stringArray = {"Apple", "Banana", "Cherry"}; // Another way of initialization, each element is initialized separately String[] dynamicStringArray = new String[3]; dynamicStringArray[0] = "Apple"; dynamicStringArray[1] = "Banana"; dynamicStringArray[2] = "Cherry"; } }
3. The default value of string array
If you create a string array but not initialized, each element will be initialized by defaultnull
。
demo:
public class StringArrayDefaultValues { public static void main(String[] args) { String[] uninitializedArray = new String[5]; // The default value in the output array for (String value : uninitializedArray) { (value); // Output: null null null null null } } }
4. Traversal of string arrays
You can use a for loop or an enhanced for-each loop to iterate through all elements in a string array.
demo:
public class StringArrayTraversal { public static void main(String[] args) { String[] stringArray = {"Apple", "Banana", "Cherry"}; // Use for loop to loop through string array for (int i = 0; i < ; i++) { (stringArray[i]); // Output: Apple Banana Cherry } // Loop through string arrays using enhanced for-each for (String value : stringArray) { (value); // Output: Apple Banana Cherry } } }
5. Common operations of string arrays
String arrays support common array operations, such as sorting, filling, copying, searching, etc.
demo: sort
import ; public class StringArrayOperations { public static void main(String[] args) { String[] stringArray = {"Apple", "Banana", "Cherry"}; // Sort string arrays using Arrays class (stringArray); ((stringArray)); // Output: [Apple, Banana, Cherry] } }
Summarize
This is the end of this article about the creation of Java string arrays. For more related content on Java string array creation, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!