File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes Best way of intialization Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Best way of intialization" Watch "Best way of intialization" New topic

Best way of intialization

tushar jayawant

Joined: Aug 20, 2003
Posts: 19
Hi to all

Which is best way of intialization the Instance Variable

1) class A {
B b= new B();
C c = new C();



class A {
B b ;
C c ;


b= new B();
c = new C();



Thankx in Advance
Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24199

If you initialize member variables in the body of the class, the compiler actually puts a copy of that initialization code at the beginning of each constructor, so in terms of efficiency or anything like that, they're really equivalent. The only thing that matters, then, is maintainability and readability.

The rule I follow, loosely, is that primitive types can be initialized to constants in the class body, while objects are created in a constructor. The main reason for this is consistency; some objects have to be created in a constructor (or in an initializer block) because their constructors throw exceptions -- so to be consistent, I do them all that way.

Other people may have other rules.

[Jess in Action][AskingGoodQuestions]
tushar jayawant

Joined: Aug 20, 2003
Posts: 19

Thankx for the Reply......

Frank Harper

Joined: May 27, 2004
Posts: 5
The advantage of initializing member variables in the body of the class is that you only have to do it once, instead of for each constructor.

This eliminates potential bugs where someone forgets to initialize a member in in a certain constructor.
I agree. Here's the link:
subject: Best way of intialization
It's not a secret anymore!