X Tutup
Skip to content

Latest commit

 

History

History
534 lines (416 loc) · 13.2 KB

File metadata and controls

534 lines (416 loc) · 13.2 KB

Understanding Methods in Java

Now that you understand classes and objects, let’s dive deeper into methods - the actions that objects can perform. Methods are like mini-programs inside your classes that do specific tasks.

What is a Method?

A method is a block of code that performs a specific task. Think of methods as the "verbs" of your program - they represent actions that can be performed.

Just like in real life:

  • A Person can walk(), talk(), or sleep()

  • A Car can start(), accelerate(), or brake()

  • A Calculator can add(), subtract(), or divide()

Methods help you:

  1. Organize code into logical chunks

  2. Reuse code instead of writing the same thing multiple times

  3. Break down complex problems into smaller, manageable pieces

  4. Make code easier to read and understand

Method Basics

Here’s the basic structure of a method:

public static returnType methodName(parameters) {
    // Code that does something
    return value; // if the method returns something
}

Let’s break this down:

  • returnType - What type of data the method gives back (or void if it gives back nothing)

  • methodName - What you want to call your method

  • parameters - Input values the method needs to do its work

  • return - Sends a value back to whoever called the method

  • public static - Special keywords we’ll explain later (for now, just include them)

Simple Method Examples

Let’s start with some basic methods you can try in jshell:

Methods that Don’t Return Anything (void methods)

Some methods just perform actions without giving anything back. These are called "void" methods because they return nothing - they just do something like printing text or changing data.

jshell> public static void sayHello() {
   ...>     System.out.println("Hello there!");
   ...> }
|  created method sayHello()

jshell> sayHello();
Hello there!
jshell> public static void printBorder() {
   ...>     System.out.println("========================");
   ...> }
|  created method printBorder()

jshell> printBorder();
========================

Methods with Parameters

Parameters let you pass information into your methods:

jshell> public static void greetPerson(String name) {
   ...>     System.out.println("Hello, " + name + "!");
   ...> }
|  created method greetPerson(String)

jshell> greetPerson("Alice");
Hello, Alice!

jshell> greetPerson("Bob");
Hello, Bob!
jshell> public static void printSquare(int size) {
   ...>     for (int i = 0; i < size; i++) {
   ...>         for (int j = 0; j < size; j++) {
   ...>             System.out.print("* ");
   ...>         }
   ...>         System.out.println();
   ...>     }
   ...> }
|  created method printSquare(int)

jshell> printSquare(3);
* * *
* * *
* * *

Methods that Return Values

Many methods calculate something and give you back the result:

jshell> public static int add(int a, int b) {
   ...>     return a + b;
   ...> }
|  created method add(int,int)

jshell> int result = add(5, 3);
result ==> 8

jshell> System.out.println("5 + 3 = " + result);
5 + 3 = 8
jshell> public static double calculateCircleArea(double radius) {
   ...>     return 3.14159 * radius * radius;
   ...> }
|  created method calculateCircleArea(double)

jshell> double area = calculateCircleArea(5.0);
area ==> 78.53975

jshell> System.out.println("Area of circle with radius 5: " + area);
Area of circle with radius 5: 78.53975

Methods in Classes

Remember our classes from the previous section? Methods inside classes can work with the object’s data (instance variables):

jshell> class BankAccount {
   ...>     String accountNumber;
   ...>     String ownerName;
   ...>     double balance;
   ...>
   ...>     void deposit(double amount) {
   ...>         balance = balance + amount;
   ...>         System.out.println("Deposited $" + amount);
   ...>         System.out.println("New balance: $" + balance);
   ...>     }
   ...>
   ...>     void withdraw(double amount) {
   ...>         if (amount <= balance) {
   ...>             balance = balance - amount;
   ...>             System.out.println("Withdrew $" + amount);
   ...>             System.out.println("New balance: $" + balance);
   ...>         } else {
   ...>             System.out.println("Insufficient funds!");
   ...>         }
   ...>     }
   ...>
   ...>     double getBalance() {
   ...>         return balance;
   ...>     }
   ...> }
