Once you click post assignment, learners in the selected class will immediately be able to see and complete this assignment
Back to Classroom
Methods
Introduction To Java Course
Engineers From These Top Companies and Universities Trust EXLskills
1M+ Professionals | 100+ Institutions
This is the EXLskills free and open-source Introduction To Java Course. It guides learners via explanation, demonstration, and thorough practice, from no more than a basic understanding of Java, to a moderate level of essential coding proficiency.
Is this course FREE?
Yes, this a 100% free course that you can contribute to on GitHub here!
Methods are another section of the class we will explore. In addition to the main method in the class, more methods that have other functions can exist in the project.
Methods are constructed out of statements which are placed between brackets like these "{ }" as shown below:
MethodExample.java
package exlcode;
public class MethodExample {
public static int exampleVariableOne = 5;
public static int exampleVariableTwo = 10;
public static void main(String[] args) {
// this prints the sum of exampleVariableOne and exampleVariableTwo
System.out.println(add(exampleVariableOne, exampleVariableTwo));
}
// this method takes in two parameters and
// returns the sum of the two parameters
public static int add(int parameterOne, int parameterTwo) {
return parameterOne + parameterTwo;
}
}
We can identify a method name because it is always followed by parentheses, which may also enclose parameters. The general form of the method header will be similar to what you see below:
The items that must be written in a method header are "returnType", "functionName" and "parameterName", because "visibility" has a default value. In the above example, the return type void signifies that the method does not return anything, which is why we do not see a statement that says return. As we see in the method above, a return value can be printed so that it appears on the console. This ensures that we are not only calling the result, but we are also able to view it and check it to make sure the program is running correctly. When we need more than one parameter, they are written one after the other, separated by commas.
An extremely important attribute of parameters to keep in mind is that all parameters are just copies of the original value or address. Regardless of what we do to the parameter inside the method, the original value will not change. The only way to change it is to assign the original value in the original parameter to something else. To explain using our example, changing the value of parameterOne does not affect the value of exampleVariableOne.