Unit 2: Using Objects
Mastering Java Methods for AP CSA
Introduction to Methods:
Definition and Purpose
- Definition: Named blocks of code designed to perform a specific task or computation. They are reusable and can be invoked from anywhere in the program. They are also known as functions or procedures in other programming languages.
- Purpose: Encapsulation, code reuse, modularization, and readability. Methods are used to break down a program into smaller, more manageable pieces. They also allow us to reuse code and avoid repetition.
Anatomy of a Method:
Method Header
- Access modifier (public, private, etc.).
- Return type (void for no return, or specific data types like int, double, etc.).
- Method name (should be a verb or action phrase, using camelCase).
- Parameters (variables passed into the method).
// method header right below public static ...
public static int add(int x, int y) {
// method body
}
Method Body
- Enclosed in curly braces { }.
- Contains statements to execute.
// method body right below method header
public static int add(int x, int y) {
// statements to execute are inside the method
// body between the curly braces
return x + y;
}
Method Declaration:
Static vs. Non-static
Static methods belong to the class rather than an instance of the class. They can be invoked using the class name. Non-static methods belong to an instance of the class. They can be invoked using an object reference.
- Static: Belongs to the class rather than an instance (static keyword).
- Non-static (or instance): Belongs to an instance of the class.
public class Person {
private String name;
private int age;
// static method
public static void sayHello() {
System.out.println("Hello!");
}
// non-static method
public void sayName() {
System.out.println("My name is " + name);
}
}
Parameters and Arguments
There is a subtle difference between parameters and arguments. Parameters are the variables listed in the method header. Arguments are the actual values passed into a method.
- Parameters: Variables listed in the method header.
- Arguments: Actual values passed into a method.
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
}
Method Overloading
Method overloading is the process of declaring multiple methods with the same name but different parameter lists. The return type does not differentiate overloaded methods. Overloaded methods must have different parameter lists.
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public Person(String name) {
this.name = name;
this.age = 0;
}
}
- Declaring multiple methods with the same name but different parameter lists.
- Return type does not differentiate overloaded methods.
- Overloaded methods must have different parameter lists.
Return Values:
The return Statement
The return statement is used to exit a method and optionally return a value. The method's declared return type must match the type of the value returned. The return statement can be used anywhere in the method body.
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public Person(String name) {
this.name = name;
this.age = 0;
}
public int getAge() {
return age;
}
}
- Used to exit a method and optionally return a value.
- The method's declared return type must match the type of the value returned.
- The return statement can be used anywhere in the method body.
Void Methods
A void method does not return a value. The void keyword is used in the method header to indicate that the method does not return a value.
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public Person(String name) {
this.name = name;
this.age = 0;
}
public void sayHello() {
System.out.println("Hello!");
}
}
- Do not return a value.
- Use the void keyword.
Method Invocation
Calling a Method
Calling a method executes the statements in the method body. The method name is followed by parentheses containing the arguments to pass into the method. The method invocation can be used as part of an expression.
For static methods: ClassName.methodName(arguments);
For instance methods: objectReference.methodName(arguments);
public class Person { private String name; private int age; public Person(String name, int age) { this.name = name; this.age = age; } public Person(String name) { this.name = name; this.age = 0; } public static void sayHello() { System.out.println("Hello!"); } public void sayName() { System.out.println("My name is " + name); } }
public class Main { public static void main(String[] args) { Person.sayHello(); Person p = new Person("John"); p.sayName(); } }
Pass-by-Value
Java uses pass-by-value for method parameters. For primitives, the value is passed. For objects, the reference value (memory address) is passed. This means that changes to the parameter variable do not affect the original variable. However, changes to the object's state do affect the original object.
- Java uses pass-by-value for method parameters.
- For primitives: The value is passed.
- For objects: The reference value (memory address) is passed.
- Changes to the parameter variable do not affect the original variable.
- Changes to the object's state do affect the original object.
The this Keyword
The this keyword refers to the current object. It is used to access instance variables and methods. It can also be used to call another constructor in the same class. The this keyword can be used in both static and non-static methods. It can also be used in constructors. It cannot be used in static contexts.
- Refers to the current object.
- Used to access instance variables and methods.
- Can be used to call another constructor in the same class.
- Can be used in both static and non-static methods.
- Can be used in constructors.
- Cannot be used in static contexts.
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public Person(String name) {
this(name, 0);
}
}
Recursive Methods
A recursive method is a method that calls itself. It must have a base case to avoid infinite recursion. Common examples include factorial and Fibonacci.
Recursive methods can be used to solve problems that can be broken down into smaller sub-problems. They can also be used to solve problems that can be solved using the same algorithm on smaller inputs.
A method that calls itself.
Must have a base case to avoid infinite recursion.
Common examples: Factorial, Fibonacci.
public class Main { public static void main(String[] args) { System.out.println(factorial(5)); System.out.println(fibonacci(10)); } public static int factorial(int n) { if (n == 0) { return 1; } else { return n * factorial(n - 1); } } public static int fibonacci(int n) { if (n == 0 || n == 1) { return n; } else { return fibonacci(n - 1) + fibonacci(n - 2); } } }
Access Modifiers
Access modifiers control the visibility of methods. There are four access modifiers in Java: public, private, protected, and package-private. The default access modifier is package-private. Access modifiers can be used to control access to methods and variables. They can also be used to control access to classes and interfaces.
- Public (public): Can be accessed from any other class.
- Private (private): Can only be accessed from within its own class.
- Protected (protected): Can be accessed within its own package and by subclasses.
- Package-private (no modifier): Accessible within its own package.
Method Comments (JavaDoc)
JavaDoc comments can be used to document methods. They are written above the method header. They should include the following information:
- Description of the method.
- Description of the parameters.
- Description of the return value.
- Description of any exceptions thrown.
/**
* Returns the sum of two integers.
*
* @param x the first integer
* @param y the second integer
* @return the sum of x and y
*/
public static int add(int x, int y) {
return x + y;
}
Varargs
Varargs allow a method to accept an arbitrary number of arguments of a specified type. They are declared using an ellipsis (...) after the parameter type. Varargs should be the last parameter in the method header.
- Allows a method to accept an arbitrary number of arguments of a specified type.
- Uses an ellipsis (...).
- Varargs should be the last parameter.
public static int sum(int... nums) {
int sum = 0;
for (int num : nums) {
sum += num;
}
return sum;
}
Summary
Methods in Java are named blocks of code designed to perform a specific task or computation. They are reusable and can be invoked from anywhere in the program.
Methods are declared using a header and a body.
The header contains the access modifier, return type, method name, and parameters.
The body contains the statements to execute.
Methods can be static or non-static.
Methods can be overloaded.
Methods can return a value using the return statement.
Methods can be invoked using the dot operator.
Java uses pass-by-value for method parameters.
The this keyword refers to the current object.
Recursive methods call themselves.
Access modifiers control the visibility of methods.
JavaDoc comments can be used to document methods.
Varargs allow a method to accept an arbitrary number of arguments of a specified type.
AP CSA Homework Assignment
Assignment
Instructions
Create a class called Calculator that contains the following methods:
- add: Takes two integers and returns their sum.
- subtract: Takes two integers and returns their difference.
- multiply: Takes two integers and returns their product.
- divide: Takes two integers and returns their quotient.
- power: Takes two integers and returns the first integer raised to the power of the second integer.
- factorial: Takes an integer and returns its factorial.
- fibonacci: Takes an integer and returns the nth Fibonacci number.