Calling a Void Method: AP Computer Science A Study Guide
Introduction to Methods
Welcome to the adventure of programming methods! 🚀 In the world of AP Computer Science A, methods are the secret sauce that makes everything work. Think of a method as a magical spell that gets a specific job done in your code. Sometimes, these spells need ingredients (parameters), but other times they work just fine on their own. When you call a method, it's like summoning a wizard to do something amazing, like changing data, printing text to the screen, or even animating a unicorn in a graphic. 🦄 For now, we'll be focusing on void methods, which are perfect for changes and actions without any return value (like mystical actions with no echo).
Void Methods vs. Non-Void Methods
There are two types of methods in our magical toolkit: void methods and non-void methods. Don't worry, non-void methods are like that mysterious scroll we'll unroll in Topic 2.5.
Void methods are a bit like wizards who complete a task but don't leave behind any magical artifacts. They cast their spell, do their thing, and that's it. These methods are great for changing characteristics of an object or printing text, like a wizard changing a character's hair color or announcing "Dinner is ready!".
Here's the typical header format for a void method:
public void spellName(parameterList) {
// magical actions performed here
}
Void methods might have parameters (ingredients for their spell), but they can also work without them:
spellName()
Method names use camelCase, just like variable and object names.
Static vs. Non-Static Methods
Next, let's discuss another way to sort our magical spells: static methods and non-static methods.
Static Methods
Static methods are like the general spells of the wizarding world. Think of a citywide enchantment to change the minimum wage for all workers. You don't need an individual wizard to cast it for each person; one spell covers everyone.
Here's a static method in action:
public static void incrementMinimumWage() {
minimumWage++;
}
To call this citywide enchantment, you use dot notation with the class name:
ClassName.incrementMinimumWage();
When you call a static method, the program pauses its current task, executes the spell, and then continues.
Non-Static Methods
Non-static methods, on the other hand, are for individual actions, like casting a spell to print a particular person's name. Each person (object) might have a different name, so each needs its own spell.
Here's how you define a non-static method:
public void printName() {
System.out.println(name);
}
To cast this spell, you use dot notation with the object's name:
objectName.printName();
Using the class name here would just be redundant—it's like yelling "Harry, student, print your name!" instead of just "Harry, print your name!"
Methods Practice Problems
Example Classes & Valid Statements
Let’s cast some more spells by looking at practical examples. 🧙♂️
Dog Class
public class Dog {
public String name;
public int age;
public boolean isTrained;
public void setName(String newName) {
name = newName;
}
public void train() {
isTrained = true;
}
}
Assume Dog myDog = new Dog();
is initialized somewhere else. Which 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");
Car Class
public class Car {
public String make;
public String model;
public int year;
public boolean isNew;
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 Car myCar = new Car();
is initialized somewhere else. Which 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();
Student Class
public class Student {
public String name;
public int age;
public int grade;
public boolean isEnrolled;
public void setName(String newName) {
name = newName;
}
public void enroll() {
isEnrolled = true;
}
}
Assume Student myStudent = new Student();
is initialized somewhere else. Which 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");
Book Class
public class Book {
public String title;
public String author;
public int pages;
public boolean isCheckedOut;
public void setTitle(String newTitle) {
title = newTitle;
}
public void setAuthor(String newAuthor) {
author = newAuthor;
}
public void checkOut() {
isCheckedOut = true;
}
}
Assume Book myBook = new Book();
is initialized somewhere else. Which 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");
Flower Class
public class Flower {
public String species;
public String color;
public boolean isBlooming;
public boolean isPoisonous;
public void setSpecies(String newSpecies) {
species = newSpecies;
}
public void setColor(String newColor) {
color = newColor;
}
public void startBlooming() {
isBlooming = true;
}
}
Assume Flower myFlower = new Flower();
is initialized somewhere else. Which 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");
House Class
public class House {
public String address;
public int numBedrooms;
public int numBathrooms;
public boolean isForSale;
public void setAddress(String newAddress) {
address = newAddress;
}
public void setNumBedrooms(int newNumBedrooms) {
numBedrooms = newNumBedrooms;
}
public void putOnMarket() {
isForSale = true;
}
}
Assume House myHouse = new House();
is initialized somewhere else. Which 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();
Game Class
public class Game {
public String title;
public String developer;
public int releaseYear;
public boolean isMultiplayer;
public void setTitle(String newTitle) {
title = newTitle;
}
public void setDeveloper(String newDeveloper) {
developer = newDeveloper;
}
public void setMultiplayer(boolean newIsMultiplayer) {
isMultiplayer = newIsMultiplayer;
}
}
Assume Game myGame = new Game();
is initialized somewhere else. Which 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());
Answers: A. myGame.setTitle("Fortnite");
, B. myGame.setDeveloper("Epic Games");
More Challenging Examples
Ready for some advanced wizardry? Let’s look at code segments that involve chaining spells! ✨
Dog Class Chaining
public class Dog {
public void bark() {
System.out.print("Bark ");
}
public void wagTail() {
System.out.print("wag");
}
public void greetOwner() {
bark();
wagTail();
}
}
Which code segments will cause "Bark wag" to be printed?
A. Dog a = new Dog().greetOwner();
B. Dog a = new Dog(); a.bark(); a.wagTail();
C. Dog a = new Dog(); a.greetOwner();
D. Dog a = new Dog(); Dog.bark(); Dog.wagTail();
E. Dog a = new Dog(); a.bark();
Answers: B. Dog a = new Dog(); a.bark(); a.wagTail();
, C. Dog a = new Dog(); a.greetOwner();
Robot Class Chaining
public class Robot {
public void moveForward() {
System.out.print("Move forward ");
}
public void turnRight() {
System.out.print("turn right");
}
public void navigateMaze() {
turnRight();
moveForward();
}
}
Which code segments will cause "Move forward turn right" to be printed?
A. Robot a = new Robot(); a.moveForward();
B. Robot a = new Robot(); a.navigateMaze();
C. Robot a = new Robot(); a.moveForward(); a.turnRight();
D. Robot a = new Robot(); Robot.moveForward(); Robot.turnRight();
E. Robot a = new Robot(); a.navigateMaze();
Answer: D. Robot a = new Robot(); Robot.moveForward(); Robot.turnRight();
Car Class Chaining
public class Car {
public void accelerate() {
System.out.print("Accelerate ");
}
public void brake() {
System.out.print("brake");
}
public void drive() {
accelerate();
brake();
}
}
Which code segments will cause "Accelerate brake" to be printed?
A. Car a = new Car(); a.accelerate();
B. Car a = new Car(); a.drive();
C. Car a = new Car(); a.brake(); a.accelerate();
D. Car a = new Car(); Car.accelerate(); Car.brake();
E. Car a = new Car(); a.drive();
Answer: E. Car a = new Car(); a.drive();
Fun Exercise – Singing a Song in Code 🎤
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();
}
}
What does the above code print?
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 if you started singing along! 🎶)
Key Terms to Review
-
Method: A method is a named set of instructions that can be called to perform a specific task. Methods are key to reusing code, staying organized, and simplifying your programs.
-
Non-Static Methods: Non-static methods belong to an individual object and are accessed via an instance of the class. They can alter that instance's state and aren't tied to any specific class alone.
And there you have it! Calling void methods can be a powerful tool in your programming arsenal, allowing you to execute tasks without needing a return value. Armed with this knowledge, you're ready to work some serious code magic! 🧙♂️💻