Course Content
Java Extended
Java Extended
What is a Method?
Method
In Java, a method is a block of code that performs a specific task. It is a reusable unit of code that can be called and executed multiple times throughout a program. Methods are used to break down the complexity of a program into smaller, manageable parts, making the code more organized and easier to understand.
A method consists of a method signature, which includes the method name and any parameters it accepts, and a method body, which contains the code that defines the behavior of the method.
Methods can have a return type, indicating the type of value that the method returns after execution, or they can be void, meaning they do not return any value.
The basic syntax of any method looks like:
Main
ReturnType MethodName(ParameterType parameter, ParameterType parameter) { // code that will be executed when we will call this method }
Now let's go through everything that has been written above:
ReturnType
: This is the type of value that the method will return. In simple terms, it is the result of executing the method. If the functionality of the method is to add two numbers and return an integer value, then theReturnType
will also beint
;MethodName
: It's just the name of our method. It is good practice to give methods informative names. For example, if the method adds two numbers, a good name would beaddTwoNumbers
;ParameterType
: This is the type of the parameter that the method will accept when it is used. Again, let's take the example of summing two numbers: in this case, we will have two parameters with the typeint
;Parameter
: This is the name of the parameter. This parameter can be used inside the body of the method. It will become clearer when you see a real example of method usage.
Now let's take a look at an example of a method that adds two numbers and returns their sum:
Main
int addTwoNumbers(int firstNumber, int secondNumber) { int result = firstNumber + secondNumber; return result; }
This method takes two int values as parameters, creates a new variable called result
within itself, and assigns it the sum of the two parameters. Then we use the return
keyword, which returns the value of result
.
Note
Methods in Java are similar to functions in other programming languages. They allow you to group blocks of code together to perform specific operations or calculations. Like functions, methods can accept parameters, perform actions, and return results. This enables code organization, reusability, and abstraction of program logic. Additionally, methods in Java can be called from other parts of the program, making them modular and convenient for use in different contexts.
In the next chapter, we will delve deeper into how this method works and learn how to create our own methods.
Thanks for your feedback!