In this section, we will learn what the Class methods are and how to use them in Java.
Note: Before reading this section, we’re assuming you’re already familiar with classes and objects as well as attributes in a class.
What is Method in Java?
A car has attributes and methods. The attributes of a car or any other objects in essence are those properties and information that are attached to the object. Like its name, shape, height, weight, color and taste etc. as mentioned in the attribute section.
On the other hand, we have methods of an object.
Consider a car: It has multiple functionalities and so provided multiple methods for running those functions.
For example, we use the wheel to control the direction of the car. We use gas pedal to increase the speed of the machine. We use brake pedal to stop the car. We use door handles to open and close the doors of the car.
Each of these functions and many others has a method that we can use to run the function.
Even under the hood of a car, there are functions and methods that work without us knowing that they are there.
Now in programming, we have methods as well. These methods have bodies and inside these bodies, we can define a set of instructions to be executed whenever that method is called.
In terms of visibility, there are two types of methods in an object:
- Those that are public and basically we can interact with them, which are called the interface of the object. (Pedals and the wheel of a car are just a few methods that are part of the overall interface of the car).
- Those that are hidden (private or protected): these methods are inside an object and when we interact with public methods, these public methods can call those hidden methods and run the necessary instructions.
For example, if we consider a gas pedal in a car as the public method, then calling this method (pushing the pedal) will call other hidden methods (like hidden sensors etc.) To make the overall speed of the car to increase.
As you’ll soon see, methods and attributes in a class can interact with each other no-matter if they are private or public.
Alright, now that we know what methods are, let’s see how we can create and use them in Java programming.
How to define a method in Java: Method Syntax
This is the structure of a method in a class:
Access-specifier data-type methodName(parameters…) { //body… }
Note: `{}`: after the parentheses of a method, comes the pair of braces `{}` and here we write the instructions that is expected for this method to run at each method call.
Method Access Modifiers
A method just like classes and attributes has access-specifier.
There are three types of access specifiers that we can set for a method:
- `private`: a private method can only be accessed within the body of the class itself. This means no object that is created from this class can access the method. Also, a private method cannot be accessed in a derived class (more about this in inheritance section. )
- `public`: a method that is declared as `public` can be accessed within the body of the class that is being declared in; objects that are created from the class and the derived classes can also access the method. (Derived classes are explained in inheritance section).
- `protected`: a method that is declared as `protected` is only accessible from the body of the class that is being declared in and the derived classes and the objects that are in the same package.
Note: objects that are of the same class type but are declared in a separate package cannot access their protected methods.
Note: if we don’t set the access specifier of a method, it will be accessible only within the package that the owner class is defined in. That means an object, derived classes etc. in the same package can work with such a method. But if they are in another package, the method will be hidden from them.
Return Type of a Method in Java
A method can be designed in a way to return a value to the caller. Caller is actually another method that within its body it calls the target method. (We will explain how to call a method later in this section). So when designing a method to return a value, we need to declare the type of value that this method can return.
Example: methods with different return types in Java
public String getName(){ return name; } public String getLastName(){ return lastName; } public int getAge(){ return age; }
Here we have three methods and their return types are String and int.
Java Void Method: void keyword
If the method does not return anything to the caller, we set the keyword `void` as the replacement of the `data-type` which signals the compiler that this method does not return anything to its caller.
For example, if the method returns an integer value at each call, then the type of method is `int`. Or if the method returns `double` values at each call, then the data-type of that method should be declared as `double` and so on…
Method Identifier in Java
A method should have a name, otherwise how can we call a method? The name of a method is known as its identifier.
Also, the rules that apply to the name of variables also apply to the name of methods as well.
Note:
- The de facto standard is to start the name of a method with a lowercase letter.
Method Parameters in Java
After the name of a method comes the parentheses `()`. Some methods, in order to function correctly, they need inputs. For example, consider a method named `sum`. This method accepts two input values and adds them together and returns the result. So obviously, this method needs two values to function correctly. This is where parameters come in.
Inside the parentheses of a method, we can declare multiple variables that are also called parameters:
- These variables (AKA parameters) are the local variable of the method and cannot be accessed via other methods in the same class.
- Variables (AKA parameter) are separated from each other via comma `,`.
If for example, the `sum` method mentioned above takes 2 integer values, then this is how we should design the parameters of the method:
public int sum(int a, int b){ //body... }
As you can see, the name of the method is `sum`, the return data type of this method is `int`, its access specifier is `public` and it has two parameters (local variables) named `a` and `b` which are of type integer and so when are calling this method, we need to set two integer values as its input.
What is argument in Java?
The value we put as the argument of a method when calling it is known as argument.
You’ll see how to call a method and put values as its input, but for now this is how we can call a method like `sum`:
sum(10,20);
The first input value will be stored in the variable `a` and the second value will be stored in the variable `b`.
Note: we use comma `,` to separate the argument values when calling a method that takes multiple arguments.
Example: setting parameters for methods in Java
public int sum(int a, int b){ int res = a + b; return res; }
Here in the body of the method `sum` we’ve added the values of two variables `a` and `b` and stored that result in a local variable named `res` and then returned the value of this `res` variable as the result to the caller method.
Notes:
Inside the body of a method in a class, we can access the private members (attributes or other private methods) of that class.
Return statement in a method
When a method is expected to return a value to its caller, we use the `return` statement and put the final value that we want to be sent to the caller on the right side of this keyword. Basically, the `return` keyword creates a terminating statement. This means the moment Java engine reaches to this statement, it will return the value on the right side of the `return` keyword back to the caller and stop the execution of instructions (if any) in that method. So if we put any more instructions after the `return` keyword, they won’t be run.
In this example, we’ve returned the value of the ` res` variable via the `return` keyword.
Note: In stack & heap section we explained in more details but for now, remember that after calling the `return;` statement, the life of the method is ended and so we can’t put any instruction after this statement because it won’t be run.
As you can see in the example above, the data-type of the returned value is the same as the data-type of the method (both are `int`).
Example: creating a void method in Java
public void printMessage(String name) { System.out.println(name); }
The access specifier of this method is `public` which means it is accessible from other objects as well as inside the class that is being declared and inside the derived classes that inherit from this class.
The data-type of this method is `void` which means it does not return any value to its caller.
The name of the method is `printMessage`.
It has one parameter, and that is of type `String` (Again, parameters are the local variable of the method). And so when we call this method, we need to set one string input as the input value of the method.
Also, inside the body of this method, the input value will be sent to the output stream.
Calling a Method in Java
Calling a method is relatively simple. All we need to do is to call the name of the method and put a pair of parentheses on the right side of the method.
Note: if a method has N number of parameters, we need to set exactly the same number of values (AKA arguments) for the method when calling it. Otherwise the compiler will return error instead of compiling the program.
Example: calling a method in Java
Create a class with the name `Person` that has this body:
public class Person { private String name; private String lastName; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } }
Now, in the same directory, create another class with the name `Simple` that has this body:
public class Simple { public static void main(String[] args) { Person prs = new Person(); prs.setName("John"); prs.setLastName("Doe"); System.out.println(prs.getName()); System.out.println(prs.getLastName()); } }
Output:
John Doe
If you compile and run the example above, you’ll see the name and the last name appeared on your screen.
Inside the body of the `Person` class, we’ve two private attributes named `name` and `lastName` and 4 public methods.
The first public method of this class is:
public String getName() { return name; }
Here the name of the method is `getName()`, the access specifier is `public` and so objects can access the method(basically this method is part of the interface that the object represents). The method returns a value of type `String`. It does not have a parameter and so it won’t take any argument (input) when it is being called.
Any object that calls this method will get the value of `name` attribute (which is private to the eyes of objects but methods of this object can set and get the value of this variable).
The next method of the class `Person` is:
public void setName(String name) { this.name = name; }
The access specifier of the method is `public`, the data-type of the method is `void` which means it does not return a value. The name of the method is `setName` and it has one parameter of type `String`. This means when calling the method, we need to put a string value as its argument.
Inside the body of this method, we’ve assigned the input value to the `name` attribute of the object.
Note: because the name of the parameter and the name of the attribute are the same here, we’ve used the `this` keyword before the name of the attribute to differentiate these two names from each other.
So the `this.name` is pointing to the `name` attribute of the object and the identifier `name` alone is pointing to the parameter of the method in this example.
The next method in this class is:
public String getLastName() { return lastName; }
Here the name of the method is `getLastName`, its data-type is `String`, its access specifier is `public` which means objects can access this method. And inside the body of the method, we’re returning the value of the `lastName` attribute to the caller.
Again: methods in a class have the access to the private and protected members (attributes and methods) of that class.
The next method of this class is:
public void setLastName(String lastName) { this.lastName = lastName; }
Here the name of the method is `setLastName`, the data-type of the method is `void` which means it does not return any value to the caller. The access specifier is `public` and so objects can access this method (basically the method is part of the interface of the object). This method also has one parameter named `lastName` which is of type `String`.
Inside the body of the method, we’ve assigned the value of the `lastName` parameter to the `lastName` attribute of the object.
Next inside the body of `main()` method in the `Simple` class, we’ve created an object of type `Person` and stored that object in the `prs` variable.
To access the public methods of this object, we use the dot `.` operator and followed by that is the name of the methods that we want to call.
Note: inside the body of a class, one method can invoke the other without prefixing a name (unless the method is static and this will be covered in the static method section).
Inside the body of the `main()` method, we used the `prs` object to call its methods:
The first call is:
prs.setName("John");
We know that the `setName()` method had one parameter of type String and so to call this method we need to put one string argument as well. Otherwise the compiler will return error.
The next method that we’ve called is:
prs.setLastName("Doe");
Again, we know that the `setLastName()` method had one parameter of type `String` and so we need to put a string value when calling this method. Otherwise the compiler will return error instead of compiling.
The next method call is:
System.out.println(prs.getName());
Here inside the `println()` method, we called another method `getName()`.
We remembered that the `getName()` method returns a string value. So when we called this method, it retuned the value of the `name` attribute of the `psr` object and then set this value as the argument of the `println()` method.
Note: The `println()` method also takes a string value as its argument and so in this example the returned value of the `getName()` method became the argument of this method.
The next method call in this example is:
System.out.println(prs.getLastName());
Here, inside the parentheses of the `println()` method we called the `getLastName()` method and we know that this method returns a value and that is the value of the `lastName` attribute of the `psr` object. And this returned value becomes the argument (input value) to the `println()` method.
Basically, the `println()` only needs an argument (value) to function correctly, but it doesn’t care where this value is coming from. This value could be the value of a variable, the returned value of a method call or the result of an expression.
Note: if a method does not return a value (it is declared as `void`) we can’t use it as the argument of the `println()` method because this method needs a value and a void method does not return a value.
Remember: A method that calls another method is named `caller method` and the method that is being called is named `called` or `callee` method.
So far in the examples of this section, the `main` method was the `caller method` and other methods that we called them in the body of this method were `called or callee methods`.
Final parameters in Java
As mentioned before, parameters are basically the local variables of methods. So a local variable just like other types of variables can be set to final and that means after declaring and initializing the variable (or parameter) we can no-longer reassign that variable.
Example: creating final parameters in Java
public void setName(final String name){ this.name= name; } public void setLastName(final String lastName){ this.lastName = lastName; }
Here, the two parameters of these methods are set to final. This means inside the body of the methods we can’t reassign a value to these parameters anymore! Basically, only when the methods are being called, the assignment is allowed.
Note: you can call a method is final parameters as many times as you want but inside the body of such method, we can’t reassign a value to a final parameter.
Java Local variables
So far we’ve mentioned local variables a few times, but now let’s see what it really means when we say a local variable!
A local variable is a variable that is defined inside the body of a method or in a block `{}`.
Such a variable is only accessible within its enclosing open brace `{` and closing brace `}`. This means outside the boundary of that block, the target local variable does not exist!
Take a look at the example below.
Example: creating local variables in Java
class Main{ public static void main(String[] args) { sMeth(); System.out.println(name); } public static void sMeth(){ String name = "John Doe"; System.out.println(name); } }
Output:
Main.java:5: error: cannot find symbol System.out.println(name);
In this example, we have two methods: `main` and `sMeth`. Inside the body of the `sMeth()` method we have one variable called `name`. Note that because this variable is defined inside the body of the `sMeth()` then it is local to this method only! This means we can access this variable anywhere within the boundary of the open brace `{` and the closing `}` brace of the `sMeth` method. But outside of this boundary, it’s like the variable does not exist at all!
That’s why we got error when we’ve tried to access the variable `name` in the body of the `main` method.
Difference between Parameter and Argument
In short, parameters are the local variables that we set for a method when that method needs input values in order to function correctly.
On the other hand, arguments are those values that we pass to a method in order to be assigned to the parameters of that method.