|  created class BankAccount

jshell> BankAccount account = new BankAccount();
account ==> BankAccount@...

jshell> account.ownerName = "Sarah";
account.ownerName ==> "Sarah"

jshell> account.balance = 100.0;
account.balance ==> 100.0

jshell> account.deposit(50.0);
Deposited $50.0
New balance: $150.0

jshell> account.withdraw(25.0);
Withdrew $25.0
New balance: $125.0

jshell> double currentBalance = account.getBalance();
currentBalance ==> 125.0

Method Parameters in Detail

Methods can take different types and numbers of parameters:

Single Parameter

Parameters let you pass information into a method. With a single parameter, your method can work with different values each time:

jshell> public static int square(int number) {
   ...>     return number * number;
   ...> }
|  created method square(int)

jshell> square(4);
$1 ==> 16

Multiple Parameters

When your method needs more than one piece of information, you can pass multiple parameters separated by commas:

jshell> public static int multiply(int a, int b) {
   ...>     return a * b;
   ...> }
|  created method multiply(int,int)

jshell> multiply(6, 7);
$2 ==> 42

Different Parameter Types

Methods can accept different types of parameters in the same method. This lets you work with text, numbers, and other data types together:

jshell> public static void introduce(String name, int age, double height) {
   ...>     System.out.println("Name: " + name);
   ...>     System.out.println("Age: " + age);
   ...>     System.out.println("Height: " + height + " feet");
   ...> }
|  created method introduce(String,int,double)

jshell> introduce("Alex", 25, 5.8);
Name: Alex
Age: 25
Height: 5.8 feet

Return Values Explained

Programming is all about moving data around and transforming it. Methods do calculations and then need a way to give back their results. This is where return values come in.

When a method returns a resulting value, you can:

Store it in a variable:

jshell> public static String getFullName(String first, String last) {
   ...>     return first + " " + last;
   ...> }
|  created method getFullName(String,String)

jshell> String name = getFullName("John", "Smith");
name ==> "John Smith"

Use it directly in expressions:

jshell> System.out.println("Hello, " + getFullName("Jane", "Doe"));
Hello, Jane Doe

Use it in calculations:

jshell> public static int getAge() {
   ...>     return 25;
   ...> }
|  created method getAge()

jshell> int ageInMonths = getAge() * 12;
ageInMonths ==> 300

Methods with Conditional Logic

Methods often need to make decisions based on the data they receive. This is where if statements become very useful:

jshell> public static String checkGrade(int score) {
   ...>     if (score >= 90) {
   ...>         return "A";
   ...>     } else if (score >= 80) {
   ...>         return "B";
   ...>     } else if (score >= 70) {
   ...>         return "C";
   ...>     } else if (score >= 60) {
   ...>         return "D";
   ...>     } else {
   ...>         return "F";
   ...>     }
   ...> }
|  created method checkGrade(int)

jshell> checkGrade(85);
$3 ==> "B"

jshell> checkGrade(92);
$4 ==> "A"

jshell> checkGrade(55);
$5 ==> "F"

Practical Example: A Complete Class with Methods

Let’s create a Student class that demonstrates various types of methods:

jshell> class Student {
   ...>     String name;
   ...>     int grade;
   ...>     double[] testScores;
   ...>     int numTests;
   ...>
   ...>     Student(String studentName) {
   ...>         name = studentName;
   ...>         grade = 0;
   ...>         testScores = new double[10]; // can store up to 10 test scores
   ...>         numTests = 0;
   ...>     }
   ...>
   ...>     void addTestScore(double score) {
   ...>         if (numTests < testScores.length) {
   ...>             testScores[numTests] = score;
   ...>             numTests++;
   ...>             System.out.println("Added test score: " + score);
   ...>         } else {
   ...>             System.out.println("Cannot add more test scores!");
   ...>         }
   ...>     }
   ...>
   ...>     double calculateAverage() {
   ...>         if (numTests == 0) {
   ...>             return 0.0;
   ...>         }
   ...>
   ...>         double sum = 0.0;
   ...>         for (int i = 0; i < numTests; i++) {
   ...>             sum += testScores[i];
   ...>         }
   ...>         return sum / numTests;
   ...>     }
   ...>
   ...>     String getLetterGrade() {
   ...>         double average = calculateAverage();
   ...>         if (average >= 90) return "A";
   ...>         else if (average >= 80) return "B";
   ...>         else if (average >= 70) return "C";
   ...>         else if (average >= 60) return "D";
   ...>         else return "F";
   ...>     }
   ...>
   ...>     void printReport() {
   ...>         System.out.println("Student: " + name);
   ...>         System.out.println("Number of tests: " + numTests);
   ...>         System.out.println("Average: " + calculateAverage());
   ...>         System.out.println("Letter grade: " + getLetterGrade());
   ...>     }
   ...> }
