• Post Reply Bookmark Topic Watch Topic
  • New Topic

Grammar question relating to Constructor  RSS feed

 
Benedict Wong
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello everyone, below is a code snippet in which I have a grammatical question.



On line23, I understand that in order to create a physical copy of FailSoftArray class, the new keyword must be used.

However, why is there a need for the new keyword to be used in a Constructor on line16?

Thank you. 
 
Stephan van Hulst
Saloon Keeper
Posts: 7969
143
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to CodeRanch, Benedict!

This is not a matter of grammar. This is a matter of logic. The new keyword reserves a block of memory so that an object can be stored there. When you execute FailSoftArray fs = new FailSoftArray(5, -1), you reserve memory for a new object of type FailSoftArray. Among other things, this block of memory will hold the values of the a, errval and length fields. It's very important to realize that a has type int[], and arrays are reference types. The block of memory for the FailSoftArray object does not contain space for the array, but rather a reference to an array somewhere else in memory. The block of memory for the array must also still be reserved. To reserve a block of memory for the int array, you need to call new int[size]. That will reserve memory for the array, and return a reference to that block of memory, which is then stored in the a field.
 
Benedict Wong
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Stephan!

That is why for primitive types, there's no need for new right? So as long as it is a reference type, new must be used whether in a Constructor or elsewhere.

Thanks for clearing my mental block!
 
Stephan van Hulst
Saloon Keeper
Posts: 7969
143
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes. There is only one exception: String is a reference type, but you can get an instance of it by using a string literal. The space for string literals is already reserved when the application starts running, and executing a statement that contains a string literal will not allocate extra memory for the string.
 
Diego Nobrega
Greenhorn
Posts: 3
Java Netbeans IDE
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
every array is an object, not a simple primitive type. If you press ctrl + space you will see all the methods from Object class (equals(), clone(), etc - because every class in java inherits from Object). Because of that, the 'new' is necessary.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!