Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Difference between String creation in class and in constructor

Status
Not open for further replies.

dvsmas

Programmer
Jun 20, 2001
16
0
0
US
Can anyone please tell me if there is any difference in the following ways of a String creation.

class A{
String X;
A(){ X = new String("Hello");
}
}

class A{
String X=new String("Hello");
}

Which option is better?
Thanks in advance
 
Generally as a rule if both situations work identically, then the shorter code is more efficient. I guess that makes it "better"

-kaht
 
Only the sequences are different. First the body is executed,then your constructor runs when you create an instance of your class A.

Salih Sipahi
Software Engineer.
City of Istanbul Turkey
s.sipahi@sahinlerholding.com.tr
turkey_clr.gif
 
When you would have more than 1 constructor, there can be a difference, depending on which constructor you call.

There would also be a difference if your class would extend another class and you wanted to call super(...) [as it must be the first statement in the constructor].
 
Yes.Hologram is extremely correct.In fact I was looking for a good example to state this but could not find a good example for that.[smile]

Salih Sipahi
Software Engineer.
City of Istanbul Turkey
s.sipahi@sahinlerholding.com.tr
turkey_clr.gif
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top