Fiveable
Fiveable
pep
Fiveable
Fiveable

or

Log in

Find what you need to study


Light

2.5 Calling a Non-Void Method

7 min readdecember 28, 2022

Athena_Codes

Athena_Codes

user_sophia9212

user_sophia9212

Athena_Codes

Athena_Codes

user_sophia9212

user_sophia9212

Void methods are used to complete actions and represent tasks. However, most of the time we want to use a method as part of an expression or stored as a variable. This is what non-void methods are for. In place of a void keyword, there is a return type, which is the type that the method returns for use by the program. Non-void methods can return both primitive and . You can store the results of methods in variables as well as follows:

dataType 

To make a non-void method, we use the following method header format (with being optional):

Returning Integers/Doubles

Sometimes, we want to calculate a value to use in future calculations. This is when we can return an integer or double which will be used in the future. Usually, these methods perform some type of calculation by themselves and return the result of these calculations. The printRectanglePerimeter() method from Topic 2.4 can be written as a non-void method with a few modifications as follows:

The most important change is the substitution of the print statement with the . The takes the expression on that line, evaluates it, and returns it to the program that called the method for use. The stops the method execution and ignores any code below the . In the example above, the "some other code" will never be run since it is after the .

Returning Booleans

Methods that return booleans are usually used to show whether a condition is true or not. The method has to do with the evaluation of a boolean expression, which shows whether something is true or not. We will learn more about in Unit 3! When naming boolean-return methods, we commonly name the method using the isCondition() name format to show whether a condition is true or not. Here are some method signatures of methods which return booleans that we can make once we learn more Java:

isPrime(int number)
isEven(int number)
isLeapYear(int year)
isPalindrome(String word)

Returning Strings

Methods that return strings usually deal with string manipulation or string construction. These will have to do with making or modifying new strings. We don't know much about strings yet, but we will learn a lot more about them in the next two topics!

Returning Objects and Other Reference Types

Methods which return objects or other reference types are similar to those which return strings in which they either create new or modify parts of this . We will learn about these in Units 5-8!

Non-Void Methods Practice Problems

What is the output of the following code?

class Calculator

{

int add(int x, int y)

{

return x + y;

}

int multiply(int x, int y)

{

return x * y;

}

void main(String[] args) {

Calculator calc = new Calculator();

System.out.println( calc.add(5,6) + calc.multiply(2,3) );

}

}

A. 10

B. 17

C. 21

D. 23

E. An error message

Answer: B. 17

What will the following code print out?

class NamePrinter

{

void printName(String name)

{

System.out.println("Your name is: " + name);

}

void printAge(int age)

{

System.out.println("Your age is: " + age);

}

void main(String[] args) {

NamePrinter np = new NamePrinter();

np.printName("John");

np.printAge(32);

}

}

A. 

Your name is: John

Your age is: 32

B. 

John

32

C. 

Your age is: 32

Your name is: John

D. 

32

John

E. An error message

Answer:

A. 

Your name is: John

Your age is: 32

What is the result of the following code?

class Shapes

{

double calculateCircleArea(double radius)

{

return Math.PI * Math.pow(radius, 2);

}

double calculateRectangleArea(double length, double width)

{

return length * width;

}

void main(String[] args) {

Shapes shapes = new Shapes();

System.out.println( shapes.calculateCircleArea(5) + shapes.calculateRectangleArea(10,2) );

}

}

A. 78.5

B. 80.5

C. 82.5

D. 98.5

E. An error message

Answer: D. 98.5

What will the following code output?

class Book

{

String title;

String author;

int pages;

Book(String bookTitle, String bookAuthor, int bookPages)

{

title = bookTitle;

author = bookAuthor;

pages = bookPages;

}

void printBookInfo()

{

System.out.println("Title: " + title);

System.out.println("Author: " + author);

System.out.println("Pages: " + pages);

}

void main(String[] args) {

Book book = new Book("The Great Gatsby", "F. Scott Fitzgerald", 180);

book.printBookInfo();

}

}

A. 

Title: 180

Author: The Great Gatsby

