I am new to java and have been watching a tutorial, the instructor has added initializing variables outside of the public static void main(String[] args) method as well as he creates another method outside of the main one. I was lead to believe the initialization of variables was to be inside of the public static void main(String[] args) method so why is he putting it outside? He tries to explain but earlier in the tutorial he put them inside so i am confused. Here is what code is going on:
public class Main {
//initializing (why is this here not in the public static void main)
private static ArrayList<Contact> contacts;
private static Scanner scanner;
//the main code area
public static void main(String[] args) {
contacts = new ArrayList<>();
System.out.println("Welcome!");
showInitialOptions();
}
// why did he create this down here and not in public static void main)
private static void showInitialOptions(){
System.out.println("Please select one: "
"\n\n1. Manage Contacts"
"\n\n2. Messages"
"\n\n3. Quit");
scanner = new Scanner(System.in);
int choice = scanner.nextInt();
Maybe i'm just that dumb but if someone could clarify what's going on in a dumbed down way that would be great. Here is the tutorial where things get weird: https://youtu.be/fis26HvvDII?t=18174
CodePudding user response:
Functions allow you to piece-up your code to be reusable, modular and abstractable. In your case showInitialOptions is a logic step in your procedure that can be abstracted in a function different from main, and only then used my other parts of the program that need it.
Also, variables are subject to scoping rules that define their lifetime and usage.
In short, since you seem to be a beginner and this is what you are asking for: some things are outside the main() because otherwise it would be too long and unreadable.
CodePudding user response:
Variables outside a method are called global variables, it's extending the range of using them, unlike local variables instantiation. Search more for global vs. local variables to understand it better.
You can use local or global variables in the upper example but it is a better practice to instantiate them global for later usage, and a bigger range of the class scope.
The second example is a method, you can't create functions inside other functions in Java and in any programming languages (as far as i know).
