Presentation is loading. Please wait.

Presentation is loading. Please wait.

Department of Computer Science

Similar presentations


Presentation on theme: "Department of Computer Science"— Presentation transcript:

1 Department of Computer Science
COM S 207 Variable Scope Instructor: Ying Cai Department of Computer Science Iowa State University

2 The scope of a variable is the part of the program in which it is visible
public static void main(String[] args) { System.out.println(cubeVolume(10)); } public static double cubeVolume(double sideLength) return sideLength * sideLength * sideLength; the scope of the parameter sideLength is the entire cubeVolume method, but not the main method

3 Local variable: A variable that is defined within a method
public static void main(String[] args) { int sum = 0; for (int i=0; i<=10; i++) int square = i * i; sum = sum + square; } System.out.println(sum); The scope of a local variable ranges from its declaration until the end of the bloack or for statement in which it is declared.

4 An example of a scope problem
public static void main(String[] args) { double sideLength = 10; int result = cubeVolume((); System.out.println(result); } public static double cubeVolume() return sideLength * sideLength * sideLength; trying to reference a variable defined outside of the method body

5 The same variable name may be used more than once
public static void main(String[] args) { int result = square(3) + square(4); System.out.println(result); } public static int square(int n) int result = n * n; return result;

6 The same variable name may be used more than once
public static void main(String[] args) { int result = square(3) + square(4); System.out.println(result); } public static int square(int n) int result = n * n; return result;

7 You can have two variables with the same name in the same method
public static void main(String[] args) { int sum = 0; for (int i=1; i<=10; i++) sum = sum + i; }

8 Illegal: two variables with the same name have their scopes overlapped
public static int sumOfSquares(int n) { int sum = 0; for (int i=1; i<=n; i++) int n = i+1; sum = sum + n; } return sum;

9 Exercise what is the scope of variable i defined in line 13?
public class Sample { public static void main(String[] args) int x = 4; x = mystery(x+1); System.out.println(s); } public static int mystery(int x) int s = 0; for (int i=0; i<x; x++) int x = i+1; s = s + x; return s; what is the scope of variable i defined in line 13? which is the scope of variable x defined in line 10? there are two scope errors in the code. what are they?


Download ppt "Department of Computer Science"

Similar presentations


Ads by Google