Pages: F. Scott Fitzgerald

B. 

Title: F. Scott Fitzgerald

Author: The Great Gatsby

Pages: 180

C. 

Title: The Great Gatsby

Author: F. Scott Fitzgerald

Pages: 180

D. The Great Gatsby, F. Scott Fitzgerald, 180

E. An error message

Answer: 

C. 

Title: The Great Gatsby

Author: F. Scott Fitzgerald

Pages: 180

What is the output of the following code?

class Employee

{

String name;

int salary;

Employee(String empName, int empSalary)

{

name = empName;

salary = empSalary;

}

void printEmployeeInfo()

{

System.out.println("Name: " + name);

System.out.println("Salary: $" + salary);

}

void giveRaise(int raiseAmount)

{

salary += raiseAmount;

}

void main(String[] args) {

Employee emp = new Employee("John", 50000);

emp.printEmployeeInfo();

emp.giveRaise(2000);

emp.printEmployeeInfo();

}

}

A. 

Name: John

Salary: $50000

Name: John

Salary: $52000

B. 

Name: John

Salary: $52000

Name: John

Salary: $50000

C. 

Name: John

Salary: $50000

Name: $2000

Salary: $52000

D. 

Name: John

Salary: $52000

Name: $2000

Salary: $50000

E. An error message

Answer: 

A. 

Name: John

Salary: $50000

Name: John

Salary: $52000

Consider the following method.

int sumNumbers(int num1, int num2, int num3)

{ /*implementation not shown */ }

Which of the following lines of code, if located in a method in the same class as sumNumbers, will compile without an error?

A. int result = sumNumbers(1, 2, 3);

B. double result = sumNumbers(1.0, 2.0, 3.0);

C. int result = sumNumbers(1.0, 2, 3);

D. double result = sumNumbers(1, 2, 3);

E. result = sumNumbers(1, 2, 3);

Answer: A. int result = sumNumbers(1, 2, 3);

Consider the following method.

boolean isValidEmail(String email)

{ /*implementation not shown */ }

Which of the following lines of code, if located in a method in the same class as isValidEmail, will compile without an error?

A. String result = isValidEmail("john@gmail.com");

B. int result = isValidEmail("john@gmail.com");

C. double result = isValidEmail("john@gmail.com");

D. boolean result = isValidEmail("john@gmail.com");

E. result = isValidEmail("john@gmail.com");

Answer: D. boolean result = isValidEmail("john@gmail.com");

Consider the following method.

String reverseString(String str)

{ /*implementation not shown */ }

Which of the following lines of code, if located in a method in the same class as reverseString, will compile without an error?

A. int result = reverseString("hello");

B. String result = reverseString("hello");

C. double result = reverseString("hello");

D. boolean result = reverseString("hello");

E. result = reverseString("hello");

Answer: B. String result = reverseString("hello");

Consider the following method.

int calculateTriangleArea(int base, double height)

{ /*implementation not shown */ }

Which of the following lines of code, if located in a method in the same class as calculateTriangleArea, will compile without an error?

A. int result = calculateTriangleArea(5, 10);

B. double result = calculateTriangleArea(5.0, 10.0);

C. int result = calculateTriangleArea(5.0, 10);

D. double result = calculateTriangleArea(5, 10.0);

E. result = calculateTriangleArea(5, 10);

Answer: D. double result = calculateTriangleArea(5, 10.0);

Consider the following .

class Animal

{

private String species;

private int age;

private double weight;

Animal(String animalSpecies, int animalAge, double animalWeight)

{

    species = animalSpecies;

    age = animalAge;

    weight = animalWeight;

}

void eat()

{

    weight += 5;

}

double getWeight()

{

    return weight;

}

}

Assume that the following code segment appears in a class other than Animal.

Animal dog = new Animal("Dog", 3, 15);

dog.eat();

System.out.println(dog.getWeight());

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

A. 20

B. 15

C. dog.getWeight()

D. The code will not compile.

E. 5

Answer: A. 20

Consider the following .

class Car

