2. 2
Parameters
• The method below will print the first 5 squares:
public class ParameterTest {
public static void printSquares() {
for (int i = 1; i <= 5; i++) {
System.out.println(i + " squared = " + i * i);
}
}
public static void main(String[] args) {
printSquares();
}
}
• What if we wanted to make this print an arbitrary number of
squares?
Monday, September 9, 13
3. 3
Parameters
• You could assign try to assign a variable to do it:
public class ParameterTest {
public static void printSquares() {
for (int i = 1; i <= maxSquare; i++) {
System.out.println(i + " squared = " + i * i);
}
}
public static void main(String[] args) {
int maxSquare = 5;
printSquares();
}
}
// won’t work!
Monday, September 9, 13
4. 4
Parameters
• Instead, we can have printSquares() take a parameter:
public class ParameterTest {
// maxSquare is a variable local to the method
public static void printSquares(int maxSquare) {
for (int i = 1; i <= maxSquare; i++) {
System.out.println(i + " squared = " + i * i);
}
}
public static void main(String[] args) {
printSquares(5);
}
}
• formal parameter (variable) vs. actual parameter (value)
Monday, September 9, 13
5. 5
Parameters
• The actual parameters passed to a method call can be
expressions:
public class ParameterTest {
public static void printSquares(int maxSquare) {
for (int i = 1; i <= maxSquare; i++) {
System.out.println(i + " squared = " + i * i);
}
}
public static void main(String[] args) {
int firstMax = 5, secondMax = 8;
printSquares(firstMax); // prints all squares to 5
printSquares(secondMax + 1); // prints all squares to 9
}
}
Monday, September 9, 13
6. 6
Scoping methods
public class ParameterTest {
public static void printSquares(int maxSquare) {
for (int i = 1; i <= maxSquare; i++) {
System.out.println(i + " squared = " + i * i);
}
}
public static void main(String[] args) {
int firstMax = 5, secondMax = 8;
printSquares(firstMax); // prints all squares to 5
printSquares(secondMax + 1); // prints all squares to 9
}
}
method main method printSquares method printSquares
firstMax
secondMax
maxSquare maxSquare5
8
5 9
Monday, September 9, 13
7. 7
Scoping methods
• Be careful with the way you name parameters:
public class ParameterExample {
public static void main(String[] args) {
int x = 4;
doubleNumber(x);
System.out.println("x = " + x);
}
public static void doubleNumber(int x) {
System.out.println("Initial value = " + x);
x *= 2;
System.out.println("Final value = " + x);
}
}
method main method doubleNumber
x x4 48
Monday, September 9, 13