I do not understand "new" operator

Good morning,

I am taking the first course in Java. many times i see the “new” operator being implemented in different lines of code. I saw it first during the the Array session, as in:

public static void main(String[] args) {
int[] numbers = new int [5];

I do not understand its use. We are already assigning “numbers” in

 int[] numbers = 

and the [] specifies it will be an array. However why the “new” afterwards? why not

public static void main(String[] args) {
int[] numbers = int [5];


Thank you

Their is a difference between declaration and initialization. When we write:

int[] numbers

We are actually declaring that the variable numbers will contain an array of integers. At this moment only a variable is declared and no space is allocated. And when we write:

new int[5]

We are initializing the array and telling the program to create an integer array of 5 elements. At this moment the space will be allocated for array.

Moreover you can search for declaration and initialization for more details.


Thank you! I understand it better now. I will search for both declaration and initialization to understand more.

1 Like

new is how you ask the computer “I need memory space.”

int a = 2: The computer knows an int is 4 bytes. So it can assume you just need 4 bytes and new isn’t needed.
Technically you can be like: int a = new Integer(2); but that’s not needed.

int[] array = int[23]: The computer knows you’re making an array, but it doesn’t know what int[23] means. It doesn’t know what to do with the 23.

int[] array = new int[23]: The computer now knows from the new keyword that you want to allocate space for an integer array of 23 elements.

So whenever you use new, you’re asking the computer to give you space for whatever comes after the keyword.

If you got to the part about contructors, then you know that new will also call the contructor function.

Hope that makes sense! :slight_smile:


Another great explanation! I understand it much better now, thank you.

Using word new what you do really you call a constructor. and as you can notice, you should in particular cases use some values in parenthesis. same for a method when you call them you should or sometimes should not pass values. to determine you call constructor you can tell by you should use a capital letter in first. but let this description stop now. Just remember this.

1 Like

Thank you! Now that I got to the meats and potatoes of class and objects is where I am having a little difficulty in getting it. But I’m practicing and eventually it’ll become second nature.