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.

Recommended Answers

All 2 Replies

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.

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.