0

Is it legal to declare a variable in the constructor in java? example.

Time(){
        long timeMill = System.currentTimeMillis();
        int second = (int) (timeMill / 1000) ;
        this.second = second % 60;
        int minute = (int) (timeMill / 60);
        this.minute = minute % 60;
        int hour = (int) (timeMill / 360);
        this.hour = hour % 24;

    }
Jamuhuri
  • 19
  • 3
  • Yes, it is. If it compiles, it's allowed. And that does compile. – blalasaadri Mar 27 '15 at 13:36
  • Check here the answer http://stackoverflow.com/questions/3918578/should-i-initialize-variable-within-constructor-or-outside-constructor – knowledge flow Mar 27 '15 at 13:37
  • yes. It compiles fine but scope of these variable is limited to constructor then. So, it is always advisable to declare variables outside of constructor and initializing them inside constructor. check [this](http://stackoverflow.com/questions/18649126/can-you-declare-an-instance-variable-as-a-parameter-in-a-constructor) – codiacTushki Mar 27 '15 at 13:42

1 Answers1

1

Yes.

There's nothing wrong with declaring a variable constructor-scoped, just as there's nothing wrong with scoping a variable to a method in general.

It really depends on the context.

Fine print:

Careful about variables declared within constructors or methods, they have no default values and must be assigned before being referenced, otherwise your code will not compile.

Mena
  • 47,782
  • 11
  • 87
  • 106