Java Interview Question - Interval Aggregation Service Bug
Why your 2D array is actually just vibes and nulls
Context
You are working on a backend service that processes user activity windows.
Each user has multiple active sessions represented as intervals:
[startTime, endTime]The service converts these into a 2D array for downstream analytics.
The service is failing intermittently with:
NullPointerException📢 Get actionable Java and Spring Boot insights every week, including practical code tips and real-world, use-case-based interview questions, to help you level up your backend skills—join 7300+ subscribers for hand-crafted, no-fluff content.
First 100 paid subscribers will get the annual membership at $50/year forever that is ~ $4/mo ( 89 already converted to paid, 11 sport remaining)
Testimonials
Identify the root cause of the failure
The NullPointerException happens because the code assumes that each row inside the 2D array is already allocated, but it is not.
int[][] result = new int[sessions.size()][];This only creates the outer array, not the inner arrays.
So at this point:
result
- null
- null
- nullEach result[i] is null.
when we do
result[i][0] = session[0];
result[i][1] = session[1];This tries to access:
(null)[0]which throws NullPointerException
Propose the fix for the bug
The root issue is that only the outer array is created, not the inner arrays. So we must ensure each row is initialized before accessing it.
Fix 1: initialize each row
Each result[i] now points to a real int[] before assignment.
Fix 2: Use rectangular allocation
If the structure is always [start, end], then:
No manual row allocation needed.
Fix 3: Use direct assignment
Since sessions.get(i) is already int[]:
int[][] result = sessions.toArray(new int[0][]);This is a trick where we are saying “Please allocate the correct sized array for me“
if (a.length < size)
create new array of correct sizeThats all for this question! Thanks for reading this far. If you liked it please share with your network.
Happy Coding 🚀
Suraj
Subscribe | Sponsor us | LinkedIn | Twitter






