Java Scope and All That Jazz
In Java, variables are only accessible (can only be used) inside the region they are created; this is called scope.
A method is a block of code that only runs when it is called. Variables declared (created) within the method are within the method scope. The main
method —
public static void main(String[] args) {}
— is the entry point for your application and will subsequently invoke (run) all the other methods required by your program. The main
method accepts a single argument: an array of elements of type String.
myMethod()
is an example name of a method- void means that this method does not have a return value.
- static means that the method belongs to the Main class and not an object of the Main class
Using the keyword static
means methods and variables declared inside the method are class methods and variables; without it, the methods and variables are instance methods. This means the static methods and variables can be accessed (used) anywhere within the code, while the instance variables can only be accessed within the instance method.
A block of code may exist on its own or it can belong to an if
, while
or for
statement. With for
statements, variables that are declared in the statement itself are also available inside the block's scope. Below the variable index
is created in the for loop as an index for each item in the array and can be used in the sayHello() method block.
public class Main { static void sayHello(){ String [] greeting = {“Hello!”, “Hey there!”, “What’s happening?!”, “Hey! Hugs!”}; for (String index : greeting) { System.out.println(index); } }public static void main(String[] args) { sayHello(); }}
Every Java program has a class name, which must match the filename, and every program must contain the main()
method. Curly braces, {}
, mark the beginning and the end of a block of code and each code statement must end with a semicolon (see below for details).
public class Main {public static void main(String[] args) { // Code here CANNOT use x { // This is a block // Code here CANNOT use x int x = 100; // Code here CAN use x System.out.println(x); } // The block ends here // Code here CANNOT use x }}
For more information: https://www.w3schools.com/java/java_scope.asp