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:
I'm not considering the case where the number of element can vary. It will ALWAYS be 10
- is it really better ?
Not really, IMO.
- is there some good reasons : convention ? style ?
There may be valid reasons for choosing one way over the other is when you have multiple constructors, or when the initial values depend on constructor arguments; e.g.
private int[] tab;
public Example(int size) {
tab = new int[size];
for (int i = 0; i < size; i++)
tab[i] = (int) (Math.random() * 100);
}
or
private int[] tab = new int[10];
public Example(int initial) {
for (int i = 0; i < 10; i++)
tab[i] = initial;
}
public Example() {
for (int i = 0; i < 10; i++)
tab[i] = (int) (Math.random() * 100);
}
Apart from that (and in your example) there are no general rules about this. It's a matter of personal taste.
- does it change anything like less/more memory used ?
In your example it will make no difference. In general, there might be a tiny difference in the code size or performance, but it is not worth worrying about.
In short, I don't think your suggestion to your friend has a rational basis.
The way I learn it, you can initialize variables with basic types (int, double...) but for arrays you should do it in the constructor.
You should unlearn that ... or at least recognize that it is just a personal preference.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With