Methods and Parameters
💻 JavaBreak programs into small methods with clear inputs and outputs.
A method names a piece of work. Good methods are short, do one thing and make the calling code read like a sentence.
- Define and call methods.
- Pass parameters and return values.
- Overload methods.
Defining a Method
A method declares its return type, name and parameters. Use void when nothing is returned.
public class Maths {
static int add(int a, int b) {
return a + b;
}
static void greet(String name) {
System.out.println("Hello, " + name);
}
public static void main(String[] args) {
System.out.println(add(3, 4));
greet("Amina");
}
}Parameters and Arguments
Parameters are the names in the method definition. Arguments are the values passed at the call site. Java passes primitives by value.
Overloading
Several methods can share a name if their parameter lists differ. The compiler chooses the matching one.
static int area(int side) {
return side * side;
}
static double area(double length, double width) {
return length * width;
}Practice
- Write a method that returns the larger of two numbers.
- Write a void method that prints a separator line.
- Overload a greet method for one name and for two names.
Hands-on exercise
Write a method grade(int score) that returns:
A for 70 or more, B for 60 to 69, C for 50 to 59, otherwise F.
Call it with 72, 64 and 41 and print each result.
Recap
Methods name work, take parameters and return results. Keep them short and give them honest names.
Example
public class Maths {
static int add(int a, int b) {
return a + b;
}
static void greet(String name) {
System.out.println("Hello, " + name);
}
public static void main(String[] args) {
System.out.println(add(3, 4));
greet("Amina");
}
}
Exercises
A for 70 or more, B for 60 to 69, C for 50 to 59, otherwise F.
Call it with 72, 64 and 41 and print each result.
Expected Output
A
B
F
Lesson Nav
Java Course
0/9 lessons completed
- 1 Getting Started with Java Tutorial
- 2 Variables and Data Types Tutorial
- 3 Conditions and Loops Tutorial
- 4 Methods and Parameters Tutorial
- 5 Arrays and ArrayLists Tutorial
- 6 Classes and Objects Tutorial
- 7 Inheritance, Interfaces and Polymorphism Tutorial
- 8 Exceptions and Files Tutorial
- 9 Project: A Console Grade Book Project