0
0
Javaprogramming~15 mins

Common array operations in Java - Cheat Sheet & Quick Revision

Choose your learning style8 modes available
overviewRecall & Review
beginner
What is the syntax to declare and initialize an array of integers with values 1, 2, 3 in Java?
You can declare and initialize an integer array like this:
int[] numbers = {1, 2, 3};
touch_appClick to reveal answer
beginner
How do you find the length of an array named arr in Java?
Use arr.length to get the number of elements in the array.
Example:
int size = arr.length;
touch_appClick to reveal answer
beginner
How can you loop through all elements of an array arr using a for-each loop?
Use the for-each loop syntax:
for (int element : arr) {
    // use element
}

This goes through each item in arr one by one.
touch_appClick to reveal answer
intermediate
How do you copy an array source to a new array copy in Java?
You can use Arrays.copyOf:
int[] copy = Arrays.copyOf(source, source.length);

This creates a new array with the same elements.
touch_appClick to reveal answer
beginner
How do you sort an array arr of integers in Java?
Use Arrays.sort(arr); to sort the array in ascending order.
Example:
Arrays.sort(arr);
touch_appClick to reveal answer
Which of the following is the correct way to declare an array of strings named names?
AString[] names = new String;
BString[] names;
CString names = new String[];
DString names[] = ();
How do you access the third element of an array arr?
Aarr.get(3)
Barr[3]
Carr[2]
Darr(2)
What does arr.length return?
AThe number of elements in the array
BThe last element of the array
CThe size of the array in bytes
DThe index of the last element
Which method sorts an array arr in Java?
AArrays.sort(arr);
Barr.sort();
CCollections.sort(arr);
Darr.sorted();
How do you loop through all elements of an array arr using a for-each loop?
Afor each (int x in arr) { }
Bfor (int i = 0; i < arr.length; i++) { }
Cfor (int i = 1; i <= arr.length; i++) { }
Dfor (int x : arr) { }
Explain how to declare, initialize, and access elements in a Java array.
Describe how to loop through all elements of an array and how to sort an array in Java.