hailey_lp
hailey_lp

Reputation: 21

adding size to private array - java

I'm very new to Java programming and wanted to try my hand at a little bit outside of my classes. I've created a class that will manipulate arrays, so I set up a private array with no size allocated to it. In a public constructor, how do I set the size of this array?

Upvotes: 1

Views: 2600

Answers (2)

ajax992
ajax992

Reputation: 996

public ClassName()
{
  arr = new int[10];
}

Remember that the Constructor is the method called when an object is instantiated. The Constructor must be a method with no return type and the same name as the class. You could even take in parameters if you'd like to(say a size variable), then create a new array based on the size.

For instance, you could do this:

public ClassName(int size)
{
   arr = new int[size];
}

Now when in your tester class, you could create a new object using that constructor.

ClassName c = new ClassName(5);

Which creates a new object with an array of size 5 as a class variable. Hope this helped!

Edit: I should add; if you do not specify a constructor, Java will do it for you, but it will do nothing.

Upvotes: 2

itay
itay

Reputation: 357

Just like in must of the languages.

example:

anArray = new int[10]; //10 - array size, int is the array type

read about JAVA Arrays

Upvotes: 0

Related Questions