0

Sorry, if this question is trivial...

There are two ways of initializing fields

For example:

The first way is:

Public class A{
    int a;
    A(){
        a = 5;
    }
}

The second way is:

Public class A{
    int a = 5;
    A(){
    }
}

Which way is better? Why or why not?

CSnerd
  • 2,129
  • 8
  • 22
  • 45
  • Whether you initialize or not primitive int is always '0'. Coming to declaration if you are sticking with a constant default value initializing during the declaration is preferred. If you want the value to be passed while initializing the object then use the constructor. – Puru-- Apr 06 '14 at 00:48
  • Instance variable are by default initialized. its zero for int. – Braj Apr 06 '14 at 00:49
  • @Braj what if the a = 5 at the beginning? – CSnerd Apr 06 '14 at 00:52
  • My mistake, I looked at the answer first. – Braj Apr 06 '14 at 00:53

2 Answers2

0

It really depends on what you want.

If you only have one constructor, then it doesn't matter, because either way the value will start a 0. If you have more than one constructor, it still doesn't really matter, but it might be better to do it the following way:

int a;

A() {
    a = 0;
}

A(int newA) {
    a = newA;
}

When I personally develop, I will assign the value at the top in the following cases only:

  1. The variable I am assigning is a constants.
  2. The variable has some sort of default value, that can and usually will change.
Tamby Kojak
  • 2,129
  • 1
  • 14
  • 25
0

Both ways are correct.

Prefer second way if you don't want to repeat the code as shown in below code:

public class A{
    int a;
    A(){
       a=5;
    }
    A(String s){
       a=5;
    }
    A(Long l){
       a=5;
    }
 }

 public class A{
    int a = 5;
    A(){
    }
    A(String s){
    }
    A(Long l){
    }
 }

In the second case you don't have to initialize it for all the overloaded constructor.

Now it depends on your choice.

Braj
  • 46,415
  • 5
  • 60
  • 76
  • I like this reason: "Prefer second way if you don't want to repeat the code as shown in below code" – CSnerd Apr 06 '14 at 01:03
  • Instead of A(String a), i think it should be A(int a) { this.a = a; }. Please check – bgth Apr 06 '14 at 03:35