Topic Overview and Actualization

Greetings! Today, we will venture into the universe of functions and procedures in Java, which are vital tools in the programmer's toolbox - they introduce reusable components that can be defined once and used everywhere. Functions execute tasks and return a value, whereas procedures perform tasks without returning anything. This lesson will guide you through writing Java functions and procedures.

Understanding Java Syntax for Functions and Procedures

Functions and procedures are similar to recipes. They consolidate instructions to carry out specific tasks. Imagine baking a cake — a procedure — and sharing it — a function. Baking doesn't yield anything, so it's a procedure. However, sharing returns the remaining cakes, making it a function.

The structure of functions and procedures in Java is as follows:

static returnType functionName(parameters) {
  // Code body
}

At first, this structure may seem strange, but think of it as a recipe. static is just a keyword you have to remember for now. returnType is the type of dish you'll get after cooking. functionName is the title of the recipe. The parameters are the ingredients, with the {} brackets containing the cooking method - the recipe itself.

Writing Our Own Java Function

With those explanations in mind, let's craft some functions and procedures.

static int addTwoNumbers(int num1, int num2) {
  int sum = num1 + num2; 
  return sum; // returns the sum of num1 and num2
}

This function is named addTwoNumbers, takes two int numbers as parameters, and returns an int too. Inside the function, it adds two input parameters and returns their sum as the result of the function.

The return statement is akin to the chef announcing that the dish is ready. It notifies the program that the function has accomplished its task and produced a result, finishing the function's execution after that. In the addTwoNumbers function, return sum; indicates that the operation has concluded, and the sum of num1 and num2 is the result. You can't execute any other code or statements after return.

Writing Our Own Java Procedure

Next, we'll create a procedure that prints a greeting:

static void printGreeting(String name) {
  System.out.println("Hello "+ name + ", welcome to Java!");
}

The procedure is the same function, but with return type void - meaning "no return". As you can see, this procedure just prints a simple greeting message to the console and doesn't return anything as a result.

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal