• Post Reply Bookmark Topic Watch Topic
  • New Topic

Which is a better approach ??  RSS feed

 
Sajee Joseph
Ranch Hand
Posts: 200
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello all,
Here is a beginners question.
Which is a better approach among the following
1. class A
{
String sTemp;

public A()
{
this.sTemp = "";
}
}
2.
class A
{
String sTemp = "";
}
I Feel approach 2 is better?
What do u feel?
I would like to know if there are any overheads in the first approach
Thanks,
Sajee Joseph.
 
Gabriel White
Ranch Hand
Posts: 233
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In my experience, which is far outweighed by most in this forum, the "this" command will call from the constructor in that class from which you are working. Your code does have a constructor so I would gather that nothing different would happen as you may already know. As far as overhead I would also gather that since the "this" command is not needed then overhead would be next to nill.
You may want to look at this thread:

HTH
Stevehttp://www.coderanch.com/t/395349/java/java/Difference-xxx-xxx
[ January 20, 2004: Message edited by: Steve Wysocki ]
[ January 21, 2004: Message edited by: Steve Wysocki ]
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, from a performance standpoint, there's absolutely no difference; both compile to identical code. You can see this by compiling each version and then looking at the bytecodes using "javap -c A" .
From a style standpoint, as the second version is both shorter and clearer, I agree that's it's better.
 
Ram Mohan
Ranch Hand
Posts: 44
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i have to disagree with u all....i'm getting confused here, but wouldn't the variable sTemp be available inside the object only inside the first way??? ok, obviously its only a temporary variable (from your name definition), but then again how would i know "how temporary" the variable is...?
 
Dirk Schreckmann
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Take another look at the code examples. sTemp is not a temporary variable, it's an instance variable in both examples.
 
Ram Mohan
Ranch Hand
Posts: 44
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
so does that mean anything declared in a constructor becomes an instance variable?
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No. sTemp is not declared inside a constructor; it's declared by the line "String sTemp;" which is outside any constructor or method, but inside the class.
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!