{

private String make;

private String model;

private int year;

private double speed;

Car(String carMake, String carModel, int carYear)

{

    make = carMake;

    model = carModel;

    year = carYear;

    speed = 0;

}

void accelerate()

{

    speed += 10;

}

double getSpeed()

{

    return speed;

}

}

Assume that the following code segment appears in a class other than Car.

Car car = new Car("Toyota", "Corolla", 2010);

car.accelerate();

System.out.println(car.getSpeed());

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

A. 0

B. 10

C. car.getSpeed()

D. The code will not compile.

E. Toyota

Answer: B. 10

Consider the following .

class Customer

{

private String name;

private String address;

private int phone;

private boolean isPremium;

Customer(String customerName, String customerAddress, int customerPhone, boolean customerIsPremium)

{

    name = customerName;

    address = customerAddress;

    phone = customerPhone;

    isPremium = customerIsPremium;

}

boolean getIsPremium()

{

    return isPremium;

}

}

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

Customer customer = new Customer("Jane", "123 Main St.", 555-1212, 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

Key Terms to Review (22)

Boolean Expressions

: Boolean expressions are statements that evaluate to either true or false. They are commonly used in programming to make decisions and control the flow of a program.

calculateCircleArea(double radius)

: The calculateCircleArea method is used to compute the area of a circle based on its radius. It takes in the radius as input and returns the calculated area.

calculateRectangleArea(double length, double width)

: The calculateRectangleArea method is used to calculate the area of a rectangle based on its length and width. It takes in the length and width as input parameters and returns the calculated area.

calculateTriangleArea(int base, double height)

: This function calculates the area of a triangle using its base length and height.

Class Definition

: A class definition is a blueprint or template for creating objects of a particular type. It defines the properties and behaviors that an object of that class will have.

Data Type

: A data type is a classification that specifies the type of value that a variable can hold. It determines the operations that can be performed on the variable, such as arithmetic operations or string manipulation.

eat()

: The eat() method is a function that allows an object to consume food or perform actions related to consuming food.

getIsPremium()

: The method getIsPremium() is used to check if a user has a premium account or not. It returns true if the user is a premium member, and false otherwise.

getSpeed()

: The method getSpeed() is used to retrieve the value of the speed attribute in a program. It returns the current speed of an object or entity.

giveRaise(int raiseAmount)

: This term refers to a function or method that increases an employee's salary by a specified amount.

isCondition()

: The isCondition() method is used in programming to check if a certain condition is true or false. It returns a boolean value, either true or false, based on the evaluation of the condition.

isValidEmail(String email)

: This method checks whether a given email address is valid or not.

methodName(parameterListOptional)

: A method name is an identifier that represents an action or behavior that an object can perform. It may also include optional parameters, which are values passed into the method for it to use during its execution.

Primitive Data

: Primitive data refers to basic data types that are built into a programming language, such as integers, floating-point numbers, characters, and booleans. These data types are not composed of other data types.

printBookInfo()

: This term refers to a method or function that displays information about a book, such as its title, author, and publication date.

public

: Public is an access modifier in Java that indicates unrestricted visibility for classes, methods, and variables. Public members can be accessed from any other class or package.

Reference Data

: Reference data refers to complex data types that are composed of multiple primitive or reference data types. Examples include arrays, objects, and strings. Unlike primitive data types, reference variables store references (memory addresses) rather than actual values.

Return Statement

: A return statement is used in functions/methods to specify what value should be sent back as output when the function is called. It terminates the execution of a function and returns control back to where it was called from.

reverseString(String str)

: This method takes a string as input and returns the reversed version of that string.

Static

: In programming, "static" refers to a variable or method that belongs to the class itself, rather than an instance of the class. It can be accessed without creating an object of the class.

sumNumbers(int num1, int num2, int num3)

: This term refers to a function or method that adds together three numbers and returns their sum.

variableName

: A variable name is a unique identifier that is used to store and refer to a value in a program. It must follow certain rules, such as starting with a letter or underscore, and cannot be a reserved keyword.

2.5 Calling a Non-Void Method

7 min readdecember 28, 2022

Athena_Codes

Athena_Codes

user_sophia9212

user_sophia9212

Athena_Codes

Athena_Codes

user_sophia9212

user_sophia9212

Void methods are used to complete actions and represent tasks. However, most of the time we want to use a method as part of an expression or stored as a variable. This is what non-void methods are for. In place of a void keyword, there is a return type, which is the type that the method returns for use by the program. Non-void methods can return both primitive and . You can store the results of methods in variables as well as follows:

dataType 

To make a non-void method, we use the following method header format (with being optional):

Returning Integers/Doubles

Sometimes, we want to calculate a value to use in future calculations. This is when we can return an integer or double which will be used in the future. Usually, these methods perform some type of calculation by themselves and return the result of these calculations. The printRectanglePerimeter() method from Topic 2.4 can be written as a non-void method with a few modifications as follows:

The most important change is the substitution of the print statement with the . The takes the expression on that line, evaluates it, and returns it to the program that called the method for use. The stops the method execution and ignores any code below the . In the example above, the "some other code" will never be run since it is after the .

Returning Booleans

Methods that return booleans are usually used to show whether a condition is true or not. The method has to do with the evaluation of a boolean expression, which shows whether something is true or not. We will learn more about in Unit 3! When naming boolean-return methods, we commonly name the method using the isCondition() name format to show whether a condition is true or not. Here are some method signatures of methods which return booleans that we can make once we learn more Java:

isPrime(int number)
isEven(int number)
isLeapYear(int year)
isPalindrome(String word)

Returning Strings

Methods that return strings usually deal with string manipulation or string construction. These will have to do with making or modifying new strings. We don't know much about strings yet, but we will learn a lot more about them in the next two topics!

Returning Objects and Other Reference Types

Methods which return objects or other reference types are similar to those which return strings in which they either create new or modify parts of this . We will learn about these in Units 5-8!

Non-Void Methods Practice Problems

What is the output of the following code?

class Calculator

{

int add(int x, int y)

{

return x + y;

}

int multiply(int x, int y)

{

return x * y;

}

void main(String[] args) {

Calculator calc = new Calculator();

System.out.println( calc.add(5,6) + calc.multiply(2,3) );

}

}

A. 10

B. 17

C. 21

D. 23

E. An error message

Answer: B. 17

What will the following code print out?

class NamePrinter

{

void printName(String name)

{

System.out.println("Your name is: " + name);

}

void printAge(int age)

{

System.out.println("Your age is: " + age);

}

void main(String[] args) {

NamePrinter np = new NamePrinter();

np.printName("John");

np.printAge(32);

}

}

A. 

Your name is: John

Your age is: 32

B. 

John

32

C. 

Your age is: 32

Your name is: John

D. 

32

John

E. An error message

Answer:

A. 

Your name is: John

Your age is: 32

What is the result of the following code?

class Shapes

{

double calculateCircleArea(double radius)

{

return Math.PI * Math.pow(radius, 2);

}

double calculateRectangleArea(double length, double width)

{

return length * width;

}

void main(String[] args) {

Shapes shapes = new Shapes();

System.out.println( shapes.calculateCircleArea(5) + shapes.calculateRectangleArea(10,2) );

}

}

A. 78.5

B. 80.5

C. 82.5

D. 98.5

E. An error message

Answer: D. 98.5

What will the following code output?

class Book

{

String title;

String author;

int pages;

Book(String bookTitle, String bookAuthor, int bookPages)

{

title = bookTitle;

author = bookAuthor;

pages = bookPages;

}

void printBookInfo()

{

System.out.println("Title: " + title);

System.out.println("Author: " + author);

System.out.println("Pages: " + pages);

}

void main(String[] args) {

Book book = new Book("The Great Gatsby", "F. Scott Fitzgerald", 180);

book.printBookInfo();

}

}

A. 

Title: 180

Author: The Great Gatsby

Pages: F. Scott Fitzgerald

B. 

Title: F. Scott Fitzgerald

Author: The Great Gatsby

Pages: 180

C. 

Title: The Great Gatsby

Author: F. Scott Fitzgerald

Pages: 180

D. The Great Gatsby, F. Scott Fitzgerald, 180

E. An error message

Answer: 

C. 

Title: The Great Gatsby

Author: F. Scott Fitzgerald

Pages: 180

What is the output of the following code?

class Employee

{

String name;

int salary;

Employee(String empName, int empSalary)

{

name = empName;

salary = empSalary;

}

void printEmployeeInfo()

{

System.out.println("Name: " + name);

System.out.println("Salary: $" + salary);

}

void giveRaise(int raiseAmount)

{

salary += raiseAmount;

}

void main(String[] args) {

Employee emp = new Employee("John", 50000);

emp.printEmployeeInfo();

emp.giveRaise(2000);

emp.printEmployeeInfo();

}

}

A. 

Name: John

Salary: $50000

Name: John

Salary: $52000

B. 

Name: John

Salary: $52000

Name: John

Salary: $50000

C. 

Name: John

Salary: $50000

Name: $2000

Salary: $52000

D. 

Name: John

Salary: $52000

Name: $2000

Salary: $50000

E. An error message

Answer: 

A. 

Name: John

Salary: $50000

Name: John

Salary: $52000

Consider the following method.

int sumNumbers(int num1, int num2, int num3)

{ /*implementation not shown */ }

Which of the following lines of code, if located in a method in the same class as sumNumbers, will compile without an error?

A. int result = sumNumbers(1, 2, 3);

B. double result = sumNumbers(1.0, 2.0, 3.0);

C. int result = sumNumbers(1.0, 2, 3);

D. double result = sumNumbers(1, 2, 3);

E. result = sumNumbers(1, 2, 3);

Answer: A. int result = sumNumbers(1, 2, 3);

Consider the following method.

boolean isValidEmail(String email)

{ /*implementation not shown */ }

Which of the following lines of code, if located in a method in the same class as isValidEmail, will compile without an error?

A. String result = isValidEmail("john@gmail.com");

B. int result = isValidEmail("john@gmail.com");

C. double result = isValidEmail("john@gmail.com");

D. boolean result = isValidEmail("john@gmail.com");

E. result = isValidEmail("john@gmail.com");

Answer: D. boolean result = isValidEmail("john@gmail.com");

Consider the following method.

String reverseString(String str)

{ /*implementation not shown */ }

Which of the following lines of code, if located in a method in the same class as reverseString, will compile without an error?

A. int result = reverseString("hello");

B. String result = reverseString("hello");

C. double result = reverseString("hello");

D. boolean result = reverseString("hello");

E. result = reverseString("hello");

Answer: B. String result = reverseString("hello");

Consider the following method.

int calculateTriangleArea(int base, double height)

{ /*implementation not shown */ }

Which of the following lines of code, if located in a method in the same class as calculateTriangleArea, will compile without an error?

A. int result = calculateTriangleArea(5, 10);

B. double result = calculateTriangleArea(5.0, 10.0);

C. int result = calculateTriangleArea(5.0, 10);

D. double result = calculateTriangleArea(5, 10.0);

E. result = calculateTriangleArea(5, 10);

Answer: D. double result = calculateTriangleArea(5, 10.0);

Consider the following .

class Animal

{

private String species;

private int age;

private double weight;

Animal(String animalSpecies, int animalAge, double animalWeight)

{

    species = animalSpecies;

    age = animalAge;

    weight = animalWeight;

}

void eat()

{

    weight += 5;

}

double getWeight()

{

    return weight;

}

}

Assume that the following code segment appears in a class other than Animal.

Animal dog = new Animal("Dog", 3, 15);

dog.eat();

System.out.println(dog.getWeight());

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

A. 20

B. 15

C. dog.getWeight()

D. The code will not compile.

E. 5

Answer: A. 20

Consider the following .

class Car

{

private String make;

private String model;

private int year;

private double speed;

Car(String carMake, String carModel, int carYear)

{

    make = carMake;

    model = carModel;

    year = carYear;

    speed = 0;

}

void accelerate()

{

    speed += 10;

}

double getSpeed()

{

    return speed;

}

}

Assume that the following code segment appears in a class other than Car.

Car car = new Car("Toyota", "Corolla", 2010);

car.accelerate();

System.out.println(car.getSpeed());

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

A. 0

B. 10

C. car.getSpeed()

D. The code will not compile.

E. Toyota

Answer: B. 10

Consider the following .

class Customer

{

private String name;

private String address;

private int phone;

private boolean isPremium;

Customer(String customerName, String customerAddress, int customerPhone, boolean customerIsPremium)

{

    name = customerName;

    address = customerAddress;

    phone = customerPhone;

    isPremium = customerIsPremium;

}

boolean getIsPremium()

{

    return isPremium;

}

}

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

Customer customer = new Customer("Jane", "123 Main St.", 555-1212, 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

Key Terms to Review (22)

Boolean Expressions

: Boolean expressions are statements that evaluate to either true or false. They are commonly used in programming to make decisions and control the flow of a program.

calculateCircleArea(double radius)

: The calculateCircleArea method is used to compute the area of a circle based on its radius. It takes in the radius as input and returns the calculated area.

calculateRectangleArea(double length, double width)

: The calculateRectangleArea method is used to calculate the area of a rectangle based on its length and width. It takes in the length and width as input parameters and returns the calculated area.

calculateTriangleArea(int base, double height)

: This function calculates the area of a triangle using its base length and height.

Class Definition

: A class definition is a blueprint or template for creating objects of a particular type. It defines the properties and behaviors that an object of that class will have.

Data Type

: A data type is a classification that specifies the type of value that a variable can hold. It determines the operations that can be performed on the variable, such as arithmetic operations or string manipulation.

eat()

: The eat() method is a function that allows an object to consume food or perform actions related to consuming food.

getIsPremium()

: The method getIsPremium() is used to check if a user has a premium account or not. It returns true if the user is a premium member, and false otherwise.

getSpeed()

: The method getSpeed() is used to retrieve the value of the speed attribute in a program. It returns the current speed of an object or entity.

giveRaise(int raiseAmount)

: This term refers to a function or method that increases an employee's salary by a specified amount.

isCondition()

: The isCondition() method is used in programming to check if a certain condition is true or false. It returns a boolean value, either true or false, based on the evaluation of the condition.

isValidEmail(String email)

: This method checks whether a given email address is valid or not.

methodName(parameterListOptional)

: A method name is an identifier that represents an action or behavior that an object can perform. It may also include optional parameters, which are values passed into the method for it to use during its execution.

Primitive Data

: Primitive data refers to basic data types that are built into a programming language, such as integers, floating-point numbers, characters, and booleans. These data types are not composed of other data types.

printBookInfo()

: This term refers to a method or function that displays information about a book, such as its title, author, and publication date.

public

: Public is an access modifier in Java that indicates unrestricted visibility for classes, methods, and variables. Public members can be accessed from any other class or package.

Reference Data

: Reference data refers to complex data types that are composed of multiple primitive or reference data types. Examples include arrays, objects, and strings. Unlike primitive data types, reference variables store references (memory addresses) rather than actual values.

Return Statement

: A return statement is used in functions/methods to specify what value should be sent back as output when the function is called. It terminates the execution of a function and returns control back to where it was called from.

reverseString(String str)

: This method takes a string as input and returns the reversed version of that string.

Static

: In programming, "static" refers to a variable or method that belongs to the class itself, rather than an instance of the class. It can be accessed without creating an object of the class.

sumNumbers(int num1, int num2, int num3)

: This term refers to a function or method that adds together three numbers and returns their sum.

variableName

: A variable name is a unique identifier that is used to store and refer to a value in a program. It must follow certain rules, such as starting with a letter or underscore, and cannot be a reserved keyword.


© 2024 Fiveable Inc. All rights reserved.

AP® and SAT® are trademarks registered by the College Board, which is not affiliated with, and does not endorse this website.


© 2024 Fiveable Inc. All rights reserved.

AP® and SAT® are trademarks registered by the College Board, which is not affiliated with, and does not endorse this website.