Parameters are a fundamental concept in Java that allows for flexible and reusable code. In this blog, we'll explore the basics of parameters, their types, and how they're used in methods and constructors.
What are Parameters?
Parameters are variables defined inside the parentheses ()
of a method or constructor. They act as placeholders that receive values, known as arguments, when the method or constructor is called.
Types of Parameters
There are two primary types of parameters:
-
Formal Parameters: These are defined in the method or constructor declaration. For example,
int a
andint b
inadd(int a, int b)
are formal parameters. -
Actual Parameters (Arguments): These are the values passed when calling the method or constructor. For example,
5
and3
inadd(5, 3)
are actual parameters.
Example Program with Parameters
Let's consider an example program that demonstrates the use of parameters in a Type
class:
class Type {
int num1;
int num2;
int num3;
Type(int x, int y, int z) {
num1 = x;
num2 = y;
num3 = z;
}
// Methods for calculations
int addTwo() {
return num1 + num2;
}
int addThree() {
return num1 + num2 + num3;
}
// Other methods...
void displayDetails() {
System.out.println("Numbers: " + num1 + " , " + num2 + " , " + num3);
System.out.println("Add num1 + num2 = " + addTwo());
System.out.println("Add num1 + num2 + num3 = " + addThree());
// Other calculations...
}
}
public class Calculator1 {
public static void main(String args[]) {
Type t1 = new Type(20, 30, 60);
t1.displayDetails();
}
}
Output:
Numbers: 20 , 30 , 60
Add num1 + num2 = 50
Add num1 + num2 + num3 = 110
Sub num1 - num2 = -10
Sub num1 - num2 - num3 = -70
Multi num1 * num2 = 600
Multi num1 * num2 * num3 = 36000
Div num1 / num2 = 0
Div num1 / num2 / num3 = 0
Modulus num1 % num2 = 20
Modulus num1 % num2 % num3 = 20
Key Learning Points
- Parameters enable code reusability by allowing you to pass values instead of hardcoding them.
- Constructor parameters initialize object data.
- Method parameters are used for calculations and operations.
- Division '/' with integers gives only the quotient (no decimal).
- Modulus '%' gives the remainder.
By understanding parameters and how to use them effectively, you can write more flexible and reusable code in Java.
Top comments (0)