Win a copy of Java Mock Exams (software) this week in the Programmer Certification (OCPJP) forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

why initialize variables the way they do in Android

 
x kevik
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am curious to why certain things are done in android and why they are done in that way. What is the advantage? One of these things is the way that variables are initialized in Android. I see many examples on the net and in books where they define the variable in the beginning of the class and never give it an initial value. then later they will initialize the variable in the onCreate method of the activity. Why not define it and initialize it in only one line like this: Int x = 0; or Button b = (Button) findViewById(buttonFromXML);

instead it is always split in two like this;

Integer x;
Button b;

@Override
public void onCreate() {

x = 0;

b = (Button) findViewById(buttonFromXML);

}
 
Ulf Dittmer
Rancher
Posts: 42970
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The button (or whatever UI component) only exists once the layout that contains it has been created. That's usually one of the first things that happens in the onCreate method.
 
Happiness is not a goal ... it's a by-product of a life well lived - Eleanor Roosevelt. Tiny ad:
the new thread boost feature: great for the advertiser and smooth for the coderanch user
https://coderanch.com/t/674455/Thread-Boost-feature
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!