Which of the following is a valid declaration and initialization of a String array in Java?
A. String[] names = {"Alice", "Bob", "Charlie"};
B. String names[] = new String[]{"Alice", "Bob", "Charlie"};
C. String[3] names = {"Alice", "Bob", "Charlie"};
D. Both A and B
E. Both B and C
Answer: Option D
Solution (By Examveda Team)
Option A initializes a String array named "names" with three elements: "Alice", "Bob", and "Charlie".This is a valid and commonly used syntax for declaring and initializing a String array in Java.
Option B:
String names[] = new String[]{"Alice", "Bob", "Charlie"};
This syntax is also valid for declaring and initializing a String array in Java. However, it's less commonly used.
Option C:
String[3] names = {"Alice", "Bob", "Charlie"};
This syntax is invalid. In Java, when declaring an array, the size should not be specified in the square brackets.
Which of the following is a valid declaration and initialization of a String array in Java?
A. String[] names = {"Alice", "Bob", "Charlie"};
B. String names[] = {"Alice", "Bob", "Charlie"};
C. String[3] names = {"Alice", "Bob", "Charlie"};
D. All of the above
option A and option B both are true and valid why given only answer A