Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (2.6k points)

When I use Java based on my C++ knowledge, I love to initialize variable using the following way.

public class ME {

    private int i;

    public ME() {

         this.i = 100;

    }

}

After some time, I change the habit to

public class ME {

    private int i = 100;

    public ME() {

    }

}

I came across others source code, some are using 1st convention, others are using 2nd convention.

May I know which convention do you all recommend, and why?

1 Answer

0 votes
by (46k points)

I obtain the second style (code + initialization in one go) superior. Reasons:

  • It performs it clear at a glimpse of how the variable is initialized. Typically, when reading a program and developing across a variable, you'll first go to its information (often spontaneous in IDEs). With style 2, you recognize the default value immediately. With style 1, you need to attend at the constructor as well.
  • If you hold more than one constructor, you don't have to renew the initializations (and you cannot ignore them).

Of course, if the initialization value is modified in various constructors (or even calculated in the constructor), you need to do it in the constructor.

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...