Hello.
Simple question. A friend of mind wrote code similar to this one (which is just to explain you my question, it's not useful at all....)
class Example{
private int[] tab = new int[10];
public Example() {
for(int i = 0 ; i < 10 ; i++)
tab[i] = (int)(Math.random()*100);
for(int i = 0 ; i < 10 ; i++)
System.out.println(tab[i]);
}
public static void main(String[] arg) {
Example ex = new Example();
}
}
I told him he should put the new
inside the constructor
class Example{
private int[] tab;
public Example() {
tab = new int[10];
...
}
When he ask me why, I din't know what to answer : I didn't have a definite argument other than "it's better this way". The way I learn it, you can initialize variables with basic types (int, double...) but for arrays you should do it in the constructor.
So :
- is it really better ?
- is there some good reasons : convention ? style ?
- does it change anything like less/more memory used ?
I'm not considering the case where the number of element can vary. It will ALWAYS be 10