7 min read•Last Updated on June 18, 2024
Avanish Gupta
user_sophia9212
Avanish Gupta
user_sophia9212
Now, we will discuss adding parameters to the void methods mentioned in the previous section. With parameters, the method works like a function in math—different input parameters can give different outputs, but the same set of parameters give the same behavior. If there are no parameters, then the method always has the same behavior. All of these are assuming that these methods are calling on the same object because different objects have different characteristics, so they would return different behaviors otherwise.
Courtesy of Illustrative Mathematics.
This machine serves as a model for how methods work. The inputs are our parameters, the rule is the code inside our method, and the output is the result of the method, which may be a printed line of text or a changed variable.
The method signature is the same as a constructor signature, with the name of the method followed by the parameters and their types in parentheses. For example, here is a method that prints the perimeter of a rectangle:
public static void printRectanglePerimeter(double length, double width) {
[System.out.println](https://www.fiveableKeyTerm:System.out.println)(2 * (length + width));
}
To call the method, use the method signature, but plug in the values in place of the variables. Here is how:
printRectanglePerimeter(1.5, 2.5);
This will print out 8.0, which is the result of the calculation done in the method.
Like constructors, methods can be overloaded as well. Like constructors, we need to have a different order of parameter types. Thus, the following two overloaded are illegal since the orders of parameter types for both are both (double, double):
printRectanglePerimeter(double length, double width)
printRectanglePerimeter(double width, double length)
Here is how to write methods that are overloaded with the printRectanglePerimeter() method with the following assumptions:
public static void printRectanglePerimeter(double length, double width) {
System.out.println(2 * (length + width));
}
public static void printRectanglePerimeter(double side) {
System.out.println(4 * side);
}
public static void printRectanglePerimeter() {
System.out.println(0);
According to the overloaded method that we have just written, a call to printRectanglePerimeter(2.5) would print out 10.0, while a call to just printRectanglePerimeter() would print out 0.
Consider the following methods:
public void millimetersToInches(double mm)
{
double inches = mm * 0.0393701;
printInInches(mm, inches);
}
public void printInInches(double millimeters, double inches)
{
System.out.print(millimeters + "-->" + inches);
}
Assume that the method called millimetersToInches(25.4) appears in a method in the same class. What is printed as a result of the method call?
A. 25.4 –> 0.0393701
B. 25.4 –> 0.9990558
C. 25.4 –> 1.00000054
D. 0.0393701 –> 25.4
E. 0.9990558 –> 25.4
Answer: C. 25.4 –> 1.00000054
Consider the following methods:
public void milesToKilometers(double miles)
{
double km = miles * 1.60934;
printInKilometers(miles, km);
}
public void printInKilometers(double miles, double km)
{
System.out.print(miles + "-->" + km);
}
Assume that the method called milesToKilometers(1) appears in a method in the same class. What is printed as a result of the method call?
A. 1 –> 1.60934
B. 1 –> 0.621371
C. 1.60934 –> 1
D. 0.621371 –> 1
E. 1.60934 –> 0.621371
Answer: A. 1 –> 1.60934
Consider the following methods:
public void fahrenheitToCelsius(double fahrenheit)
{
double celsius = (fahrenheit - 32) * (5.0/9.0);
printInCelsius(fahrenheit, celsius);
}
public void printInCelsius(double fahrenheit, double celsius)
{
System.out.print(fahrenheit + "-->" + celsius);
}
Assume that the method called fahrenheitToCelsius(32) appears in a method in the same class. What is printed as a result of the method call?
A. 32 –> 0
B. 32 –> 5.0/9.0
C. 0 –> 32
D. 5.0/9.0 –> 32
E. 0 –> 5.0/9.0
Answer: A. 32 –> 0
Consider the following methods:
public void poundsToKilograms(double pounds)
{
double kilograms = pounds * 0.453592;
printInKilograms(pounds, kilograms);
}
public void printInKilograms(double pounds, double kilograms)
{
System.out.print(pounds + "-->" + kilograms);
}
Assume that the method called poundsToKilograms(2) appears in a method in the same class. What is printed as a result of the method call?
A. 2 –> 0.453592
B. 2 –> 0.907184
C. 0.453592 –> 2
D. 0.907184 –> 2
E. 0.453592 –> 0.907184
Answer: B. 2 –> 0.907184
Consider the following methods:
public void litersToGallons(double liters)
{
double gallons = liters * 0.264172;
printInGallons(liters, gallons);
}
public void printInGallons(double liters, double gallons)
{
System.out.print(liters + "-->" + gallons);
}
Assume that the method called litersToGallons(3.785) appears in a method in the same class. What is printed as a result of the method call?
A. 3.785 –> 1.2
B. 3.785 –> 0.264172
C. 1 –> 3.785
D. 0.264172 –> 3.785
E. 3.785 –> 0.99989102
Answer: E. 3.785 –> 0.99989102
Consider the following methods, which appear in the same class:
public void calculateArea(int length, int width)
{
int rectangleArea = length * width;
/* INSERT CODE HERE */
}
public void printArea(int area)
{
System.out.println("The area is: " + area);
}
Which of the following lines would go into / INSERT CODE HERE / in the method calculateArea in order to call the printArea method to print the area correctly?
A. printArea(retangleArea);
B. printArea(length);
C. printArea(width);
D. calculateArea(area);
E. calculateArea(length);
Answer: A. printArea(retangleArea);
Consider the following methods, which appear in the same class:
public void calculateSum(int num1, int num2)
{
int numSum = num1 + num2;
/* INSERT CODE HERE */
}
public void printSum(int sum)
{
System.out.println("The sum is: " + sum);
}
Which of the following lines would go into / INSERT CODE HERE / in the method calculateSum in order to call the printSum method to print the sum correctly?
A. printSum(num2);
B. printSum(num1);
C. printSum(numSum);
D. calculateSum(sum);
E. calculateSum(num1);
Answer: C. printSum(numSum);
Consider the following methods, which appear in the same class:
public void calculateAverage(int num1, int num2, int num3)
{
int numAverage = (num1 + num2 + num3) / 3;
/* INSERT CODE HERE */
}
public void printAverage(int average)
{
System.out.println("The average is: " + average);
}
Which of the following lines would go into / INSERT CODE HERE / in the method calculateAverage in order to call the printAverage method to print the average correctly?
A. calculateAverage(average);
B. printAverage(num1);
C. printAverage(num2);
D. printAverage(num3);
E. printAverage(numAverage);
Answer: E. printAverage(numAverage);
Consider the following methods, which appear in the same class:
public void calculateDiscount(int price, int discount)
{
int calculatedPrice = price - (price * discount / 100);
/* INSERT CODE HERE */
}
public void printDiscountedPrice(int discountedPrice)
{
System.out.println("The discounted price is: " + discountedPrice);
}
Which of the following lines would go into / INSERT CODE HERE / in the method calculateDiscount in order to call the printDiscountedPrice method to print the discounted price correctly?
A. printDiscountedPrice(calculatedPrice);
B. printDiscountedPrice(price);
C. printDiscountedPrice(discount);
D. calculateDiscount(calculatedPrice);
E. calculateDiscount(price);
Answer: A. printDiscountedPrice(calculatedPrice);
Consider the following methods, which appear in the same class:
public void calculateVolume(int length, int width, int height)
{
int boxVolume = length * width * height;
/* INSERT CODE HERE */
}
public void printVolume(int volume)
{
System.out.println("The volume is: " + volume);
}
Which of the following lines would go into / INSERT CODE HERE / in the method calculateVolume in order to call the printVolume method to print the volume correctly?
A. printVolume(width);
B. printVolume(volume);
C. printVolume(boxVolume);
D. printVolume(height);
E. calculateVolume(boxVolume);
Answer: C. printVolume(boxVolume);
What does the following code output:
public class MethodTrace
{
public void add(int x, int y)
{
System.out.println(x+y);
}
public void subtract(int x, int y)
{
System.out.println(x-y);
}
public static void main(String[] args) {
MethodTrace traceObj = new MethodTrace();
traceObj.add(5, 3);
System.out.print(" and ");
traceObj.subtract(5, 3);
}
}
A. 8 and 2
B. 2 and 8
C. 8 and -2
D. 2 and -8
E. Nothing, it does not compile.
Answer: A. 8 and 2
What is the output of the following code:
public class MethodTrace
{
public void concatenate(String x, String y)
{
System.out.println(x+y);
}
public void repeat(String x, int y)
{
for(int i=0; i<y; i++) {
System.out.print(x);
}
}
public static void main(String[] args) {
MethodTrace traceObj = new MethodTrace();
traceObj.concatenate("Hello", "World");
System.out.print(" and ");
traceObj.repeat("Hello", 3);
}
}
A. HelloWorld and WorldHello
B. WorldHello and HelloHelloHello
C. HelloWorld and HelloHelloHello
D. WorldHello and WorldWorldWorld
E. Nothing, it does not compile.
Answer: C. HelloWorld and HelloHelloHello
What is the output of the following code:
public class MethodTrace
{
public void add(int x, int y)
{
System.out.print(x+y);
}
public void divide(int x, int y)
{
System.out.println(x/y);
}
public static void main(String[] args) {
MethodTrace traceObj = new MethodTrace();
traceObj.add(4, 2);
System.out.print(" and ");
traceObj.divide(5, 2);
}
}
A. 6 and 2.5
B. 6 and 2
C. 6 and 3
D. 6 and 3.5
E. Nothing, it does not compile.
Answer: B. 6 and 2
What is the output of the following code:
public class MethodTrace
{
public void concatenate(String x, String y)
{
System.out.print(x+y);
}
public void toUpperCase(String x)
{
System.out.println(x.toUpperCase());
}
public static void main(String[] args) {
MethodTrace traceObj = new MethodTrace();
traceObj.concatenate("good", "bye");
System.out.print(" and ");
traceObj.toUpperCase("see you later");
}
}
A. goodbye and SEE YOU LATER
B. byegood and SEE YOU LATER
C. goodbye and LATER YOU SEE
D. byegood and LATER
Answer: A. goodbye and SEE YOU LATER
CalculateArea refers to the process of determining the size or extent of an enclosed shape or region using mathematical formulas or algorithms. It is commonly used in programming when working with geometric shapes.
Term 1 of 13
CalculateArea refers to the process of determining the size or extent of an enclosed shape or region using mathematical formulas or algorithms. It is commonly used in programming when working with geometric shapes.
Term 1 of 13
CalculateArea refers to the process of determining the size or extent of an enclosed shape or region using mathematical formulas or algorithms. It is commonly used in programming when working with geometric shapes.
Term 1 of 13
Void methods are methods in programming that do not return a value. They perform a specific task or action, but they do not produce any output.
Parameters: Parameters are variables that are passed into a method. They allow us to provide input values for the method to use.
Input Parameters: Input parameters are specific types of parameters that receive input values from the caller of a method.
Return Type: Return type is the data type of the value that a method returns. In void methods, there is no return type because they don't return any value.
Outputs refer to the results or values that are produced by a program or function when it is executed.
Inputs: Inputs are the values or data that are provided to a program or function before it is executed.
Return Value: The return value is the specific output that is returned by a function after it has been executed.
Standard Output: Standard output refers to the default output stream where data is displayed in a console or terminal window.
A method signature refers to the unique combination of a method's name and its parameter types. It helps distinguish one method from another.
Method Overloading: Method overloading occurs when multiple methods have the same name but different parameter lists in order to perform similar tasks with varying inputs.
Access Modifiers: Access modifiers determine the visibility and accessibility of methods, variables, and classes within a program.
Return Type: The return type specifies what type of value (if any) is returned by a method after it has been executed.
A constructor signature refers to the unique combination of a class's name and its parameter types. It helps create instances (objects) of that class with specific initial values.
Default Constructor: A default constructor is automatically created by Java if no constructor is explicitly defined in a class. It has no parameters and initializes the object with default values.
Parameterized Constructor: A parameterized constructor is a constructor that accepts one or more parameters, allowing you to initialize an object with specific values during its creation.
Instance Variables: Instance variables are variables declared within a class but outside of any method. They hold data that is unique to each instance (object) of the class.
CalculateArea refers to the process of determining the size or extent of an enclosed shape or region using mathematical formulas or algorithms. It is commonly used in programming when working with geometric shapes.
Perimeter: The distance around the boundary of a shape.
Geometry: The branch of mathematics that deals with the properties and relationships of points, lines, surfaces, and solids.
Algorithm: A step-by-step procedure or set of rules for solving a specific problem or accomplishing a specific task.
The term printArea refers to a function or method that outputs the calculated area of a shape onto a physical medium, such as paper or a computer screen.
calculateSum: CalculateSum is an operation that involves adding up multiple numbers together to obtain their total sum.
printSum: PrintSum refers to an action where the computed sum of multiple numbers is displayed on some physical medium for viewing purposes.
area: Area is the measurement of the space inside a two-dimensional shape, which is what printArea calculates.
CalculateSum is an operation that involves adding up multiple numbers together to obtain their total sum.
printArea: PrintArea is another operation, but instead of adding numbers together, it calculates and outputs the area of shapes.
printSum: Similar to calculateSum, this operation also involves outputting information onto some medium. However, instead of calculating sums, it prints out the total sum obtained from adding numbers together.
sum: Sum refers to the result obtained when adding two or more numbers together. CalculateSum computes this value.
PrintSum refers to an action where the computed sum of multiple numbers is displayed on some physical medium for viewing purposes.
printArea: Similar to printSum, this term involves outputting information onto a physical medium. However, instead of displaying sums, it prints out the calculated area of shapes.
calculateSum: This operation adds up multiple numbers together to obtain their total sum, which is then displayed using printSum.
sum: Sum refers to the result obtained when adding two or more numbers together. PrintSum displays this value on a physical medium.
CalculateAverage refers to the process of finding the mean value of a set of numbers by adding them up and dividing by the total count.
Sum: The sum is the result when you add up all the numbers in a set.
Mean: Mean is another term for average, representing the central value in a set of numbers.
Count: Count refers to the total number of items or elements in a given set.
PrintAverage refers to displaying or outputting the calculated average value on a screen or paper.
Output: Output is any information that is produced or displayed by a computer program.
Display: Display refers to showing or presenting data visually, such as on a screen or monitor.
Format: Format determines how data is arranged and presented, like choosing whether to display an average as a decimal or percentage.
CalculateDiscount means determining how much money can be saved from an original price by applying a percentage reduction.
Original Price: The original price represents the initial cost before any discount is applied.
Percentage Reduction/Off: Percentage reduction/off indicates how much less than the original price an item costs after a discount is applied.
Final Price: The final price is the amount you pay after the discount has been subtracted from the original price.