0

I have written a class like this -

class foo
    {
       int t, b;
       foo(int a, int b)
          {
              this.a = a; this.b = b
          }
       foo(){}
    }

now I want to create an array of objects. what is the difference between this two-line-

foo[] ab = new foo[100];
foo ab[100] = new foo[100];
1
  • And unrelated: class names go UpperCase in Java. Also note that you should better follow consistent bracing strategies. Commented Nov 5, 2019 at 9:50

2 Answers 2

5

The difference is that the second line will not even compile, as that is invalid syntax in Java. So besides that there is "sense" in repeating that 100 information, that part only belongs on the right hand side of the statement.

On the left hand side, you have the type. The type is "array of foo". The number of elements within an actual instance of that type is "runtime only". It is not reflected in the type.

Sign up to request clarification or add additional context in comments.

Comments

0

foo[] ab = new foo[100];

Above line of code will create a reference variable that hold the reference to object containing declaration of 100 variables of type foo (Class name though should be in Initial Caps)

foo ab[100] = new foo[100]; This line of code will throw compilation error as you are declaring an array variable with size.

You can replace this line with creating a new object and asisgning to variable per index. ab[0] = new foo(1,2); This way you can create the object and assign to your array indexes.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.