7 min read•Last Updated on June 18, 2024
Avanish Gupta
user_sophia9212
Avanish Gupta
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 reference data. You can store the results of methods in variables as well as follows:
dataType [variableName](https://www.fiveableKeyTerm:variableName) = [methodName(parameterListOptional)](https://www.fiveableKeyTerm:methodName(parameterListOptional));
To make a non-void method, we use the following method header format (with static being optional):
[public](https://www.fiveableKeyTerm: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
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.
Term 1 of 22
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.
Term 1 of 22
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.
Term 1 of 22
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.
Primitive Data: Primitive data refers to basic built-in datatypes such as integers, floating-point numbers, characters, and booleans.
Data Type: A datatype 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.
Array: An array is an ordered collection of elements with fixed size where each element can be accessed using an index. It is a type of reference data.
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.
Instance Variable: A variable that belongs to each individual object created from a class.
Class Method: A method that belongs to the class itself and can be called without creating an object.
Static Block: A block of code in a class that is executed only once when the class is loaded into memory.
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.
Function: A function is a block of code that performs a specific task. It can have input parameters and may or may not return a value.
Method: A method is similar to a function but is associated with an object or class in object-oriented programming.
Void: Void is used as a return type for functions/methods that do not return any value.
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.
If statement: A programming construct that allows you to execute a block of code if a certain condition is true.
Logical operators: Symbols such as AND (&&), OR (||), and NOT (!) used to combine multiple boolean expressions and create more complex conditions.
Comparison operators: Symbols such as ==, !=, <, >, <=, >= used to compare values and produce boolean results.
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.
if statement: A control structure that allows the program to make decisions based on whether a certain condition is true or false.
boolean data type: A data type that can only have two values - true or false.
comparison operators: Symbols used to compare two values and evaluate their relationship, such as == (equal to), != (not equal to), > (greater than), < (less than).
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.
Radius: The radius is the distance from the center of a circle to any point on its edge.
Area: In geometry, area refers to the amount of space occupied by an object or shape.
Method Overloading: Method overloading allows multiple methods with different parameters but with the same name within a single class.
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.
Length: The length refers to the measurement of an object or shape from one end to another in one dimension.
Width: The width refers to the measurement of an object or shape from side to side in one dimension.
Return Type: The return type specifies what type of value a method will return after it has finished executing.
This term refers to a method or function that displays information about a book, such as its title, author, and publication date.
getTitle(): This method returns the title of a book.
getAuthor(): This method returns the author of a book.
getPublicationDate(): This method returns the publication date of a book.
This term refers to a function or method that increases an employee's salary by a specified amount.
setSalary(double newSalary): This method sets the salary of an employee to a specific value.
calculateBonus(double bonusPercentage): This method calculates and adds a bonus amount based on a percentage of an employee's salary.
deductTaxes(): This method subtracts taxes from an employee's salary.
This term refers to a function or method that adds together three numbers and returns their sum.
multiplyNumbers(int num1, int num2): This function multiplies two numbers together and returns their product.
averageNumbers(int[] numbers): This function calculates and returns the average value of multiple numbers.
findMax(int[] numbers): This function finds and returns the largest number from a given list of numbers.
This method checks whether a given email address is valid or not.
String: A sequence of characters that can be manipulated and stored in variables.
Regular Expression: A pattern used to match strings with specific formats, like email addresses.
Validation: The process of checking if data meets certain criteria or requirements.
This method takes a string as input and returns the reversed version of that string.
Character Array: An array that stores individual characters of a string.
Indexing: The process of accessing individual elements within an array or collection by their position.
Palindrome: A word, phrase, number, or other sequence of characters that reads the same forward and backward.
This function calculates the area of a triangle using its base length and height.
Area Formulae: Mathematical formulas used to calculate areas for different shapes.
Base Length/Height Ratio: The relationship between the length of the base and height in various geometric shapes.
Geometry: The branch of mathematics that deals with the properties and relationships of points, lines, surfaces, solids, and higher-dimensional analogs.
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.
Object: An object is an instance of a class. It represents a specific entity with its own set of data and behavior.
Property: A property is a characteristic or attribute of an object. It stores data related to the object.
Method: A method is a function defined within a class that performs certain actions or operations on objects of that class.
The eat() method is a function that allows an object to consume food or perform actions related to consuming food.
chew(): This term refers to another method that can be used in conjunction with the eat() method. It represents the action of breaking down food into smaller pieces.
digest(): Another related term, digest(), represents the process of converting consumed food into energy or usable forms.
fullnessLevel: This variable keeps track of how much food has been eaten and helps determine when an object is satiated.
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.
setSpeed(): This method is used to change or update the value of the speed attribute.
accelerate(): This method increases the speed of an object by a certain amount.
decelerate(): This method decreases the speed of an object by a certain amount.
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.
setIsPremium(): This method is used to set or update the premium status for a user.
upgradeToPremium(): This method upgrades a regular account to premium status.
downgradeToRegular(): This method downgrades a premium account back to regular status.