Hint: Use 'new' keyword and specify size in brackets [OK]
Common Mistakes:
Forgetting 'new' keyword
Using wrong brackets or missing type
Declaring array without brackets
2. Which of the following is a valid way to declare and initialize an array with values in Java?
easy
A. int[] arr = new int[] {1, 2, 3, 4};
B. int arr[] = new int{1, 2, 3, 4};
C. int[] arr = new int{1, 2, 3, 4};
D. int arr = {1, 2, 3, 4};
Solution
Step 1: Understand array initialization with values
In Java, to initialize an array with values using 'new', syntax is: int[] arr = new int[] {values};
Step 2: Check each option
int[] arr = new int[] {1, 2, 3, 4};: correct syntax. int arr[] = new int{1, 2, 3, 4};: incorrect declaration style and missing [] after new int. int[] arr = new int{1, 2, 3, 4};: missing [] after new int. int arr = {1, 2, 3, 4};: arr not declared as array.
Final Answer:
int[] arr = new int[] {1, 2, 3, 4}; -> Option A
Quick Check:
Array init with 'new int[]' = int[] arr = new int[] {1, 2, 3, 4}; [OK]
Hint: Use 'new int[]' when initializing separately [OK]
Common Mistakes:
Omitting 'new' when required
Using wrong brackets
Assigning values without array type
3. What will be the output of the following Java code?