Java arrays and how they exist in memory.

Mike Sun
3 min readApr 7, 2019

--

Arrays can be very abstract when you first start programming. Even if you know how to use them, you may fumble on the fundamental structure of them. This is an algo clarification to let you have a solid understanding of how arrays interact with memory.

//case 1:
int [] intArr;

The code above only creates a reference in the memory, not object. You need to be careful if you forget to assign a value to it and use it like an object, you will run into errors when compiling. Hence for beginners, I would usually just declare the values on the go and not lump everything at the top. I would leave that to the refactoring step.

//case 2:
int[] intArr1 = new int[3];
//The new keyword creates an object

In this case, a reference called intArr1 is created and followed by an int[] object of 4 slots. Hence, there is 1 object created. Refer to diagram below:

//case3:
int[][] intArr2D = new int[2][2];

In this case, we created a 2D array, meaning array in a array. You can think of the first [] containing the second [] in int[][]. i.e.

Hence, there is 3 objects created from the statement.

However, there is another possibility of 2D array:

int[][] intArr2DSpecial = new int[2][]; 

This means that after creating the first object, it only references null. You need to create arrays for the second dimension for them to exist in objects. Hence, you can have 1 object on initiate, or a maximum of 3 object when fully declared.

Next up, let’s examine point arrays. It is often a confusing topic and testers like to exploit that. Point arrays is part of the awt API, which was originally used to design the x,y coordinates of a UI.

//case 4:
import java.awt.*;
.
.
Point[] pointArr = new Point[2];

Guess how many objects are created from this statement. Well, it depends. Minimally, you can have 1 object which is reference by pointArr. However, if you declare points inside of that object, each pair of (x,y) cord point is actually an individual object. Hence maximum of 3 points would be declared when the array is fully utilized.

Hope you like the above explanation. Happy coding!

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Mike Sun
Mike Sun

Written by Mike Sun

Random tech blog for my fellow peers troubleshooting stuff. Things I wished I knew without needing to spend hours/days digging...

No responses yet

Write a response