0

1st program without constructor:

public class Sample1 {
    int a=9;
    public static void main(String args[]) {
        Sample1 obj = new Sample1();  // I know this is a default constructor
        System.out.println(obj.a);
    }
}

Output: 9

2nd program with constructor:

public class Sample1 {
    int a;
    Sample1(){
        a=9;
    }
    public static void main(String args[]) {
        Sample1 obj = new Sample1();
        System.out.println(obj.a);
    }
}

Output: 9

If both the things give same output then what's the use of taking the pain to declare constructor?

2

2 Answers 2

1

For this usecase, there really isn't much of a difference. Constructors are usually useful in two scenarios:

  1. When you want to take arguments instead of initializing the members to hard-coded values.
  2. If you have some logic you want to run when the instance is constructed.
1

This is closely related, although it refers mostly to static: Difference between the static initializer block and regular static initialization

So in a few bullet points:

  • Essentially, for you, they're equal
  • variables get initialized first, then the CTOR gets run (but be aware, with inheritance some differences may arise)
  • in both you can assign final variables
  • inside the CTOR, you can process parameters given
  • initiailizing inside the CTOR has the big advantage that you can handle exceptions
  • in variable initialization, you cannot call any method that throws a Checked Exception (derived fom Exception but not from RuntimeException
  • in variable initialization, you cannot control what happens when the variable initialization throws and Unchecked Exception (Throwable, Error, RuntimeException)
  • inside the CTOR you can also do CTOR Chaining or reference super class CTORs

Not the answer you're looking for? Browse other questions tagged or ask your own question.