Keyword "new" and arrays - clarification

Hello Forum,

This question is about explaining arrays simply to beginners…please correct or clarify, thank you :slight_smile:

When an array is declared and initialized at the same time like this:

int mySet[] = {15,75,123,105,165,290};

then key word “new” is unnecessary. However, when an array is declared but not initialized yet then the key word “new” is required like this:

int mySet[] = new int[6];

So, is it fair to say,

"the keyword “new” is only required when using an array[] that is declared and but not initialized."

2 Likes

Placing the [] next to the datatype is more accepted by Java’s conventions:
int[] mySet = { 15, 75, 123, 105, 165, 290 };

Keyword new is still required when initialization happens after the variable is already declared:

int[] mySet;
mySet = new int[] { 15, 75, 123, 105, 165, 290 };
exit();
1 Like

" Placing the [] next to the datatype is more accepted by Java’s conventions:
int[] mySet = { 15, 75, 123, 105, 165, 290 };"

Does this mean that this array is written incorrectly even though it works in Processing?

int mySet[] = {15,75,123,105,165,290}; 

void setup (){
  size (300,300);

}

void draw () {
  background (208,236,237);
  noStroke();

   for (int i = 0; i < 6; i++){    
      fill (100,0,100,100);
      ellipse ((mySet[i]),150, 50, 200); //draw ellipses int from the array index       
     }
    }

Nope! Both the [] placement & the {} initialization block w/o keyword new were introduced on Java in order to attract the C/C++ folks. :smirk:

So, then “new” is only required when using an array that is declared and initialized in separate lines?

Also when it’s initialized by length w/o its content: int mySet[] = new int[6];

3 Likes

As always - thank you!

The nice thing about teaching this format:

int[] mySet = new int[6];
mySet = new int[] {6, 7, 8, 9, 10, 11};
int[] mySet2 = new int[] {0, 1, 2, 3, 4, 5};

…is that the type, int, is used consistently everywhere. Simple, easier to remember, forms good habits.

Then, one an additional rule:

You may optionally drop the type when initializing during declaration:

int[] mySet3 = {0, 1, 2, 3, 4, 5};
4 Likes

Hi Jeremy!

Those are helpful points! I like to keep things consistent. Thank you!