|  created class Student

jshell> Student alice = new Student("Alice Johnson");
alice ==> Student@...

jshell> alice.addTestScore(85.0);
Added test score: 85.0

jshell> alice.addTestScore(92.0);
Added test score: 92.0

jshell> alice.addTestScore(78.0);
Added test score: 78.0

jshell> alice.printReport();
Student: Alice Johnson
Number of tests: 3
Average: 85.0
Letter grade: B

Method Naming Best Practices

Choose clear, descriptive names for your methods:

Good method names:

  • calculateArea()

  • getUserInput()

  • validateEmail()

  • printReport()

  • isEven()

Poor method names:

  • doStuff()

  • method1()

  • calc()

  • x()

Common Method Patterns

Validation Methods

Validation methods check if something is true or false. They’re very useful for making decisions in your programs:

jshell> public static boolean isEven(int number) {
   ...>     return number % 2 == 0;
   ...> }
|  created method isEven(int)

jshell> isEven(4);
$6 ==> true

jshell> isEven(7);
$7 ==> false

Utility Methods

Utility methods are helpful functions you can reuse throughout your program. They handle common tasks like calculations or conversions:

jshell> public static double convertCelsiusToFahrenheit(double celsius) {
   ...>     return (celsius * 9.0 / 5.0) + 32.0;
   ...> }
|  created method convertCelsiusToFahrenheit(double)

jshell> convertCelsiusToFahrenheit(0);
$8 ==> 32.0

jshell> convertCelsiusToFahrenheit(100);
$9 ==> 212.0

Practical Exercises

Try creating these methods in jshell:

Exercise 1: Basic Math Methods

// Create these methods:
public static int findMax(int a, int b) {
    // Return the larger of the two numbers
}

public static double calculateTip(double billAmount, double tipPercent) {
    // Calculate and return the tip amount
}

public static boolean isPositive(int number) {
    // Return true if number is positive, false otherwise
}

Exercise 2: String Methods

// Create these methods:
public static String makeTitle(String text) {
    // Convert first letter to uppercase, rest to lowercase
    // "hELLO" becomes "Hello"
}

public static int countVowels(String text) {
    // Count and return the number of vowels (a, e, i, o, u)
}

Exercise 3: ZipCoder Challenge

Create a method that follows these rules:

  • If a number is divisible by both 3 and 5, print "ZipCoder"

  • If divisible by only 3, print "Zip"

  • If divisible by only 5, print "Coder"

  • Otherwise, print the number

public static void zipCoder(int number) {
    // Your code here
}

// Test it:
zipCoder(15); // Should print "ZipCoder"
zipCoder(9);  // Should print "Zip"
zipCoder(10); // Should print "Coder"
zipCoder(7);  // Should print "7"

Key Takeaways

  1. Methods organize code into reusable blocks that perform specific tasks

  2. Parameters let you pass information into methods

  3. Return values let methods give information back

  4. void methods perform actions but don’t return anything

  5. Methods in classes can access and modify the object’s instance variables

  6. Good method names make your code easier to read and understand

  7. Break complex problems into smaller methods for better organization

Methods are essential for writing organized, reusable code. They’re the building blocks that let you create powerful programs by combining simple operations into complex behaviors. As you continue learning Java, you’ll find that most of your programming involves creating and calling methods to solve problems step by step.

X Tutup