Basic Syntax


🙋 Need help? Ask an expert now!

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:
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:

{visibility}{returnType}{functionName}(type parameterName)

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.

Edit Me on GitHub!

Application Question

Which one of these method declarations is incorrect?