Java Notes
Comprehensive collection of Java array interview questions and answers covering conceptual, coding, and tricky questions asked in TCS, Infosys, Wipro, Amazon, and Google interviews.
This comprehensive collection covers conceptual, coding, and tricky output-based questions frequently asked in Java interviews at all levels — from freshers to experienced professionals.
Section 1: Conceptual Questions
Q1: What is an array in Java?
Answer: An array in Java is a fixed-size, contiguous data structure that stores multiple elements of the same data type. It is an object that resides in heap memory, accessed via a reference variable. Arrays provide O(1) random access using integer indices starting from 0.
Key characteristics:
- Fixed size (cannot grow/shrink after creation)
- Homogeneous (same data type for all elements)
- Zero-indexed (first element at index 0)
- Object in Java (inherits from java.lang.Object)
- Contiguous memory allocation for elements
Q2: Where are arrays stored in memory?
Answer: Arrays in Java have two parts:
- Reference variable — stored in stack memory (if local) or heap (if instance/static field)
- Actual array object — always stored in heap memory
When you write int[] arr = new int[5]:
arr(reference) goes on stack — takes 4/8 bytes (32-bit/64-bit JVM)- The array object (5 ints + header) goes on heap — takes 20+ bytes (5×4 + object header)
Q3: What is the difference between length, length(), and size()?
Answer:
| Property/Method | Used With | Example |
|---|---|---|
length | Arrays (property, no parentheses) | arr.length |
length() | String (method) | str.length() |
size() | Collections (method) | list.size() |
int[] arr = {1, 2, 3};
String str = "Hello";
ArrayList<Integer> list = new ArrayList<>();
System.out.println(arr.length); // 3
System.out.println(str.length()); // 5
System.out.println(list.size()); // 0Q4: What are default values of array elements?
Answer:
| Type | Default |
|---|---|
| byte, short, int, long | 0 |
| float, double | 0.0 |
| boolean | false |
| char | '\u0000' |
| Object references | null |
These defaults are assigned automatically by JVM when using new. Array literals don't need defaults since values are explicitly provided.
Q5: Can we change the size of an array after creation?
Answer: No. Arrays are fixed-size in Java. Once created with new int[5], the size is permanently 5. To "resize":
- Create a new array of desired size
- Copy elements from old to new array
- Assign the new array to the variable
int[] arr = {1, 2, 3};
arr = Arrays.copyOf(arr, 6); // Creates new array, copies, and reassigns
// Original 3-element array becomes eligible for garbage collectionUse ArrayList if dynamic sizing is needed.
Q6: What is the difference between int[] a and int a[]?
Answer: Both are valid declarations for an integer array. The difference matters when declaring multiple variables:
int[] a, b; // Both a AND b are arrays
int a[], b; // Only a is an array, b is a regular int!The first style (int[] a) is preferred in Java because the type (int[]) is clearly separated from the variable name.
Q7: Can we create an array of size 0?
Answer: Yes! new int[0] creates a valid array object with length 0. It's useful as:
- Return value when no results are found (instead of null)
- Empty varargs parameter
- Placeholder that avoids NullPointerException
Q8: What is an anonymous array in Java?
Answer: An array created without being assigned to a named variable, typically passed directly to a method:
// Anonymous array
printArray(new int[]{1, 2, 3, 4, 5});
// You cannot use shorthand syntax for anonymous arrays:
// printArray({1, 2, 3}); // COMPILE ERRORQ9: Explain array cloning in Java.
Answer: clone() creates a shallow copy of an array:
- For primitive arrays — it effectively creates a deep copy (values are copied)
- For object arrays — only references are copied; objects themselves are shared
Q10: What is ArrayStoreException?
Answer: Thrown when you try to store an object of incompatible type in an object array:
This happens because the actual array type is String[], even though the reference type is Object[].
Section 2: Coding Questions with Solutions
Q11: Write a program to find the third largest element without sorting.
public class ThirdLargest {
public static void main(String[] args) {
int[] arr = {12, 13, 1, 10, 34, 1, 50};
int first = Integer.MIN_VALUE;
int second = Integer.MIN_VALUE;
int third = Integer.MIN_VALUE;
for (int num : arr) {
if (num > first) {
third = second;
second = first;
first = num;
} else if (num > second && num != first) {
third = second;
second = num;
} else if (num > third && num != second && num != first) {
third = num;
}
}
System.out.println("Array: " + java.util.Arrays.toString(arr));
System.out.println("Third largest: " + third);
}
}Array: [12, 13, 1, 10, 34, 1, 50] Third largest: 13
Q12: Find the element that appears odd number of times.
public class OddOccurrence {
public static void main(String[] args) {
int[] arr = {2, 3, 5, 4, 5, 2, 4, 3, 5, 2, 4, 4, 2};
int result = 0;
for (int num : arr) {
result ^= num; // XOR cancels out pairs
}
System.out.println("Array: " + java.util.Arrays.toString(arr));
System.out.println("Element appearing odd times: " + result);
}
}Array: [2, 3, 5, 4, 5, 2, 4, 3, 5, 2, 4, 4, 2] Element appearing odd times: 5
Explanation: XOR of a number with itself is 0. All numbers appearing even times cancel out, leaving only the odd-occurring number.
Q13: Separate even and odd numbers in an array.
Original: [12, 34, 45, 9, 8, 90, 3, 7, 56] Separated: [12, 34, 56, 90, 8, 9, 3, 7, 45]
Q14: Find the subarray with given sum (non-negative numbers).
Array: [1, 4, 20, 3, 10, 5] Subarray with sum 33 found: Indices 2 to 4 Elements: 20 3 10
Section 3: Predict the Output Questions
Q15: What is the output?
99
Explanation: b = a copies the reference, not the array. Both a and b point to the same array object. Changing b[2] changes the shared array.
Q16: What is the output?
0 [I@1b6d3586
Explanation: arr[0] prints default value 0. arr prints the default toString() of the array object: [I means 1D int array, @ followed by hashcode in hex.
Q17: What is the output?
public class OutputQuestion3 {
static void modify(int[] arr) {
arr = new int[]{10, 20, 30};
}
public static void main(String[] args) {
int[] arr = {1, 2, 3};
modify(arr);
System.out.println(java.util.Arrays.toString(arr));
}
}[1, 2, 3]
Explanation: Inside modify(), arr = new int[]{10, 20, 30} reassigns the LOCAL parameter to a new array. The original reference in main() is unaffected. If the method had done arr[0] = 99, the original WOULD be modified.
Q18: What is the output?
public class OutputQuestion4 {
public static void main(String[] args) {
int[] a = {1, 2, 3};
int[] b = {1, 2, 3};
System.out.println(a == b);
System.out.println(a.equals(b));
System.out.println(java.util.Arrays.equals(a, b));
}
}false false true
Explanation:
a == b: Compares references — different objects, so falsea.equals(b): Arrays don't override Object.equals(), so it compares references — falseArrays.equals(a, b): Compares content element by element — true
Section 4: Tricky and Advanced Questions
Q19: What happens with negative array size?
The compiler cannot detect this because size could be a variable computed at runtime.
Q20: Can an array hold different types?
Q21: Maximum array size in Java?
Answer: Theoretically Integer.MAX_VALUE (2,147,483,647), but practically limited by:
- Available heap memory (
-Xmxsetting) - JVM implementation (many cap at
Integer.MAX_VALUE - 5orInteger.MAX_VALUE - 8) - Attempting too large causes
OutOfMemoryError
Q22: How to convert array to ArrayList and vice versa?
ArrayList: [A, B, C] Array: [A, B, C]
Q23: Why does Arrays.asList() return a fixed-size list?
Answer: Arrays.asList() returns a java.util.Arrays$ArrayList (inner class), NOT java.util.ArrayList. This wrapper is backed by the original array, so:
- You CAN
set()elements (modifies the original array too) - You CANNOT
add()orremove()— throwsUnsupportedOperationException
To get a modifiable list: new ArrayList<>(Arrays.asList(arr))
Q24: Explain covariance in arrays.
Arrays are covariant (allows SubType[] where SuperType[] is expected) which can lead to runtime errors. Generics are invariant, catching errors at compile time.
Q25: What is the time and space complexity of common array operations?
| Operation | Time Complexity | Notes |
|---|---|---|
| Access by index | O(1) | Direct address calculation |
| Search (unsorted) | O(n) | Linear search |
| Search (sorted) | O(log n) | Binary search |
| Insert at end | O(1) | If space available |
| Insert at position | O(n) | Shift elements |
| Delete at position | O(n) | Shift elements |
| Sort | O(n log n) | Arrays.sort() |
| Copy | O(n) | Must visit each element |
Common Mistakes
- Using == to compare arrays — compares references, not content
- Forgetting that clone() is shallow for object arrays
- Not checking for null before accessing array properties
- ArrayStoreException when using covariant arrays
- Off-by-one errors — valid indices are 0 to length-1
- Confusing fixed-size list from
Arrays.asList()with regular ArrayList - Integer overflow when computing mid in binary search: use
low + (high - low) / 2 - Modifying array passed to method without documenting the side effect
Best Practices
- Use Arrays.equals() for comparison, Arrays.deepEquals() for multi-dimensional
- Prefer ArrayList when size is dynamic
- Use enhanced for loop when index isn't needed
- Document array semantics — what each index represents
- Return empty arrays instead of null from methods
- Use Arrays.copyOf() instead of manual copy loops
- Validate inputs — check for null, empty, and bounds
- Consider immutability — use
Collections.unmodifiableList()after wrapping - Profile before optimizing — premature optimization is the root of all evil
- Know your algorithm complexities — choose the right approach for the data size
Interview Questions (Quick-Fire Round)
Q1: Is array a primitive or reference type? → Reference type (object)
Q2: Can array size be a variable? → Yes, any non-negative int expression
Q3: What class do arrays extend? → java.lang.Object
Q4: Is length a method or field? → Field (public final int)
Q5: Can you serialize arrays? → Yes, all arrays implement Serializable
Q6: Thread-safe? → No, arrays need external synchronization
Q7: Can arrays implement interfaces? → Yes, they implement Cloneable and Serializable
Q8: Fastest way to copy? → System.arraycopy() (native method)
Q9: How to sort descending? → Use Integer[] with Arrays.sort(arr, Collections.reverseOrder())
Q10: Null vs empty array? → Null has no object; empty (new int[0]) is a valid object with length 0
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Array Interview Questions.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Java Master Course topic.
Search Terms
java-master-course, java master course, java, master, course, fundamentals, arrays, interview
Related Java Master Course Topics