Java Class Methods
Functions that define what objects can do
⚙️ What are Class Methods?
Class methods are functions defined inside a class that specify what objects can do. Methods perform actions, process data, and interact with object attributes to provide functionality and behavior.
class Calculator {
int add(int a, int b) {
return a + b;
}
void displayResult(int result) {
System.out.println("Result: " + result);
}
}
Types of Methods
Return Methods
Methods that return a value
int getAge() {
return age;
}
Void Methods
Methods that don't return a value
void printName() {
System.out.println(name);
}
With Parameters
Methods that accept input
void setAge(int newAge) {
age = newAge;
}
No Parameters
Methods with no input
void sayHello() {
System.out.println("Hello!");
}
🔹 Basic Method Structure
Every method has a specific structure with different components:
// Method structure breakdown
public class MethodExample {
// Method with return type and parameters
public int multiply(int x, int y) {
int result = x * y;
return result;
}
// Void method with parameter
public void greet(String name) {
System.out.println("Hello, " + name + "!");
}
// Method with no parameters
public String getCurrentTime() {
return "Current time: 10:30 AM";
}
// Void method with no parameters
public void showMenu() {
System.out.println("=== MENU ===");
System.out.println("1. Add");
System.out.println("2. Subtract");
System.out.println("3. Exit");
}
}
Method Components:
- Access modifier: public, private, protected
- Return type: int, String, void, etc.
- Method name: descriptive name in camelCase
- Parameters: input values in parentheses
- Method body: code inside curly braces
🔹 Methods with Return Values
Methods can return values that can be used by the calling code:
// BankAccount.java
class BankAccount {
private double balance;
private String accountHolder;
// Constructor
public BankAccount(String holder, double initialBalance) {
accountHolder = holder;
balance = initialBalance;
}
// Method that returns current balance
public double getBalance() {
return balance;
}
// Method that returns account holder name
public String getAccountHolder() {
return accountHolder;
}
// Method that deposits money and returns new balance
public double deposit(double amount) {
if (amount > 0) {
balance += amount;
System.out.println("Deposited: $" + amount);
}
return balance;
}
// Method that withdraws money and returns success status
public boolean withdraw(double amount) {
if (amount > 0 && amount <= balance) {
balance -= amount;
System.out.println("Withdrawn: $" + amount);
return true;
} else {
System.out.println("Insufficient funds or invalid amount");
return false;
}
}
}
// BankExample.java
public class BankExample {
public static void main(String[] args) {
BankAccount account = new BankAccount("John Doe", 1000.0);
// Using methods that return values
System.out.println("Account Holder: " + account.getAccountHolder());
System.out.println("Initial Balance: $" + account.getBalance());
// Store returned values
double newBalance = account.deposit(250.0);
System.out.println("New Balance: $" + newBalance);
boolean success = account.withdraw(100.0);
System.out.println("Withdrawal successful: " + success);
System.out.println("Final Balance: $" + account.getBalance());
}
}
Output:
Account Holder: John Doe Initial Balance: $1000.0 Deposited: $250.0 New Balance: $1250.0 Withdrawn: $100.0 Withdrawal successful: true Final Balance: $1150.0
🔹 Void Methods
Void methods perform actions but don't return values:
// Robot.java
class Robot {
String name;
int batteryLevel;
boolean isOn;
// Constructor
public Robot(String robotName) {
name = robotName;
batteryLevel = 100;
isOn = false;
}
// Void method to turn on robot
public void turnOn() {
isOn = true;
System.out.println(name + " is now ON");
displayStatus();
}
// Void method to turn off robot
public void turnOff() {
isOn = false;
System.out.println(name + " is now OFF");
}
// Void method to display status
public void displayStatus() {
System.out.println("=== " + name + " Status ===");
System.out.println("Power: " + (isOn ? "ON" : "OFF"));
System.out.println("Battery: " + batteryLevel + "%");
}
// Void method with parameter
public void performTask(String task) {
if (isOn && batteryLevel > 10) {
System.out.println(name + " is performing: " + task);
batteryLevel -= 10;
System.out.println("Battery reduced to: " + batteryLevel + "%");
} else {
System.out.println(name + " cannot perform task. Check power/battery.");
}
}
// Void method to charge battery
public void charge() {
batteryLevel = 100;
System.out.println(name + " battery charged to 100%");
}
}
// RobotExample.java
public class RobotExample {
public static void main(String[] args) {
Robot robot = new Robot("R2D2");
robot.displayStatus();
robot.turnOn();
robot.performTask("Cleaning");
robot.performTask("Cooking");
robot.performTask("Dancing");
robot.charge();
robot.displayStatus();
robot.turnOff();
}
}
Output:
=== R2D2 Status === Power: OFF Battery: 100% R2D2 is now ON === R2D2 Status === Power: ON Battery: 100% R2D2 is performing: Cleaning Battery reduced to: 90% R2D2 is performing: Cooking Battery reduced to: 80% R2D2 is performing: Dancing Battery reduced to: 70% R2D2 battery charged to 100% === R2D2 Status === Power: ON Battery: 100% R2D2 is now OFF
🔹 Method Parameters
Methods can accept multiple parameters of different types:
// MathOperations.java
class MathOperations {
// Method with multiple parameters
public double calculateArea(double length, double width) {
return length * width;
}
// Method with different parameter types
public void printStudentInfo(String name, int age, double gpa, boolean isHonorStudent) {
System.out.println("=== Student Information ===");
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("GPA: " + gpa);
System.out.println("Honor Student: " + (isHonorStudent ? "Yes" : "No"));
}
// Method with array parameter
public double calculateAverage(int[] numbers) {
if (numbers.length == 0) return 0;
int sum = 0;
for (int num : numbers) {
sum += num;
}
return (double) sum / numbers.length;
}
// Method that uses parameters in calculations
public String generateReport(String studentName, int[] scores) {
double average = calculateAverage(scores);
String grade;
if (average >= 90) grade = "A";
else if (average >= 80) grade = "B";
else if (average >= 70) grade = "C";
else if (average >= 60) grade = "D";
else grade = "F";
return studentName + " - Average: " + average + ", Grade: " + grade;
}
}
// MathExample.java
public class MathExample {
public static void main(String[] args) {
MathOperations math = new MathOperations();
// Using method with multiple parameters
double area = math.calculateArea(5.5, 3.2);
System.out.println("Area: " + area);
// Using method with different parameter types
math.printStudentInfo("Alice Johnson", 20, 3.8, true);
// Using method with array parameter
int[] testScores = {85, 92, 78, 96, 88};
double average = math.calculateAverage(testScores);
System.out.println("Average score: " + average);
// Using method that combines other methods
String report = math.generateReport("Bob Smith", testScores);
System.out.println(report);
}
}
Output:
Area: 17.6 === Student Information === Name: Alice Johnson Age: 20 GPA: 3.8 Honor Student: Yes Average score: 87.8 Bob Smith - Average: 87.8, Grade: B
🔹 Method Best Practices
Naming Conventions:
- camelCase: calculateTotal, displayInfo
- Verbs: Methods should describe actions
- Descriptive: getName() not get()
Good Practices:
- Keep methods focused on one task
- Use meaningful parameter names
- Return appropriate data types
- Handle edge cases (null values, empty arrays)
- Use void for actions, return types for calculations