JAVA SCOPE
Maricar Borja
Shajani Buquis
J AVA S C O P E
JAVA In Java, variables are
only accessible inside the
SCOPE region they are created
2
JAVA SCOPE
METHOD BLOCK
LEVEL
SCOPE
SCOPE
METHOD LEVEL
SCOPE
Borja,Maricar
METHOD LEVEL SCOPE
o Any variable declared in a method, including
arguments, is not accessible outside of that
method.
o All variables declared inside methods are
visible from the beginning of their declaration
to the end of the method.
METHOD LEVEL SCOPE
o Any variable declared EXAMPLE:
in a method,
including arguments, public class Main {
is not accessible public static void main(String[] args)
outside of that {
method.
// code here cannot use x
int x = 100;
o All variables declared
inside methods are // code here can use x
visible from the System.out.println(x);
beginning of their }
declaration to the
end of the method. }
METHOD LEVEL SCOPE
o Any variable declared EXAMPLE:
in a method, public class Main {
including arguments, public static int myMethod(int arg) {
is not accessible int x = 100; //local method
outside of that variable
method. return x + arg;
}
o All variables declared public static void main(String[] args) {
inside methods are System.out.println(myMethod(5));
visible from the
beginning of their System.out.println(myMethod(17));
declaration to the }
end of the method.
}
BLOCK
SCOPE
Buquis,Shajani
BLOCK SCOPE
A block of code refers to all of the code between curly
braces {}.
Variables declared inside blocks of code are only
accessible by the code between the curly braces, which
follows the line in which the variable was declared:
BLOCK SCOPE
A block of code refers to public class Main {
all of the code between public static void main(String[] args) {
curly braces {}. { // This is a block
// Code here CANNOT use x
Variables declared inside int x = 100;
blocks of code are only // Code here CAN use x
accessible by the code System.out.println(x);
between the curly braces , } // The block ends here
which follows the line in }
which the variable was }
declared :
BLOCK SCOPE
A block of code may exist public class JScopeTest2 {
on its own or it can belong public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
to an if, while or for int sum = 0;
statement. In the case of sum = sum + i;
}
for statements, variables
declared in the statement int sum = 1;
System.out.println(sum);
itself are also available }
inside the block's scope. }
ACTIVITY TIME !
J AVA S C O P E
ACTIVITY
public class Main {
public static int myMethod(int arg) {
return x + arg;
Fix the following int x = 70;
}
code to get 78 and public static void main(String[] args) {
11 7 a s o u t p u t . System.out.println(myMethod(5));
System.out.println(myMethod(17));
}
}
13
THANK YOU
Maricar Borja
Shajani Buquis