Introduction to Java
Methods are one of the fundamental building blocks in Java. A method is a collection of code that performs a specific task.
When you call a method, the code inside the method is executed. This is known as invoking the method.
Methods can optionally take arguments. These are values that are passed into the method when it is invoked. The method can use these arguments to perform its task.
Methods can also return values. This is useful if the method needs to perform some calculations and return the result.
A method declaration in Java consists of a method signature and a method body. The method signature consists of the modifier, method name, the list of parameters, and the return type. The method body contains the executable code for the method.
Syntax of a method declaration:
Let’s look at each part of the above syntax:
The modifier provides several access modifiers to monitor classes, fields, and methods.
- public - Makes a class or method available to all other classes;
- private - Makes a class or method available only within the declaring class;
- protected - Makes a class or method available to classes in the same package as the declaring class and subclasses of the declaring class.
Static methods can be invoked without creating an instance of a class and declared with the static keyword in a class. It is a method that belongs to the class and not to the object of a class.
When you declare a method, you can optionally specify a return type for the method. A return type is the data type of the value returned by a method. Some methods act but don't return a value. In this situation, the return type is void.
This is the name that we will use to call the method. The name should be descriptive of what the method does.
A parameter list is a set of variables used to store data or information passed into a method. In Java, a parameter list is created by adding a set of parentheses after the method name, followed by a set of variables.
A statement is an instruction that tells the Java virtual machine to do something. When creating a method, you can optionally include one or more statements.
Example for method declaration:
Java has two different types of methods.
- Instance method: Instances are defined in a class that is only accessible through the class's objects. It might affect the values of the object's fields;
- Static method: Static methods belong to a class and are shared across all objects. It cannot access instance variables or methods.
Calling static methods
There are 2 ways.
- Calling from the same class - Just state the method name;
- Calling from another class - Use the class name first, followed by the name of the method, as follows:
The return type of a method that doesn't return a value is ___.
Select the correct answer
Which one is not an access modifier?
Select the correct answer