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 reference data. You can store the results of methods in variables as well as follows:
dataType variableName = methodName(parameterListOptional);
To make a non-void method, we use the following method header format (with static being optional):
public (static) dataType methodName(parameterListOptional)
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:
public static double rectanglePerimeter(double length, double width) {
return 2 * (length + width);
some other code
}
The most important change is the substitution of the print statement with the return statement. The return statement takes the expression on that line, evaluates it, and returns it to the program that called the method for use. The return statement stops the method execution and ignores any code below the return statement. In the example above, the "some other code" will never be run since it is after the return statement.
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 boolean expressions 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)
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!
Methods which return objects or other reference types are similar to those which return strings in which they either create new reference data or modify parts of this reference data. We will learn about these in Units 5-8!
What is the output of the following code?
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) );
}
}
A. 10
B. 17
C. 21
D. 23
E. An error message
Answer: B. 17
What will the following code print out?
public class NamePrinter
{
public void printName(String name)
{
System.out.println("Your name is: " + name);
}
public void printAge(int age)
{
System.out.println("Your age is: " + age);
}
public static 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?
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) );
}
}
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?
public class Book
{
public String title;
public String author;
public int pages;
public Book(String bookTitle, String bookAuthor, int bookPages)
{
title = bookTitle;
author = bookAuthor;
pages = bookPages;
}
public void printBookInfo()
{
System.out.println("Title: " + title);
System.out.println("Author: " + author);
System.out.println("Pages: " + pages);
}
public static 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?
public class Employee
{
public String name;
public int salary;
public Employee(String empName, int empSalary)
{
name = empName;
salary = empSalary;
}
public void printEmployeeInfo()
{
System.out.println("Name: " + name);
System.out.println("Salary: $" + salary);
}
public void giveRaise(int raiseAmount)
{
salary += raiseAmount;
}
public static 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.
public 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.
public 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.
public 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.
public 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 definition.
public class Animal
{
private String species;
private int age;
private double weight;
public Animal(String animalSpecies, int animalAge, double animalWeight)
{
Β Β Β Β species = animalSpecies;
Β Β Β Β age = animalAge;
Β Β Β Β weight = animalWeight;
}
public void eat()
{
Β Β Β Β weight += 5;
}
public 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 definition.
public class Car
{
private String make;
private String model;
private int year;
private double speed;
public Car(String carMake, String carModel, int carYear)
{
Β Β Β Β make = carMake;
Β Β Β Β model = carModel;
Β Β Β Β year = carYear;
Β Β Β Β speed = 0;
}
public void accelerate()
{
Β Β Β Β speed += 10;
}
public 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 definition.
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.
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