When we write Instance variables in the body of the class and given that the constructor initializes them, then why can we Initialize the variables directly and outside the constructor without going to the constructor? isn't that the constructor's duty?
class Sample{
LinkedList<String> string=new LinkedList<>();//Initializing in the body of the class
String value="Hi";//Initializing in the body of the class
public Sample(){
//shouldnt string and value initialize here?}
}
Field initialization occurs before the constructor body is executed. It's helpful in some occasions, for example if you have multiple constructors, and the field should have the same initial value. In your example, you always want to start with an empty list, so you avoid null pointer exceptions. This is indeed a good practice for collections in general.