Calling a Void Method

Sophie Anderson
13 min read
Listen to this study note
Study Guide Overview
This study guide covers methods in AP Computer Science A, including:
- Method definition, purpose, and behavior
- Void vs. Non-Void methods and Static vs. Non-Static methods
- Method signatures and calling methods using dot notation
- Practice problems and exam tips focusing on object interaction and code tracing with methods
#AP Computer Science A: Methods - The Night Before 🚀
Hey there, future AP Computer Science rockstar! Let's get you prepped for the exam with a super-focused review of methods. We'll make sure everything clicks, and you'll walk in feeling confident. Let's do this!
#Introduction to Methods
Methods are like mini-programs within your program. They perform specific tasks, and they're essential for organizing your code. Think of them as the verbs of your code, describing what actions your objects can take. 💡
- Definition: A method is a block of code that performs a specific task.
- Purpose: To organize code into reusable blocks, making programs more modular and easier to manage.
- Behavior: Methods define the actions an object can perform, also known as the object's behavior.
- Parameters: Methods can accept input values called parameters, which modify their behavior.
#Types of Methods
Methods can be classified in a few ways. Let's break them down:
#Void vs. Non-Void Methods
-
Void Methods: These methods perform actions but do not return a value. They change the state of an object or perform an operation like printing to the console.
- Example:
public void printName() { System.out.println(name); }
- Keyword:
void
in the method header indicates it's a void method. - Signature: Method name + parameter list (e.g.,
printName()
,setName(String newName)
)
- Example:
-
Non-Void Methods: These methods perform actions and return a value. We'll dive into these in more detail later.
#Static vs. Non-Static Methods
- Static Methods: These methods belong to the class itself, not to any specific object. Think of them as general tools that any object of the class can use. ⚙️
- Keyword:
static
in the method header. - Example:
- Keyword:
java
public static void incrementMinimumWage() {
minimumWage++;
}
```
- Calling Static Methods: Use the class name and dot notation: ClassName.methodName();
- Non-Static Methods: These methods operate on a specific object. Each object has its own version of these methods.
- Example:
- Example:
java
public void printName() {
System.out.println(name);
}
```
- Calling Non-Static Methods: Use the object name and dot notation: objectName.methodName();
Static methods are like class-wide tools (e.g., a calculator app), while non-static methods are like personal actions each object can take (e.g., a person's ability to speak).
#
Method Signatures
- Definition: The method signature includes the method name and the parameter list (the types and names of the inputs the method takes).
- Importance: The method signature is crucial for the compiler to identify and call the correct method.
- Example: In
public void setName(String newName)
, the method signature issetName(String newName)
. The return type (void
in this case) is not part of the method signature.
Pay close attention to method signatures in multiple-choice questions. Mismatched signatures are a common source of errors.
#
Calling Methods
- Dot Notation: Use dot notation to call both static and non-static methods.
- Static:
ClassName.methodName(parameters);
- Non-Static:
objectName.methodName(parameters);
- Static:
- Execution Flow: When a method is called, the program jumps to the method's code, executes it, and then returns to the point where it was called.
Forgetting the parentheses ()
when calling a method is a frequent error. Always include them, even if there are no parameters.
#Methods Practice Problems
Okay, let's put this knowledge to the test with some practice problems similar to what you'll see on the AP exam. Remember, practice makes perfect! 💪
#Practice Problem 1
Consider the following class definition.
java
public class Dog
{
String name;
int age;
boolean isTrained;
public Dog()
{
name = "";
age = 0;
isTrained = false;
}
public void setName(String newName)
{
name = newName;
}
public void train()
{
isTrained = true;
}
}
Assume that a Dog object called myDog
has been properly declared and initialized in a class other than Dog
. Which of the following statements are valid?
A. myDog.setName("Buddy");
B. myDog.train(true);
C. myDog.age(5);
D. System.out.println( myDog.isTrained() );
E. myDog.setAge(3);
Answer: A. myDog.setName("Buddy");
#Practice Problem 2
Consider the following class definition.
java
public class Car
{
String make;
String model;
int year;
boolean isNew;
public Car()
{
make = "";
model = "";
year = 0;
isNew = true;
}
public void setMake(String newMake)
{
make = newMake;
}
public void setModel(String newModel)
{
model = newModel;
}
public void setYear(int newYear)
{
year = newYear;
if (year < 2020)
{
isNew = false;
}
}
}
Assume that a Car object called myCar
has been properly declared and initialized in a class other than Car
. Which of the following statements are not valid?
A. myCar.setMake("Ford");
B. myCar.setModel(Mustang);
C. myCar.setYear(2022);
D. myCar.isNew();
E. myCar.setModel("Mustang");
Answers:
B. myCar.setModel(Mustang);
D. myCar.isNew();
#Practice Problem 3
Consider the following class definition.
java
public class Student
{
String name;
int age;
int grade;
boolean isEnrolled;
public Student()
{
name = "";
age = 0;
grade = 0;
isEnrolled = false;
}
public void setName(String newName)
{
name = newName;
}
public void enroll()
{
isEnrolled = true;
}
}
Assume that a Student object called myStudent
has been properly declared and initialized in a class other than Student
. Which of the following statements are valid?
A. myStudent.setGrade(11);
B. myStudent.enroll(true);
C. myStudent.age(17);
D. System.out.println( myStudent.isEnrolled() );
E. myStudent.setName("Jane");
Answer: E. myStudent.setName("Jane");
#Practice Problem 4
Consider the following class definition.
java
public class Book
{
String title;
String author;
int pages;
boolean isCheckedOut;
public Book()
{
title = "";
author = "";
pages = 0;
isCheckedOut = false;
}
public void setTitle(String newTitle)
{
title = newTitle;
}
public void setAuthor(String newAuthor)
{
author = newAuthor;
}
public void checkOut()
{
isCheckedOut = true;
}
}
Assume that a Book object called myBook
has been properly declared and initialized in a class other than Book
. Which of the following statements are valid?
A. myBook.setTitle(To Kill a Mockingbird);
B. myBook.setAuthor("Harper Lee");
C. myBook.checkOut(true);
D. myBook.pages(250);
E. System.out.println( myBook.isCheckedOut() );
Answer: B. myBook.setAuthor("Harper Lee");
#Practice Problem 5
Consider the following class definition.
java
public class Flower
{
String species;
String color;
boolean isBlooming;
boolean isPoisonous;
public Flower()
{
species = "";
color = "";
isBlooming = false;
isPoisonous = false;
}
public void setSpecies(String newSpecies)
{
species = newSpecies;
}
public void setColor(String newColor)
{
color = newColor;
}
public void startBlooming()
{
isBlooming = true;
}
}
Assume that a Flower object called myFlower
has been properly declared and initialized in a class other than Flower
. Which of the following statements are valid?
A. myFlower.setSpecies("Rose");
B. myFlower.setcolor("Red");
C. myFlower.startBlooming(true);
D. myFlower.isPoisonous(true);
E. System.out.println( myFlower.isBlooming() );
Answer: A. myFlower.setSpecies("Rose");
#Practice Problem 6
Consider the following class definition.
java
public class House
{
String address;
int numBedrooms;
int numBathrooms;
boolean isForSale;
public House()
{
address = "";
numBedrooms = 0;
numBathrooms = 0;
isForSale = false;
}
public void setAddress(String newAddress)
{
address = newAddress;
}
public void setNumBedrooms(int newNumBedrooms)
{
numBedrooms = newNumBedrooms;
}
public void putOnMarket()
{
isForSale = true;
}
}
Assume that a House object called myHouse
has been properly declared and initialized in a class other than House
. Which of the following statements are valid?
A. myHouse.setAddress(123 Main Street);
B. myHouse.setNumBedrooms("3");
C. myHouse.putOnMarket();
D. myHouse.numBathrooms(2);
E. System.out.println( myHouse.isForSale() );
Answer: C. myHouse.putOnMarket();
#Practice Problem 7
Consider the following class definition.
java
public class Game
{
String title;
String developer;
int releaseYear;
boolean isMultiplayer;
public Game()
{
title = "";
developer = "";
releaseYear = 0;
isMultiplayer = false;
}
public void setTitle(String newTitle)
{
title = newTitle;
}
public void setDeveloper(String newDeveloper)
{
developer = newDeveloper;
}
public void setMultiplayer(boolean newIsMultiplayer)
{
isMultiplayer = newIsMultiplayer;
}
}
Assume that a Game object called myGame
has been properly declared and initialized in a class other than Game
. Which of the following statements are valid?
A. myGame.setTitle("Fortnite");
B. myGame.setDeveloper("Epic Games");
C. myGame.setMultiplayer(true);
D. myGame.releaseYear(2017);
E. System.out.println( myGame.isMultiplayer() );
Answer:
A. myGame.setTitle("Fortnite");
B. myGame.setDeveloper("Epic Games");
#Practice Problem 8
Consider the following class definition.
java
public class Dog
{
public void bark()
{
System.out.print("Bark ");
}
public void wagTail()
{
System.out.print("wag");
}
public void greetOwner()
{
bark();
wagTail();
}
/* Constructors not shown */
}
Which of the following code segments, if located in a method in a class other than Dog
, will cause the message “Bark wag” to be printed?
A.
java
Dog a = new Dog().greetOwner();
B.
java
Dog a = new Dog();
a.bark();
a.wagTail();
C.
java
Dog a = new Dog();
a.greetOwner();
D.
java
Dog a = new Dog();
Dog.bark();
Dog.wagTail();
E.
java
Dog a = new Dog();
a.bark();
Answers:
B.
java
Dog a = new Dog();
a.bark();
a.wagTail();
C.
java
Dog a = new Dog();
a.greetOwner();
#Practice Problem 9
Consider the following class definition.
java
public class Robot
{
public void moveForward()
{
System.out.print("Move forward ");
}
public void turnRight()
{
System.out.print("turn right");
}
public void navigateMaze()
{
turnRight();
moveForward();
}
/* Constructors not shown */
}
Which of the following code segments, if located in a method in a class other than Robot
, will cause the message “Move forward turn right” to be printed?
A.
java
Robot a = new Robot();
a.moveForward();
B.
java
Robot a = new Robot().navigateMaze();
C.
java
Robot a = new Robot();
a.moveForward();
a.turnRight();
D.
java
Robot a = new Robot();
Robot.moveForward();
Robot.turnRight();
E.
java
Robot a = new Robot();
a.navigateMaze();
Answer:
D.
java
Robot a = new Robot();
Robot.moveForward();
Robot.turnRight();
#Practice Problem 10
Consider the following class definition.
java
public class Car
{
public void accelerate()
{
System.out.print("Accelerate ");
}
public void brake()
{
System.out.print("brake");
}
public void drive()
{
accelerate();
brake();
}
/* Constructors not shown */
}
Which of the following code segments, if located in a method in a class other than Car
, will cause the message “Accelerate brake” to be printed?
A.
java
Car a = new Car();
a.accelerate();
B.
java
Car a = new Car().drive();
C.
java
Car a = new Car();
a.brake();
a.accelerate();
D.
java
Car a = new Car();
Car.accelerate();
Car.brake();
E.
java
Car a = new Car();
a.drive();
Answer:
E.
java
Car a = new Car();
a.drive();
#Practice Problem 11
What does the following code print out?
java
public class Song
{
public void play()
{
System.out.print("We are ");
never();
ever();
ever();
together();
}
public void together()
{
System.out.println("getting back together!");
}
public void never()
{
System.out.print("never ");
}
public void ever()
{
System.out.print("ever ");
}
public static void main(String[] args)
{
Song s = new Song();
s.play();
}
}
A. We are never ever ever getting back together! B. We are never ever ever. C. We are getting back together! never ever ever. D. We are never ever ever together. E. Nothing, it does not compile.
Answer: A. We are never ever ever getting back together! (bonus points for guessing the song!)
Practice Question
json
{
"mcq": [
{
"question": "Consider the following class definition:\n\n```
java\npublic class Circle {\n private double radius;\n\n public Circle(double radius) {\n this.radius = radius;\n }\n\n public double getArea() {\n return Math.PI * radius * radius;\n }\n\n public void setRadius(double newRadius) {\n radius = newRadius;\n }\n\n public static double calculateArea(double radius) {\n return Math.PI * radius * radius;\n }\n}\n```
\n\nWhich of the following statements about the `Circle` class is true?",
"options": [
"The `getArea` method is a static method.",
"The `setRadius` method is a static method.",
"The `calculateArea` method is a non-static method.",
"The `getArea` method can only be called on a `Circle` object.",
"The `calculateArea` method can only be called on a `Circle` object."
],
"answer": "The `getArea` method can only be called on a `Circle` object."
},
{
"question": "Given the following class definition:\n\n```
java\npublic class Rectangle {\n private int width;\n private int height;\n\n public Rectangle(int width, int height) {\n this.width = width;\n this.height = height;\n }\n\n public int getArea() {\n return width * height;\n }\n\n public void resize(int newWidth, int newHeight) {\n width = newWidth;\n height = newHeight;\n }\n}\n```
\n\nWhich of the following code snippets correctly resizes a `Rectangle` object named `myRect` to a width of 10 and a height of 20?",
"options": [
"myRect.resize(10); myRect.resize(20);",
"myRect.resize(10, 20);",
"Rectangle.resize(10, 20);",
"myRect.width = 10; myRect.height = 20;",
"myRect.resize(new int[]{10, 20});"
],
"answer": "myRect.resize(10, 20);"
},
{
"question": "Consider the following code snippet:\n\n```
java\npublic class Counter {\n private int count;\n\n public Counter() {\n count = 0;\n }\n\n public void increment() {\n count++;\n }\n\n public int getCount() {\n return count;\n }\n\n public static void reset(Counter c) {\n c.count = 0;\n }\n}\n\npublic class Main {\n public static void main(String[] args) {\n Counter c1 = new Counter();\n Counter c2 = new Counter();\n c1.increment();\n Counter.reset(c2);\n System.out.println(c1.getCount() + \" \" + c2.getCount());\n }\n}\n```
\n\nWhat will be printed when the `main` method is executed?",
"options": [
"0 0",
"1 0",
"1 1",
"0 1",
"Error: Cannot call static method on object."
],
"answer": "1 0"
}
],
"frq": {
"question": "A `Student` class is defined as follows:\n\n```
java\npublic class Student {\n private String name;\n private int gradeLevel;\n private double gpa;\n\n public Student(String name, int gradeLevel, double gpa) {\n this.name = name;\n this.gradeLevel = gradeLevel;\n this.gpa = gpa;\n }\n\n public String getName() {\n return name;\n }\n\n public int getGradeLevel() {\n return gradeLevel;\n }\n\n public double getGpa() {\n return gpa;\n }\n\n public void promote() {\n gradeLevel++;\n }\n\n public void updateGpa(double newGpa) {\n gpa = newGpa;\n }\n}\n```
\n\nWrite a `School` class that contains an `ArrayList` of `Student` objects. The `School` class should have the following methods:\n\n1. A constructor that takes no parameters and initializes the `ArrayList` of `Student` objects.\n2. A method `addStudent` that takes a `Student` object as a parameter and adds it to the `ArrayList`.\n3. A method `promoteAll` that iterates through the `ArrayList` and calls the `promote` method on each `Student` object.\n4. A method `getAverageGpa` that calculates and returns the average GPA of all students in the school. If there are no students, it should return 0.0.\n\nInclude necessary import statements.",
"scoring": {
"1": "Constructor correctly initializes the ArrayList of Students (1 point)",
"2": "Method addStudent correctly adds a Student object to the ArrayList (2 points)",
"3": "Method promoteAll correctly iterates through the ArrayList and calls promote on each Student (3 points)",
"4": "Method getAverageGpa correctly calculates the average GPA of all students in the school (3 points)",
"5": "Method getAverageGpa returns 0.0 if there are no students (1 point)"
},
"solution": "```
java\nimport java.util.ArrayList;\n\npublic class School {\n private ArrayList<Student> students;\n\n public School() {\n students = new ArrayList<>();\n }\n\n public void addStudent(Student student) {\n students.add(student);\n }\n\n public void promoteAll() {\n for (Student student : students) {\n student.promote();\n }\n }\n\n public double getAverageGpa() {\n if (students.isEmpty()) {\n return 0.0;\n }\n double totalGpa = 0;\n for (Student student : students) {\n totalGpa += student.getGpa();\n }\n return totalGpa / students.size();\n }\n}\n```
"
}
}
#Final Exam Focus
Alright, let's zoom in on the highest-priority topics for the exam:
- Method Types: Understand the differences between void/non-void and static/non-static methods.
- Method Signatures: Be able to identify method signatures and call methods correctly using dot notation.
- Object Interaction: Know how objects interact with each other through methods.
- Code Tracing: Practice tracing code that involves method calls.
#Last-Minute Tips
- Time Management: Don't spend too long on any one question. If you're stuck, move on and come back later.
- Common Pitfalls: Watch out for mismatched method signatures and incorrect use of static/non-static methods.
- FRQ Strategy: Plan your FRQ responses before you start coding. Break down the problem into smaller steps.
- Stay Calm: You've got this! Take a deep breath and trust in your preparation.
Remember to read the questions carefully, pay attention to method signatures, and practice, practice, practice!
Methods are the building blocks of object-oriented programming. Mastering them is key to success!
You've worked hard, and you're ready to ace this exam. Go get 'em! 🎉
Explore more resources

How are we doing?
Give us your feedback and let us know how we can improve