So far, we've used various commands: value assignment, calculations, conditional statements, and loops. Show
Printing to the screen has been done with the statement Technically speaking, a method is a named set of statements. It's a piece of a program that can be called from elsewhere in the code by the name given to the method. For instance So far all the methods we have used have been ready-made Java methods. Next we will learn to create our own methods. Custom MethodsA method means a named set consisting of statements that can be called from elsewhere in the program code by its name. Programming languages offer pre-made methods, but programmers can also write their own ones. It would, in fact, be quite exceptional if a program used no methods written by the programmer, because methods help in structuring the program. From this point onward nearly every program on the course will therefore contain custom-created methods. In the code boilerplate, methods are written outside of the curly braces of the
Let's observe how to create a new method. We'll
create the method
And then we'll insert it into a suitable place for a method.
The definition of the method consists of two parts. The first line of the definition includes the name of the method, i.e. Calling a custom method is simple: write the name of the methods followed by a set of parentheses and the semicolon. In the following snippet the main program (main) calls the greet method four times in total.
The execution of the program produces the following output: Sample output Let's try if we can travel to the method world: Greetings from the method world! Looks like we can, let's try again: Greetings from the method world! Greetings from the method world! Greetings from the method world! The order of execution is worth noticing. The execution of the program happens by executing the lines of the main method ( Strictly speaking, the main program ( Loading Loading From here on out, when introducing methods, we will not explicitly mention that they must be located in the correct place. Methods cannot be defined e.g. inside other methods. On Naming Methods The names of methods begin with a word written entirely with lower-case letters, and the rest of the words begin with an upper-case letter - this style of writing is known as camelCase. Additionally, the code inside methods is indented by four characters. In the code example below the method is poorly named. It begins with an upper-case letter and the words are separated by _ characters. The parentheses after the method name have a space between and indentation in the code block is incorrect.
In contrast the method below is correctly named: The name begins with a lower-case letter and the words are joined together with the camelCase style, meaning that each word after the first begins with an upper-case letter. The parentheses sit next to one another and the contents are correctly indented (the method has its own code block, so the indentation of the code is four characters).
Method ParametersParameters are values given to a method that can be used in its execution. The parameters of a method are defined on the uppermost line of the method within the parentheses following its name. The values of the parameters that the method can use are copied from the values given to the method when it is executed. In the following example a parameterized method
We will call the method
Sample output Greetings! Greetings! Greetings! Greetings! Just like when calling the predefined method
Sample output Greetings! Greetings! Greetings! If an expression is used as a parameter for a method, the expression is evaluated prior to the method call. Above, the expression evaluates to Loading Loading Multiple ParametersA method can be defined with multiple parameters. When calling such a method, the parameters are passed in the same order.
Sample output The sum of numbers 3 and 5 is 8 The sum of numbers 2 and 4 is 6 Loading Loading Parameter Values Are Copied in a Method CallAs a method is called the values of its parameters are copied. In practice, this means that both the main method and the method to be called can use variables with the same name. However, changing the value of the variables inside the method does not affect the value of the variable in the main method that has the same name. Let's examine this behavior with the following program.
The output of the program is: Beneath, you'll find the same program visualized step-by-step. Changing the values of the variables in the method printNumbers does not affect the values in the main method, even though they have the same names. So, method parameters are distinct from the variables (or parameters) of other methods, even if they had the same name. As a variable is passed to a method during a method call, the value of that variable gets copied to be used as the value of the parameter variable declared in the method definition. Variables in two separate methods are independent of one another. To further demonstrate this point, let's consider the following example. We define a variable called
The execution of the program produces the following output. Sample output The value of the variable 'number' in the main program: 1 The value of the method parameter 'number': 1 The value of the method parameter 'number': 4 The value of the variable 'number' in the main program: 1 When the variable The
parameter Methods Can Return ValuesThe definition of a
method tells whether that method returns a value or not. If it does, the method definition has to include the type of the returned value. Otherwise the keyword
The keyword To actually return a value, we use the command
The method defined above returns an
The return value of the method is placed in an
All the variable types we've encountered so far can be returned from a method.
Loading Loading When execution inside a method reaches the command The lines of source code following the command For the IDE, a method such as the following is faulty.
The next method works since it is possible to reach every statement in it — even though there is source code below the return command.
If a method has the form
Defining Variables Inside MethodsDefining variables inside methods is done in the same manner as in the "main program". The following method calculates the average of the numbers it receives as parameters. Variables
One way to call the method is as follows.
Variables defined in a method are only
visible inside that method. In the example above, this means that the variables
In the above example, an attempt is made to use the variable The following mistakes are also commonplace.
Above, there is an attempt to use the name of the method As well as placing the method result into a helper variable, another way that works is to execute the method call directly inside the print statement:
Here, the method call occurs first returning the value 5.0, which is then printed with the help of the print statement. Calculating the Return Value Inside a MethodThe return value does not need to be entirely pre-defined - it can also be calculated. The return command that returns a value from the method can also be given an expression that is evaluated before the value is returned. In the following example, we'll define a method sum that adds the values of two variables and returns their sum. The values of the variables to be summed are received as method parameters.
When the execution of the method reaches the statement The method is called in the following way. Below, the method is used to add the numbers 2 and 7 together. The value resulting from the method call is placed into the
variable
Let's expand the previous example so that the numbers are entered by a user.
In the example above, the method's return value is not stored in a variable but is instead directly used as part of the print operation. The print command's execution is done by the computer first evaluating the string Since the values passed to a method are copied to its parameters, the names of the parameters and the names of the variables defined on the side of the caller have, in fact, nothing to do with each other. In the previous example,
both the variables of the main program and the method parameters were named the same (
Now the value of the variable Loading Loading Loading Loading Execution of Method Calls and the Call StackHow does the computer remember where to return after the execution of a method? The environment that executes Java source code keeps track of the method being executed in the call stack. The call stack contains frames, each of which includes information about a specific method's internal variables and their values. When a method is called, a new frame containing its variables is created in the call stack. When the execution of a method ends, the frame relating to a method is removed from the call stack, which leads to execution resuming at the previous method of the stack. The right side of the visualization below displays the functioning of the call stack. When a method is called, a new frame is created in the stack, which is removed upon exit from the method call. When a method is called, the execution of the calling method is left waiting for the execution of the called method to end. This can be visualized with the help of a call stack. The call stack refers to the stack formed by the method calls — the method currently being executed is always on the top of the stack, and when that method has finished executing the execution moves on to the method that is next on the stack. Let's examine the following program:
The execution begins from the first line of the
Once the print command has been executed, we move on to the next command, which calls the method Sample output printNumber main Once the method Call Stack and Method ParametersLet's examine the call stack in a situation where parameters have been defined for the method.
The execution of the program begins on the first line of the Sample output main beginning = 1 end = 5 When Sample output printStars beginning = 1 end = 5 main beginning = 1 end = 5 When the command Sample output printStars beginning = 2 end = 5 main beginning = 1 end = 5 As such, the values of the variables in the method Sample output main beginning = 1 end = 5 Let's observe the same program by visualizing its execution step-by-step. The application used for visualization grows the call stack downwards — on the right side, the method on top is always Call Stack and Returning a Value from a MethodLet's now study an example where the
method returns a value. The
At the beginning of the When
the variables Sample output start first = 5 second = 6 main The command Sample output sum number1 = 5 number2 = 6 start first = 5 second = 6 sum // no value main The execution of the method Sample output start first = 5 second = 6 sum = 11 main After that, the print command is executed, and then we return to the Method Calling Another MethodAs we noticed earlier, other methods can be called from within methods. An additional
example of this technique is given below. We'll create the method
The output of the method call Sample output 1 2 3 2 4 6 3 6 9 Below is a visualization of the method call Loading Loading When a method is it means that multiple methods in the same class have the same name?Having two or more methods named the same in the same class is called overloading.
Can a class have multiple methods with same method name and same parameter list?Yes, we can define multiple methods in a class with the same name but with different types of parameters.
What is it called when two methods have the same name but different parameter lists?Method overloading means two or more methods have the same name but have different parameter lists: either a different number of parameters or different types of parameters.
What do you call declaring two methods with the same name but different number of parameters inside the same class?Overloading occurs when two or more methods in one class have the same method name but different parameters.
|