Lesson 5 | Declaring methods |
Objective | Describe how methods are declared. |
Declaring Methods in Java
Purpose of Methods in Java
In Java, methods are blocks of code designed to perform specific tasks. They allow for code reusability, modularity, and better organization in programs. The primary purposes of methods are:
- Code Reusability: Once a method is defined, it can be called (invoked) multiple times, reducing the need for redundant code.
- Modularity: Methods help break the program into smaller, manageable parts. This makes the program easier to read, understand, and maintain.
- Encapsulation: Methods allow you to hide the implementation details of a specific task while exposing only the method's name and its input/output (i.e., parameters and return values).
- Logic Organization: You can organize the logic of your program by grouping related functionalities into methods, making the code more structured.
Method Declaration in Java
A method in Java is declared with the following syntax:
[modifier] returnType methodName([parameters]) {
// method body
// code to execute
}
- Modifier: Specifies the access level (e.g., `public`, `private`, `protected`) and whether the method is `static` or instance-based.
- Return Type: Specifies the type of value the method returns. If the method does not return any value, you use the `void` keyword.
- Method Name: The name of the method (should be a valid identifier in Java).
- Parameters: The input values (if any) passed into the method. These are optional.
- Method Body: The block of code that defines what the method does.
Example:
Here's an example of how methods are declared and used in Java:
public class Example {
public static void main(String[] args) {
// Calling the method to greet the user
greetUser();
// Calling a method that adds two numbers and returns the result
int sum = addNumbers(5, 10);
System.out.println("The sum is: " + sum);
}
// Method with no return value (void) that prints a message
public static void greetUser() {
System.out.println("Hello, User!");
}
// Method that takes two parameters and returns their sum
public static int addNumbers(int num1, int num2) {
int result = num1 + num2; // Local variable
return result; // Returning the sum
}
}
Key Points:
- Method Call: Methods are invoked by using the method name followed by parentheses (`methodName()`).
- Parameters: You can pass values to methods when calling them. In the `addNumbers` method, two integers are passed as arguments.
- Return Value: If a method has a return type (other than `void`), it must return a value of that type using the `return` statement. In the `addNumbers` method, an `int` value is returned.
Benefits:
- Encapsulation: You can hide the implementation of certain functionalities inside methods.
- Reusability: Methods can be used multiple times throughout the code, making it more efficient and easier to maintain.
Let me know if you'd like more clarification on any part of this!
Recommended method for creating a variable within a Java function
In Java, to create a variable within a function, you simply declare the variable inside the function's body. This type of variable is called a local variable because it is local to the function and can only be used within that function. Here is the recommended method for creating a local variable inside a function:
- Declare the variable with a type: You need to specify the data type of the variable when declaring it (e.g., `int`, `String`, `boolean`, etc.).
- Optionally, initialize the variable: You can assign a value to the variable at the time of declaration.
Example:
public class Example {
public static void main(String[] args) {
printSum(5, 10); // Calls the function with two arguments
}
// Function that creates and uses local variables
public static void printSum(int a, int b) {
int sum = a + b; // Local variable
System.out.println("The sum is: " + sum);
}
}
Key points:
- Scope: Local variables are only accessible within the function in which they are declared.
- Lifetime: These variables are created when the function is called and destroyed once the function exits.
- Initialization: Local variables must be initialized before they are used, as Java does not automatically initialize them to default values like instance variables.
How do I declare a method in Java
To declare a method in Java, you will need to specify the following:
- The access level (e.g., public, private). This determines who can access the method.
- The return type of the method (e.g., int, String). This is the type of value that the method will return. If the method does not return a value, you can use the keyword void.
- The name of the method (e.g., calculateSum). The name should be descriptive and follow Java's naming conventions.
- A list of parameters (optional). These are the values that will be passed to the method when it is called. Each parameter consists of a type and a name.
- The method body. This is the code that will be executed when the method is called.
Here is an example of a method declaration in Java:
public int calculateSum(int a, int b) {
int sum = a + b;
return sum;
}
This method is called calculateSum, it is public (so it can be accessed from anywhere in the program), and it takes two integer parameters (a and b). It returns an integer value, which is the sum of a and b.
Method Modifiers
Method modifiers are
abstract
,
final
,
native
,
private
,
protected
,
public
,
static
,
- or
synchronized
.
The following page contains a list of
atomic Methods in the
java.util.concurrent.atomic
package. They are covered later in this module. The return type of a method may be a primitive type, object type, array type, or
void
(no value is returned). A method's parameter list is a comma-separated list of parameter declarations of the form
modifier type identifier. A parameter may specify the
final
modifier, which indicates that the parameter may not be modified within the method body and may be accessed from a local inner class. The method name and its parameter list make up a
method signature[1].
A method's
throws
clause consists of a comma-separated list of class names (all of which extend
Throwable
). If an uncaught exception is thrown by a method then it must be declared in the method's
throws
clause. (Refer to Module 6. )
Passing arguments
When an argument is passed to a method, the argument's value is copied before being made available to the method via a parameter.
Any changes to the value of the parameter that occur during the method's execution do not affect the variable used as an argument.
However, if an object is passed as an argument to a method, the reference to the object is not modified as the result of the method call (since the value of the object reference is copied), but the object itself may be modified (because only the reference is copied, not the object itself).
The Java argument program demonstrates this point.
Java Argument program
The
Argument
program illustrates the effects of argument passing. It displays the following results:
10
abcdef
The value of
i
is not changed by the
increment()
method. Neither is the value of
s
. It still refers to the same
StringBuffer
object. However, the
StringBuffer
object referenced by
s
was updated.
class Argument {
public static void main(String[] args) {
new Argument();
}
Argument() {
int i = 10;
increment(i, 100);
System.out.println(i);
StringBuffer s = new StringBuffer("abc");
append(s, "def");
System.out.println(s);
}
void increment(int n, int m) {
n += m;
}
void append(StringBuffer s1, String s2) {
s1.append(s2);
s1 = new StringBuffer("xyz");
}
}
class Phone {
double weight;
void setWeight(double val) {
weight =val;
}
double getWeight() {
return weight;
}
}
If a method does not return a value, you cannot assign the result of that method to a variable.
[1]
Method signature: The name of the method and the number and types of formal parameters to the method.