Working the Magic: Interview Questions

Question 1: What’s the value of “nums” after executing the following code?

int[] nums = new int[5];
for (int i = 0; i <= nums.length; i++){
     nums[i] = i;
}

Turns out this is a trick question. Arrays in Java start counting from zero so if you try to access the index of your Array’s length, you’ll try to access an index the Array doesn’t have crashing Java.

int[] nums = new int[5];
//A Simple fix is to remove the = from your operation
for (int i = 0; i < nums.length; i++){ 
     nums[i] = i;
}

Question 2: To be Added

Leave a comment

Create your own website, free on WordPress.com.Create your own website.
Start free