Class Notes (1,100,000)
US (490,000)
Cornell (1,000)
CS (100)
CS 2110 (30)
Gries (30)
Lecture 5

# CS 2110 Lecture Notes - Lecture 5: Local Variable

Department
Computer Science
Course Code
CS 2110
Professor
Gries
Lecture
5

This preview shows half of the first page. to view the full 3 pages of the document. Lecture 5 - Scope and Inheritance
oFields belong to classes
oLocal variables belong inside some block of code
Like in an if statement or method
oParameter is inside a method definition
oArguments are passed to parameters
oExample of a Local Variable
Suppose in some block of code we want to swap the values of b and c
If (b>c) {
int temp = b;
b = c;
c = temp; }
Basically, because we declared temp inside the block of code of the if
statement, it only exists inside that block of code
If you tried to write temp = 5 OUTSIDE that block, and it was not
declared outside the if block, then you get an Error
After that if statement (the one above), we know b <= c, so we can assert
that after to be sure our code works
oScope of local variables
Scope is the area of code that certain variable/field can be used in
Inside-out rule
The innermost declaration of a variable is the one the code can
refer to
oNice example:
public class ScopeQuiz {
private int a;
public ScopeQuiz(int b) {
System.out.println(a);
int a = b + 1;
this.a = a;
System.out.println(a);
a = a + 1;
}
public static void main(String[] args) {
int a = 5;
ScopeQuiz s = new ScopeQuiz(a);
System.out.println(s.a);
}
}
What will this print?
So it starts by declaring an a in main to be 5.
Then ScopeQuiz(5) is called.
When it prints a, it first looks for an a in the method definition, but
there’s none there.
find more resources at oneclass.com
find more resources at oneclass.com