0% found this document useful (0 votes)
2 views7 pages

Java Methods: Types and Best Practices

Method declaration, variable access, instance & static variable

Uploaded by

sv21101999
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views7 pages

Java Methods: Types and Best Practices

Method declaration, variable access, instance & static variable

Uploaded by

sv21101999
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Methods

A method in Java is a collection of statements that are grouped together to perform a


specific operation. It's a fundamental building block of Java programs that promotes
code reusability and organization.

Method Components in Java


Let's examine each part with Java examples:
Method Name
• Should be a verb that describes what the method does
• Follows camelCase convention
Access Modifier
• public - accessible from any other class
• private - accessible only within its own class
• protected - accessible within package and subclasses
• (default) - accessible only within the same package
Return Type
• The data type of the value the method returns
• Use void if the method doesn't return anything
Parameters
• Input values the method needs to work with
• Specified as data type followed by parameter name

3. Types of Methods with Examples


1. No Parameters, No Return Value (void)
java
public class Printer {
// Method definition
public void printWelcome() {
[Link]("Welcome to Java Programming!");
[Link]("Enjoy learning methods!");
}
}
2. With Parameters, No Return Value
java
public class Calculator {
public void printSum(int num1, int num2) {
int sum = num1 + num2;
[Link]("The sum is: " + sum);
}
}
3. With Parameters and Return Value
java
public class MathOperations {
// Method that takes parameters and returns a value
public int multiply(int a, int b) {
return a * b;
}

public double calculateArea(double radius) {


return [Link] * radius * radius;
}
}
4. No Parameters, With Return Value
java
public class DataProvider {
public String getCurrentDate() {
return [Link]().toString();
}
}
4. How to Use Methods - The Complete Picture
Step 1: Define the Method (inside a class)
java
public class BankAccount {
private double balance;

// Constructor
public BankAccount(double initialBalance) {
[Link] = initialBalance;
}

// Method to deposit money


public void deposit(double amount) {
if (amount > 0) {
balance += amount;
[Link]("Deposited: $" + amount);
}
}

// Method to withdraw money


public boolean withdraw(double amount) {
if (amount > 0 && amount <= balance) {
balance -= amount;
[Link]("Withdrawn: $" + amount);
return true; // successful withdrawal
}
[Link]("Insufficient funds!");
return false; // failed withdrawal
}

// Method to check balance


public double getBalance() {
return balance;
}
}
Step 2: Call the Method (from another class or main method)
java
public class Main {
public static void main(String[] args) {
// Create an object of BankAccount
BankAccount myAccount = new BankAccount(1000.0);

// Calling methods on the object


[Link](500.0); // Method call 1
boolean success = [Link](200.0); // Method call 2
double currentBalance = [Link](); // Method call 3

[Link]("Current balance: $" + currentBalance);


[Link]("Withdrawal successful: " + success);
}
}
Output:
text
Deposited: $500.0
Withdrawn: $200.0
Current balance: $1300.0
Withdrawal successful: true
5. Special Types of Methods in Java
Static Methods
• Belong to the class rather than any object
• Called using class name instead of object
java
public class MathUtils {
// Static method
public static int findMax(int a, int b) {
return (a > b) ? a : b;
}

public static double convertCelsiusToFahrenheit(double celsius) {


return (celsius * 9/5) + 32;
}
}

// Usage without creating an object


public class Main {
public static void main(String[] args) {
int max = [Link](10, 20);
double fahrenheit = [Link](25.0);

[Link]("Max: " + max); // Output: Max: 20


[Link]("Temperature: " + fahrenheit + "°F"); // Output: Temperature:
77.0°F
}
}
Method Overloading
• Multiple methods with same name but different parameters
java
public class Calculator {
// Overloaded methods
public int add(int a, int b) {
return a + b;
}

public double add(double a, double b) {


return a + b;
}

public int add(int a, int b, int c) {


return a + b + c;
}
}

// Usage
Calculator calc = new Calculator();
[Link]([Link](5, 10)); // Calls first method
[Link]([Link](5.5, 2.3)); // Calls second method
[Link]([Link](1, 2, 3)); // Calls third method

6. Best Practices for Java Methods


1. Single Responsibility: Each method should do one specific task
2. Descriptive Names: Use verbs that describe the action
(calculateTotal, validateInput)
3. Reasonable Length: Keep methods short and focused
4. Proper Parameter Validation: Check inputs at the beginning
5. Clear Documentation: Use JavaDoc comments
java
/**
* Calculates the factorial of a given number
* @param n the number to calculate factorial for (must be non-negative)
* @return the factorial of the given number
* @throws IllegalArgumentException if n is negative
*/
public static long factorial(int n) {
if (n < 0) {
throw new IllegalArgumentException("Number must be non-negative");
}

long result = 1;
for (int i = 1; i <= n; i++) {
result *= i;
}
return result;
}

You might also like