0

Order of declaring a variable, methods and main-method in Java

I'm having problems to figure out if the order of declaring a variable, methods and main-method matters. What to put first? General code: Public class orderOfMethods { int a = 5 // declaring variables first? int b = 10 public static void main(String[] args) { // Then the main-method? if (a<b) { ...} //if a < b, then execute method 1 else if (a=b) { ...} // if a = b, then execute method 2 else { ...} // if a>b ,then execute method 3 } Class method1 { ...} // And after that the methods that are needed in the main-method? Class method2 { ...} // Class method3 { ...} // } I have 2 questions: 1. Does Java accept the code I wrote? So is it ok to first put a reference to method 1, 2 and 3 and after that give orders for these methods? 2. What is the most common / most practical way to write a code so it doesn't get a messy code? In other words: is there a better way to order methods etc.?

25th Apr 2018, 1:05 PM
Steffanie
Steffanie - avatar
5 odpowiedzi
+ 3
The table on this page might help... I never read anything about the subject but reading this now, I can see that it is pretty much how I was taught to organize my methods when I was taught Java in college https://web.archive.org/web/20130516014426/http://www.oracle.com/technetwork/java/codeconventions-141855.html#1852
25th Apr 2018, 1:30 PM
cyk
cyk - avatar
+ 2
Yes. Like can you define what the methods do after seemingly calling them in main? The answer is yes. In Java methods are oftentimes defined after the main method anyway.... In some other languages you cannot do that but here it is totally fine.
25th Apr 2018, 1:55 PM
cyk
cyk - avatar
25th Apr 2018, 1:26 PM
Karankumar
+ 1
And I want to answer your first question but I don't really understand what you mean
25th Apr 2018, 1:37 PM
cyk
cyk - avatar
+ 1
@Karankumar: Thank you! I'll shuffle the variables and methods to try what does work and what doesn't. @cyk: Your answer is great! I guess the table is helpful. My first question is about: will Java accept that I first give a reference to method 1, and after that give orders how to execute method 1. It's like somebody says to you: "you have to do what I told you!". And AFTER that, he is telling you what you have to do: "clean your room". Doesn't make any sense in the real world, but will Java accept this command? That confused me a little. My second question is about: is there any other way to write a better / more understandable code?
25th Apr 2018, 1:52 PM
Steffanie
Steffanie - avatar