• Post Reply Bookmark Topic Watch Topic
  • New Topic

Declaring a variable after a method that uses it?  RSS feed

 
Richard Newman
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I know that it works, so I'm just looking for a little reasoning or logic behind why Java doesn't fail to compile code like the following:



The String variable 'specialization' is declared after the variable is used in the Constructor, which I thought was always run first? And if it ran first and encountered an undeclared variable, wouldn't it fail to compile?

If I added something like



would the code still compile correctly or is declaring a variable after a method a problem whereas declaring it after a constructor apparently isn't???
 
Bear Bibeault
Author and ninkuma
Marshal
Posts: 66304
152
IntelliJ IDE Java jQuery Mac Mac OS X
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Declarations don't "run". The class is defined as the combination of its methods and variables, and that happens long before any code is run. So the order of declaration in this case is not meaningful.

That said, convention dictates that variable should precede methods, so follow that pattern and no one gets hurt.
 
Richard Newman
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Bear Bibeault wrote:Declarations don't "run". The class is defined as the combination of its methods and variables, and that happens long before any code is run. So the order of declaration in this case is not meaningful.

That said, convention dictates that variable should precede methods, so follow that pattern and no one gets hurt.


Thanks! I thought it might be something along those lines. I guess that's the downside of looking at "clean code" versus test questions. XD
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!