Methods, Arrays, and Program Structure
Parameters, Arguments, and Return Values
You are viewing a free preview lesson.
Lesson Overview
In the previous lesson, we learned how to declare and call basic methods.
Example:
static void greet() {
System.out.println("Welcome!");
}
However, this method always produces the same output.
In a real program, methods usually work with different data.
greet("Sakib");
greet("Subu");
greet("Sumu");
The same behavior can be reused with different input.
A method can also perform a calculation and return the result to its caller.
In this lesson, we will learn:
- Parameters
- Arguments
- Parameter types
- Multiple parameters
- Return values
- Return types
returnvoidvs. value-returning methods- Using returned values
- Early return
- Basic pass-by-value behavior
- Useful method signatures
Learning Objectives
After completing this lesson, you will be able to:
- Distinguish between parameters and arguments
- Pass input to a method
- Use multiple parameters
- Write value-returning methods
- Choose an appropriate return type
- Store and reuse returned values
- Understand the difference between
voidand value-returning methods - Use early return
- Understand return paths in non-
voidmethods - Design simple reusable method signatures
Why Do Methods Need Input?
Consider:
static void greet() {
System.out.println(
"Hello, Sakib!"
);
}
If we want to greet Subu:
Hello, Subu!
we could create another method:
static void greetSubu() {
System.out.println(
"Hello, Subu!"
);
}
But the behavior is the same.
Only the data changes:
Name
Therefore, the name should be an input to the method.
What Is a Parameter?
A parameter is a typed variable declared in a method declaration to receive input.
static void greet(
String name
) {
System.out.println(
"Hello, "
+ name
+ "!"
);
}
Here:
name
is the parameter.
And:
String
is its type.
What Is an Argument?
An argument is the actual value provided for a parameter when a method is called.
greet(
"Sakib"
);
Here:
"Sakib"
is the argument.
Parameter vs. Argument
Declaration:
static void greet(
String name
) {
}
name → parameter
Call:
greet(
"Sakib"
);
"Sakib" → argument
Simply:
Parameter → What input the method expects
Argument → What actual input is provided during the call
Different Arguments, Same Method
public class Main {
public static void main(String[] args) {
greet("Sakib");
greet("Subu");
greet("Sumu");
}
static void greet(
String name
) {
System.out.println(
"Hello, "
+ name
+ "!"
);
}
}
Output:
Hello, Sakib!
Hello, Subu!
Hello, Sumu!
One method has been reused with different data.
Parameters Have Types
Java is statically typed.
Therefore, every parameter has a type.
static void printAge(
int age
) {
System.out.println(age);
}
The method expects:
int
Valid:
printAge(30);
Invalid:
printAge("thirty");
because "thirty" is a String.
A Variable Can Be an Argument
An argument does not have to be a literal.
String learnerName =
"Sakib";
greet(
learnerName
);
The current value of learnerName is passed to the method.
An Expression Can Be an Argument
static void printTotal(
int total
) {
System.out.println(total);
}
Call:
printTotal(
10 + 20
);
The expression is evaluated first:
10 + 20 → 30
Then:
30
is passed to the method as the argument.
Multiple Parameters
A method can receive multiple inputs.
static void printCourse(
String title,
long priceInPaisa
) {
System.out.println(
title
+ " - "
+ priceInPaisa
);
}
Call:
printCourse(
"Java and OOP Foundation",
499_000L
);
Parameter Order Is Important
Declaration:
static void printProfile(
String name,
int age
) {
}
Correct:
printProfile(
"Sakib",
30
);
The values are mapped by position:
"Sakib" → name
30 → age
Wrong:
printProfile(
30,
"Sakib"
);
The types do not match the expected positions.
Be More Careful When Parameters Have the Same Type
static void printFullName(
String firstName,
String lastName
) {
System.out.println(
firstName
+ " "
+ lastName
);
}
Both of these calls compile:
printFullName(
"Samiul",
"Sakib"
);
printFullName(
"Sakib",
"Samiul"
);
Java cannot understand semantic intent from the types alone.
Therefore, clear parameter names and logical ordering are important.
Parameters Are Local Variables
A parameter can be used like a local variable inside its method.
static void greet(
String name
) {
System.out.println(name);
}
However, name is not available outside the method.
Each method call receives its own parameter value.
greet("Sakib");
greet("Jalisa");
First call:
name = "Sakib"
Second call:
name = "Jalisa"
What Is a Return Value?
Some methods only perform an action:
static void greet(
String name
) {
System.out.println(
"Hello, " + name
);
}
But some methods calculate a result and return it to the caller.
static int add(
int first,
int second
) {
return first + second;
}
This method returns an:
int
Return Type
The type before the method name tells us what type of value the method returns.
static int add(
int first,
int second
)
Here:
int
is the return type.
return
return first + second;
This does two things:
- Evaluates the expression
- Sends the result back to the caller
Example:
int result =
add(
10,
20
);
System.out.println(result);
Output:
30
Returning Different Types
int
static int getAge() {
return 30;
}
String
static String createGreeting(
String name
) {
return "Hello, "
+ name
+ "!";
}
boolean
static boolean isAdult(
int age
) {
return age >= 18;
}
long
static long calculateTotal(
long priceInPaisa,
int quantity
) {
return priceInPaisa
* quantity;
}
Return Type and Returned Value Must Be Compatible
Valid:
static int getAge() {
return 30;
}
Invalid:
static int getAge() {
return "thirty";
}
The method promises:
int
but the returned value is:
String
Therefore, the code does not compile.
Storing a Returned Value
int total =
add(
10,
20
);
Now:
total = 30
Using a Returned Value Directly
System.out.println(
add(
5,
7
)
);
Output:
12
The method call acts as its returned value within the expression.
Using a Returned Value in a Condition
if (
isAdult(20)
) {
System.out.println(
"Adult"
);
}
isAdult(20) evaluates and returns:
true
A Returned Value Can Be an Argument to Another Method
static int doubleValue(
int value
) {
return value * 2;
}
static void printNumber(
int number
) {
System.out.println(number);
}
Call:
printNumber(
doubleValue(10)
);
Flow:
doubleValue(10)
↓
20
↓
printNumber(20)
Output:
20
Method Calls Can Be Composed
static int add(
int first,
int second
) {
return first + second;
}
static int multiply(
int first,
int second
) {
return first * second;
}
Usage:
int result =
multiply(
add(2, 3),
4
);
Evaluation:
add(2, 3)
→ 5
multiply(5, 4)
→ 20
void vs. Returning Method
Action method:
static void printTotal(
int first,
int second
) {
System.out.println(
first + second
);
}
Value-returning method:
static int calculateTotal(
int first,
int second
) {
return first + second;
}
Difference
The first method:
prints the result
The second method:
returns the result to the caller
A returning method is generally more flexible for calculations.
Why Is Returning a Calculation Useful?
static long calculateTotal(
long priceInPaisa,
int quantity
) {
return priceInPaisa
* quantity;
}
The caller can print the result:
long total =
calculateTotal(
499_000L,
2
);
System.out.println(total);
It can also use the result in a condition:
if (total > 500_000L) {
System.out.println(
"Large order"
);
}
The calculation method itself does not decide how the result should be displayed.
return Ends Method Execution
static int getNumber() {
return 10;
}
When return executes, the current method invocation ends immediately.
A statement cannot be written after an unconditional return:
static int getNumber() {
return 10;
System.out.println("Hello");
}
The final statement is unreachable.
Early Return
return can also exit from the middle of a method.
static void printAge(
int age
) {
if (age < 0) {
System.out.println(
"Invalid age"
);
return;
}
System.out.println(
"Age: " + age
);
}
If age < 0, the method ends at that point.
Early Return with a Value
static String classifyAge(
int age
) {
if (age < 0) {
return "Invalid";
}
if (age < 18) {
return "Minor";
}
return "Adult";
}
Examples:
classifyAge(-1);
returns:
Invalid
classifyAge(15);
returns:
Minor
classifyAge(30);
returns:
Adult
Every Path in a Non-void Method Must Return a Value
Invalid:
static String getResult(
boolean passed
) {
if (passed) {
return "Passed";
}
}
If passed == false, no value is returned.
Correct:
static String getResult(
boolean passed
) {
if (passed) {
return "Passed";
}
return "Failed";
}
Basic Pass-by-Value
When a Java method is called, the argument's value is provided to the parameter.
Primitive example:
static void changeNumber(
int number
) {
number = 100;
}
Caller:
int value = 10;
changeNumber(value);
System.out.println(value);
Output:
10
The method parameter:
number
receives its own local value.
Changing that value does not change the caller's:
value
variable.
We will study how this rule works with objects and references in more detail when we learn about objects.
Useful Method Signature
Look at this method:
static long calculateTotal(
long priceInPaisa,
int quantity
)
From the signature, we can understand:
Method name → calculateTotal
Input → priceInPaisa, quantity
Output → long
The method signature communicates the intent of the code.
Parameters Should Represent Only Necessary Input
Good:
static long calculateTotal(
long priceInPaisa,
int quantity
) {
return priceInPaisa
* quantity;
}
The required input is visible in the method call.
Meaningful Method and Parameter Names
Good:
static boolean canEnroll(
boolean coursePublished,
boolean alreadyEnrolled
)
Weak:
static boolean check(
boolean a,
boolean b
)
Names help make the code understandable.
Complete Example
public class Main {
public static void main(String[] args) {
long total =
calculateTotal(
499_000L,
2
);
boolean largeOrder =
isLargeOrder(
total
);
String message =
createOrderMessage(
total,
largeOrder
);
System.out.println(
message
);
}
static long calculateTotal(
long priceInPaisa,
int quantity
) {
return priceInPaisa
* quantity;
}
static boolean isLargeOrder(
long total
) {
return total > 500_000L;
}
static String createOrderMessage(
long total,
boolean largeOrder
) {
if (largeOrder) {
return "Large order: "
+ total;
}
return "Order total: "
+ total;
}
}
Output:
Large order: 998000
Here, every method has clear input and output.
Common Mistakes
Not Providing a Required Argument
Declaration:
static void greet(
String name
) {
}
Wrong:
greet();
Correct:
greet("Sakib");
Too Many Arguments
Declaration:
static void greet(
String name
) {
}
Wrong:
greet(
"Sakib",
"Subu"
);
Wrong Argument Type
static void printAge(
int age
) {
}
Wrong:
printAge("30");
Correct:
printAge(30);
Wrong Argument Order
static void printProfile(
String name,
int age
) {
}
Wrong:
printProfile(
30,
"Sakib"
);
Not Returning a Value from a Non-void Method
Wrong:
static int calculate() {
System.out.println(
"Calculating"
);
}
The method promises an int, so it must return a compatible value.
Wrong Return Type
Wrong:
static boolean isAdult(
int age
) {
return "yes";
}
Returning a Value from a void Method
Wrong:
static void calculate() {
return 10;
}
A void method cannot return a value.
Ignoring a Returned Value
Legal:
calculateTotal(
100,
5
);
However, if the method only returns a result, that value is immediately discarded.
Usually:
long total =
calculateTotal(
100,
5
);
Important Terms
Parameter
A typed input variable declared in a method declaration.
Argument
The actual value or expression provided during a method call.
Return Type
The type of value a method produces.
Return Value
The actual result returned by the method to the caller.
return
Ends the current method invocation and, when needed, sends a result back to the caller.
Method Signature
The method's name and parameter structure, which help describe the method call contract.
Practice Exercise 1: Greeting
Create:
static void greet(
String name
)
that prints:
Hello, <name>!
Call it with three different names.
Practice Exercise 2: Add Two Numbers
Create:
static int add(
int first,
int second
)
Return the sum of the two numbers.
Practice Exercise 3: Rectangle Area
Create:
static int calculateArea(
int width,
int height
)
Example:
calculateArea(5, 4)
returns:
20
Practice Exercise 4: Adult Check
Create:
static boolean isAdult(
int age
)
Return true if age is 18 or above.
Practice Exercise 5: Largest Number
Create:
static int max(
int first,
int second
)
Do not use Math.max().
Practice Exercise 6: Score Classification
Create:
static String classifyScore(
int score
)
Rules:
Below 0 or above 100 → Invalid
90+ → Excellent
70+ → Good
Otherwise → Needs Improvement
Practice Exercise 7: Predict the Output
public class Main {
public static void main(String[] args) {
int value =
multiply(
add(2, 3),
4
);
System.out.println(value);
}
static int add(
int first,
int second
) {
return first + second;
}
static int multiply(
int first,
int second
) {
return first * second;
}
}
What will the output be?
Knowledge Check
Question 1
What is a parameter?
Question 2
What is an argument?
Question 3
What is the difference between a parameter and an argument?
Question 4
Why do parameters make a method reusable?
Question 5
Why does a parameter need a type?
Question 6
What does the return type tell us?
Question 7
What does return do?
Question 8
What is the difference between void and an int return type?
Question 9
Can a returned value be stored in a variable?
Question 10
Can a returned value be used as an argument to another method?
Question 11
What happens to a method when return executes?
Question 12
What is required from every possible path in a non-void method?
Question 13
If a primitive argument is changed through the method parameter, does the caller variable automatically change?
Question 14
Why are meaningful method and parameter names important?
Knowledge Check Answers
Answer 1
A typed variable declared in a method declaration that receives input from a method call.
Answer 2
The actual value or expression provided for a parameter when a method is called.
Answer 3
A parameter is part of the method declaration. An argument is the actual input supplied during the call.
Answer 4
The same method can work with different input values.
Answer 5
Java is statically typed, so the method needs to know what kind of input it accepts.
Answer 6
It tells us what type of value the method returns to the caller.
Answer 7
It ends the current method invocation and, for a value-returning method, sends the result back to the caller.
Answer 8
A void method does not return a result value. An int method returns an integer-compatible value.
Answer 9
Yes.
Answer 10
Yes.
Answer 11
The current method invocation ends immediately, and execution returns to the caller.
Answer 12
A compatible return value.
Answer 13
No.
Answer 14
They help the reader understand what the method does and what each input means by looking at the signature.
Lesson Summary
In this lesson, we learned:
- Parameters define a method's inputs
- Arguments are the actual inputs provided in a method call
- Every parameter has a Java type
- Argument count, order, and type must match the method declaration
- A method can receive multiple parameters
- Parameters are local variables of the method
- A method can return a result to its caller
- The return type defines the type of returned value
returnsends a result and ends method execution- A
voidmethod does not return a result value - Returned values can be used in variables, conditions, or other method calls
- Returning calculation results makes methods more reusable
- Early return can end a method based on a condition
- Every possible execution path in a non-
voidmethod must return a compatible value - Primitive argument values are passed to parameters; reassigning the parameter does not change the caller variable
- Clear method and parameter names help create useful method signatures