Gaurank Choudhary wrote:Well i am new to Java, reading Head First Java. Have some doubt about keyword "static". The book explained it well enough, but still have some doubts. So it'd be great to have help from you people..!!
The easiest way I know of explaining it for a variable is 'belongs to the class'. That is, there is exactly one variable for the class that it's defined in. Without the static modifier, there is one variable for each object.
And BTW, before you start creating lots of them, static variables should be used very sparingly (if at all). My suggestion would be not to define any until you know when and where they make sense.
Isn't it funny how there's always time and money enough to do it WRONG?
Joined: Jul 09, 2012
Well that helped a lot. But one more thing, why the main() method is made static..??? i guess this would clear all my doubts regarding static if you explain this concept.
Gaurank Choudhary wrote:Well that helped a lot. But one more thing, why the main() method is made static..???
And just to add to Henry's post - probably because that's the way C/C++ does it. Java is like a "well-behaved child" of those two languages, but the original designers probably started out with them, so couldn't throw out all the baby with the bathwater. Just my guess though.
i guess this would clear all my doubts regarding static if you explain this concept.
I doubt it, but what I would definitely recommend is NOT defining static variables because you think you have to. Those compiler errors are coming from the fact that you haven't created any objects yet. And fairly soon you'll learn not to put all your code in the main() method (in fact, almost none of it).