Lecture 16 - Method parameters and local variables
Lecture 16 - Method parameters and local variables
● A method is a block of code that performs a specific task and may or may not
return a value.
● Methods are declared within a class and can be called from other parts of the
program, either within the same class or from other classes.
● In this example, we define a class called Example with a method called sum.
● The sum method takes two integer arguments and returns their sum.
● We then call the sum method within the main method and store the result in
a variable called result, which is printed to the console.
● Methods can be declared with a variety of modifiers to specify their access
level, return type, and other properties.
● The general syntax of methods with access modifiers:
1
● methodName: The name of the method.
● parameterList: A comma-separated list of input parameters that the method
takes.
Parameters
● A parameter is a value that is passed into a method when it is called.
● Parameters are used to provide additional information to a method that is
necessary for it to perform its task.
● When defining a method, you can specify one or more parameters in the
method signature.
● The parameter list is enclosed in parentheses and can contain zero or more
parameter declarations, each of which is separated by a comma.
● For example, the following method signature declares two parameters, num1
and num2 of type int:
● When this method is called, you need to provide two arguments of type int
that will be assigned to the num1 and num2 parameters respectively.
add(2, 3);
● In this example, the add() method is called with two arguments: 2 and 3.
● The values of these arguments will be assigned to the num1 and num2
parameters respectively, and the method will execute its body using these
values.
● Parameters are used to make methods more flexible and reusable. By
accepting parameters, a method can work with different values without
having to be rewritten for each specific value.
2
Local variables
● A local variable is a variable that is declared inside a block or method and is
only accessible within that block or method.
● Local variables have a limited scope, which means that they are only visible
and can be used within the block or method in which they are declared.
● Once the block or method is finished executing, the local variables are
destroyed and their values are no longer available.
● Local variables are declared with a data type and a name, and can be
initialized with an initial value or left uninitialized.
● Consider this example of a method with a local variable: