STUDYECRAT Java : Arrays
60s
Java : Arrays
Prove your skills in this interactive quiz
Live Code
Run snippets directly
Timed
60s per question
Scored
Earn 3D badges
★ Java Arrays: Key Interview Points
1. Array Declaration & Initialization
int[] numbers = new int[5]; // Fixed-size array
String[] names = {"Alice", "Bob", "Charlie"}; // Inline initialization
// Arrays are zero-indexed in Java
String[] names = {"Alice", "Bob", "Charlie"}; // Inline initialization
// Arrays are zero-indexed in Java
- Tip: Use
Arrays.toString(arr)
to print arrays directly. - Real Use: Storing fixed-size data like days of the week or game levels.
2. Multidimensional Arrays
int[][] matrix = new int[3][3]; // 3x3 grid
matrix[0][0] = 1; // First row, first column
// Jagged arrays (rows with varying columns) are allowed
matrix[0][0] = 1; // First row, first column
// Jagged arrays (rows with varying columns) are allowed
- Tip: Use nested loops (
for-for
) to traverse 2D arrays. - Real Use: Representing grids (e.g., chessboard, spreadsheet data).
3. Array Copying & Cloning
int[] source = {1, 2, 3};
int[] dest = Arrays.copyOf(source, source.length); // Deep copy
// Modifying 'dest' won't affect 'source'
int[] dest = Arrays.copyOf(source, source.length); // Deep copy
// Modifying 'dest' won't affect 'source'
- Tip:
System.arraycopy()
is faster for large arrays. - Real Use: Backup/restore operations or thread-safe data handling.
4. Sorting & Searching
int[] nums = {5, 3, 9, 1};
Arrays.sort(nums); // Sorts in-place: [1, 3, 5, 9]
int index = Arrays.binarySearch(nums, 5); // Returns 2
// binarySearch requires a sorted array
Arrays.sort(nums); // Sorts in-place: [1, 3, 5, 9]
int index = Arrays.binarySearch(nums, 5); // Returns 2
// binarySearch requires a sorted array
- Tip: For custom sorting, use
Comparator
with object arrays. - Real Use: Leaderboard rankings or autocomplete suggestions.
5. Arrays vs. ArrayList
String[] arr = {"A", "B"}; // Fixed size
ArrayList<String> list = new ArrayList<>(Arrays.asList(arr)); // Dynamic size
list.add("C"); // Allowed
// Use Arrays for performance, ArrayList for flexibility
ArrayList<String> list = new ArrayList<>(Arrays.asList(arr)); // Dynamic size
list.add("C"); // Allowed
// Use Arrays for performance, ArrayList for flexibility
- Tip: Convert between them using
Arrays.asList()
andtoArray()
. - Real Use: Arrays for CPU-intensive tasks, ArrayList for dynamic data.
💡 Pro Interview Tip
When asked about arrays, always mention their fixed-size limitation and alternatives like ArrayList
. Interviewers often test your knowledge of trade-offs!