Search code examples
javaarraysobjectsyntaxnew-operator

Can we create an object without parentheses?


According to this site the syntax for creating a Java object is:

<JavaType> <variable> = new <JavaObject>();

Though you don't use any parantheses when creating an Array object and instead type brackets which contains the length of each dimension.

Example:

String[][] stringMatrix = new String[5][10];

What I am wondering is if this syntax is specifically and only for creating an Array object or I can make a custom class whose objects are created in a different way then usual

new <JavaObject>();

statement.


Solution

  • new keyword is used to allocate memory for the specific type, which is followed by new keyword.

    MyClass obj = new MyClass();
    

    Above line will create an object (allocate memory) for MyClass and initialize member variable by invoking default constructor.

    But, below line of code will only allocate memory and initialize each element of array with default value null.

    MyClass[][] objMatrix = new MyClass[5][10];
    

    So, we are just declaring an array of size 5x10(allocating memory), but each element in array need some object reference (since, currently they have null reference). So, for that reason, you need to initialize each objMatrix array element by creating object of MyClass and assigning them to each element.

    objMatrix[0][0] = new MyClass();