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.

Dani AI

Generated

Short answer: for a simple literal or trivial default there is no runtime difference between assigning at the field declaration or in the constructor; semantics for primitives and references are the same. As pointed out, the important thing is initialization order (superclass construction runs before instance initializers and constructor bodies), and as noted, constructor initialization can be clearer to readers when logic is involved.

A concrete pitfall where order matters (new example):

class Base {
    Base() { System.out.println("Base ctor: getX()=" + getX()); }
    int getX() { return 0; }
}

class Sub extends Base {
    int x = 42;            // instance initializer runs AFTER Base ctor
    @Override
    int getX() { return x; }
}

public class Demo { public static void main(String[] args) { new Sub(); } }

This prints Base ctor: getX()=0 because Sub.x is not yet initialized when Base constructor calls the overridden method. That illustrates why putting nontrivial logic into field initializers can be surprising.

Practical guidance:

  • Use simple inline initializers for constants and obvious defaults (less boilerplate).
  • Use constructors (or factory methods) when initialization requires logic, dependency injection, or exception handling.
  • Avoid calling overridable methods from constructors and avoid letting this escape from initializers (starting threads, registering in global registries).
  • Prefer final fields where possible (initializer or all constructors must set them).
  • Performance differences are negligible; prefer clarity and correctness over micro-optimizing where the assignment happens.

For the formal rules and exact order of execution see the Java Language Specification, Java SE 17, §12.5 (Instance Initialization): https://docs.oracle.com/javase/specs/jls/se17/html/jls-12.html#jls-12.5.

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.