zuai-logo

Calling a Non-Void Method

Emily Wilson

Emily Wilson

7 min read

Study Guide Overview

This study guide covers non-void methods in Java. It explains the core concept of returning values, method header structure (including data types, method names, and parameters), and returning various data types (integers, doubles, booleans, strings, and objects). It also highlights common mistakes, provides quick facts and exam tips, and includes practice multiple-choice and free-response questions covering topics like string manipulation and palindromes.

AP Computer Science A: Non-Void Methods - The Night Before

Hey there! Let's get you feeling confident about non-void methods. Think of this as your quick-reference guide, designed to make everything click right before the exam. We're going to make sure you know exactly what to expect and how to tackle it.

Understanding Non-Void Methods: The Core Concept

Non-void methods are all about getting a value back. Unlike void methods that just do something, non-void methods calculate or retrieve a value and then return it for use elsewhere in your program. This returned value can be a primitive type (like int, double, boolean) or a reference type (like String or other objects).

Method Header Structure

java
public (static) dataType methodName(parameterListOptional)
  • public: Access modifier (we'll dive deeper into these later).
  • static: Optional keyword; indicates the method belongs to the class itself, not an object (more on this in Unit 5).
  • dataType: Crucial! This is the type of value the method will return. It must match the type of the returned expression.
  • methodName: How you'll call the method.
  • parameterListOptional: Input values the method needs to do its job (optional).
Key Concept

Remember: The return type in the method header must match the type of the value being returned by the method.

Returning Different Data Types

Returning Integers/Doubles

These methods are your math wizards. They perform calculations and return the result. The return statement is key here. It stops the method's execution and sends the calculated value back to the caller.

java
public static double rectanglePerimeter(double length, double width) {
    return 2 * (length + width); // Returns a double
    // Any code after this return statement will be unreachable!
}
Exam Tip

Always double-check that your return type matches the type of the expression you're returning. A mismatch will cause a compile error!

Returning Booleans

Boolean methods are your condition checkers. They evaluate a boolean expression and return true or false. The naming convention isCondition() is a good practice.

java
public static boolean isEven(int number) {
    return number % 2 == 0; // Returns true if even, false otherwise
}
Memory Aid

Think of boolean methods as asking a yes/no question. The answer is always true or false.

Returning Strings

String methods are your text manipulators. They create or modify strings and return the result. We'll explore string manipulation in more detail later.

java
public static String createGreeting(String name) {
    return "Hello, " + name + "!"; // Returns a String
}

Returning Objects and Reference Types

These methods are for creating or modifying objects. They return a reference to the object. We'll get into this in detail in later units, but for now, just know that it's possible!

java
// Example (more details in Unit 5+)
public static ArrayList<Integer> createList() {
    ArrayList<Integer> list = new ArrayList<>();
    list.add(1);
    list.add(2);
    return list;
}

Common Mistake

Common Mistakes to Avoid

  • Mismatched Return Types: The return type in the method header must match the type of the value returned by the method. This is a very common source of errors.
  • Unreachable Code: Any code after a return statement within a method will never execute. Be sure to place your return statement at the end of your method.
  • Forgetting to Return: If your method is not void, it must have a return statement. Forgetting it causes a compile error.

Quick Fact

Quick Facts to Remember

  • Non-void methods return values.
  • The return statement is crucial for returning a value.
  • The return type in the method header must match the type of the returned value.
  • Methods stop executing after a return statement.

Exam Tip

Exam Tips

  • Read Carefully: Pay close attention to the method signature, especially the return type.
  • Trace Code: Step through code with non-void methods, noting the returned value.
  • Practice: The more you practice, the more comfortable you'll become with non-void methods.
  • Use a pencil: When tracing code on paper, use a pencil to track variable values and method calls.

Practice Question

Practice Problems

Multiple Choice Questions

Question 1:

java
public class Calculator {
    public int add(int x, int y) {
        return x + y;
    }
    public int multiply(int x, int y) {
        return x * y;
    }
    public static void main(String[] args) {
        Calculator calc = new Calculator();
        System.out.println(calc.add(5, 6) + calc.multiply(2, 3));
    }
}

What is the output of the above code?

A. 10 B. 17 C. 21 D. 23 E. An error message

Answer: B. 17

Question 2:

java
public class Shapes {
    public double calculateCircleArea(double radius) {
        return Math.PI * Math.pow(radius, 2);
    }
    public double calculateRectangleArea(double length, double width) {
        return length * width;
    }
    public static void main(String[] args) {
        Shapes shapes = new Shapes();
        System.out.println(shapes.calculateCircleArea(5) + shapes.calculateRectangleArea(10, 2));
    }
}

What is the output of the above code?

A. 78.5 B. 80.5 C. 82.5 D. 98.5 E. An error message

Answer: D. 98.5

Question 3:

java
public class Customer {
    private String name;
    private String address;
    private int phone;
    private boolean isPremium;
    public Customer(String customerName, String customerAddress, int customerPhone, boolean customerIsPremium) {
        name = customerName;
        address = customerAddress;
        phone = customerPhone;
        isPremium = customerIsPremium;
    }
    public boolean getIsPremium() {
        return isPremium;
    }
}

Assume that the following code segment appears in a class other than Customer:

java
Customer customer = new Customer("Jane", "123 Main St.", 5551212, true);
System.out.println(customer.getIsPremium());

What is printed as a result of executing the code segment?

A. true B. customer.getIsPremium() C. The code will not compile. D. 555-1212 E. Jane

Answer: A. true

Free Response Question

Question:

Write a class named StringUtil with the following methods:

  1. public static String reverseString(String str): This method should take a string as input and return a new string that is the reverse of the input string. For example, if the input is "hello", the method should return "olleh".
  2. public static boolean isPalindrome(String str): This method should take a string as input and return true if the string is a palindrome (reads the same forwards and backward), and false otherwise. Ignore case and spaces. For example, "Race car" is a palindrome.

Answer:

java
public class StringUtil {

    public static String reverseString(String str) {
        String reversed = "";
        for (int i = str.length() - 1; i >= 0; i--) {
            reversed += str.charAt(i);
        }
        return reversed;
    }

    public static boolean isPalindrome(String str) {
        String cleanedStr = str.replaceAll("\\s", "").toLowerCase();
        String reversedStr = reverseString(cleanedStr);
        return cleanedStr.equals(reversedStr);
    }
}

Scoring Breakdown:

  • reverseString method (5 points):
    • +2: Correctly creates an empty string to store the reversed string
    • +2: Correctly iterates through the input string in reverse order
    • +1: Correctly returns the reversed string
  • isPalindrome method (5 points):
    • +1: Correctly removes spaces and converts to lowercase
    • +2: Correctly calls the reverseString method
    • +1: Correctly compares the cleaned string to its reversed version
    • +1: Correctly returns a boolean value

Final Exam Focus

Okay, you're almost there! Here's what to prioritize in these final hours:

  • Non-Void Method Structure: Make sure you understand the method header, return types, and the importance of the return statement.
  • Data Type Matching: Double-check that your return types match the values being returned.
  • Tracing Code: Practice tracing code with non-void methods to predict output.
  • FRQ Practice: Focus on writing methods that return values, as this is a common FRQ task.

Last-Minute Tips

  • Stay Calm: You've got this! Take deep breaths and approach each question systematically.
  • Time Management: Don't get stuck on one question. Move on and come back if you have time.
  • Read Carefully: Pay close attention to the instructions and method signatures.
  • Show Your Work: Even if you're not sure, write down what you know. Partial credit is your friend.

Alright, you're ready to rock this exam! Go get 'em! 🚀

Question 1 of 9

What is the primary purpose of a non-void method? 🤔

To perform an action without returning a value

To calculate or retrieve a value and return it

To only print output to the console

To define class variables