0
0
Javaprogramming~15 mins

Array declaration and initialization in Java - Cheat Sheet & Quick Revision

Choose your learning style8 modes available
overviewRecall & Review
beginner
What is the correct way to declare an array of integers in Java?
You declare an array of integers by specifying the type followed by square brackets and the array name, like this: int[] numbers;
touch_appClick to reveal answer
beginner
How do you initialize an array with specific values at the time of declaration?
You can initialize an array with values using curly braces, like this: int[] numbers = {1, 2, 3, 4};
touch_appClick to reveal answer
beginner
What happens if you declare an array but do not initialize it?
The array variable will point to null and trying to use it will cause a NullPointerException. You must initialize it before use.
touch_appClick to reveal answer
beginner
How do you create an empty array of size 5 for integers?
You create it by specifying the size with new: int[] numbers = new int[5];. This creates an array with 5 elements, all initialized to 0.
touch_appClick to reveal answer
beginner
Can you change the size of an array after it is created in Java?
No, arrays in Java have a fixed size once created. To have a resizable collection, use classes like ArrayList.
touch_appClick to reveal answer
Which of the following is a valid array declaration and initialization in Java?
Aint[] arr = {10, 20, 30};
Bint arr = new int[3];
Cint arr[] = new int;
Dint arr = {1, 2, 3};
What is the default value of elements in a newly created int array in Java?
A1
Bnull
Cundefined
D0
How do you declare an array variable without creating the array object yet?
Aint[] arr;
Bint[] arr = new int[];
Cint arr = new int[5];
Dint arr[] = {1, 2, 3};
What happens if you try to access an element outside the array bounds?
AReturns null
BThrows ArrayIndexOutOfBoundsException
CCompiles but ignores the access
DReturns 0
Which syntax correctly creates an array of 4 strings?
AString[] names = {4};
BString names = new String[4];
CString[] names = new String[4];
DString names[] = new String;
Explain how to declare and initialize an integer array with 5 elements in Java.
Describe what happens if you try to use an array variable that has been declared but not initialized.