Notice the braces { ... }
around the body of each method:
These scopes are called
method scopes
Fact:
The braces surrounding
bodies of methodsalways define
non-overlapping (disjoint)
scopes
I.e.: method scopes are
always disjoint !!!
Example:
Properties of variables defined in
disjoint scopes
Property 1: (You have seen this property before)
You can definedifferent variables
with the same name
in
disjoint scopes
Example:
Hence:
You can use the
same name
for
different variables
in
disjoint method scopes
Example:
Property 2:
It is impossible for
computer instructions
inside one disjoint scope
to
accessvariables defined inside
another disjoint scope
The reason is as follows:
Because the 2 scopes are
disjoint (no overlap):
a statement in the
second disjoint scopemust be outside
the first disjoint scope
in which the variable was defined.
Hence:
Statements inside
one method
can never
access any
variable defined
inside another method !!!
Example:
Terminology: side effect
Side effect (computer science):
In computer science, a
method
is said to
"have a side effect" if:
The methodmodifies (= changes the value)
a variable that
is defined outside the
body of the method
Local variables make finding error easier...
Fact in Java:
A local variable
defined inside a
methodcannotmodified
by any other method
In other words:
When you are writing a method,
you can be 100% certain that
the local variables defined
inside the method will
only be changed
by statements
inside
that method
Therefore:
When you have an error inside
a method where some
variable is updated erroneously,
then you
do not need to suspect
that the cause
lies
outside that method !!!
Note:
It is pretty difficult to
find errors in
complex program
Having localized updates in methods
does make
finding errors a
little bit easier....