90 likes | 107 Views
Learn about the scope of variables in Java programming, including local, global, and parameter scopes. Explore examples and common scope errors.
E N D
COM S 207 Variable Scope Instructor: Ying Cai Department of Computer Science Iowa State University yingcai@iastate.edu
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
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.
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
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; }
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; }
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; } for (int i=1; i<=10; i++) { sum = sum + i; } }
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; }
Exercise 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?