0

Hi!

Which way is the more effective? Is there any difference?
If I give value to a variable in the class

public class A{
int a = 3;
}

or if I give value to a variable in the constructor of the class

public class A{
int a;
public A(){a=3;}
}

Is there any difference if the variable is a primitive type or an object?

Thanks.

3
Contributors
2
Replies
3
Views
5 Years
Discussion Span
Last Post by ObSys
0

The Java Language Spec section 12,5 is the definitive refernce on instance initialisation, but briefly, in simple cases like that there's no difference.
In your first example the initialisation of the int happens after all superclass constructors have been called but before the remainder of the constructor executes. It's possible to construct examples where this makes a difference, eg where a is used in the initialisation of another variable, but these are pretty artificial.
You may also consider cases where there are multiple constructors - in which case the first code is safer.
The rules are the same for primitives and reference variables, but if you want to get tricky there are more ways to create problems when initialisation of a reference variable involves creating a new object whose initialisation interacts with this class. In practice such stuff is rare.

0

I've been taught that it's better practice to initialise the variables to default values in the constructor. I don't think it matters with reference to speed but it may cause trouble when others read your code.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.