Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convention in java - "new" outside of constructor / method?

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?
  • Are 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

like image 507
Loïc Février Avatar asked Sep 30 '10 11:09

Loïc Février


1 Answers

  • 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.

like image 53
Stephen C Avatar answered Oct 16 '22 22:10

Stephen C