Chapter 5
Chapter 5
Question 1
The method which changes the state of an object is known as:
pure method
impure method
replace method
Answer
impure method
Reason — The method which changes the state of an object is known as impure method.
Question 2
Parameters used in method call statement are known as:
defined parameter
passed parameter
actual parameter
formal parameter
Answer
actual parameter
Reason — Parameters used in method call statement are known as actual parameter.
Question 3
Parameters used in the method definition are called:
forward parameter
actual parameter
formal parameter
Answer
formal parameter
Reason — Parameters used in the method definition are called formal parameters.
Question 4
The process of calling a method in such a way that the change in the formal arguments reflects on the actual parameter is
known as:
call by reference
call by value
call by method
none
Answer
call by reference
Reason — The process of calling a method in such a way that the change in the formal arguments reflects on the actual
parameter is known as call by reference.
Question 5
A method with many definitions is called:
multiple method
method overloading
floating method
none
Answer
method overloading
Question 6
A method may be associated with:
return
call
promote
none
Answer
return
Question 7
Which of the following type can be used for a non-returnable method?
int
float
double
void
Answer
void
{}
[]
()
Answer
{}
Question 9
A method is invoked through an:
object
system
parameter
none
Answer
object
Question 1
A method can return only one value to its caller program.
Question 2
If a method does not return any value its return type is void.
Question 3
A method indicating the method name, return type along with method arguments is known as method header/prototype.
Question 4
The variables used to receive the values in method header are known as formal parameters.
Question 5
Method in a Java program resides in package.
Question 6
The entire method body is enclosed under curly brackets.
Question 7
The procedural method performs some actions without returning any output.
Question 8
A method contains header and body.
Question 9
Methods used with same name but different types of arguments are known as method overloading.
Question 10
A method that is called by itself in its body is known as recursive method.
Question 1
Calling and invoking a method is same.
True
Question 2
A method can use a single return statement.
True
Question 3
Overloading of methods even depends on return type.
False
Question 4
A method cannot be defined without parameters.
False
Question 5
A method body is enclosed within curly brackets.
True
Give output of the following method definitions and also write what mathematical operations they
carry out
Question 1
void test1(int n)
if(n % x == 0)
System.out.println(x);
}
if 12 is passed to n.
Answer
Output
12
Explanation
Question 2
while( a != b)
if ( a > b)
a = a — b;
else
a = b — a;
System.out.println(a);
Answer
Output
Infinite Loop
Explanation
Initial value of a is 4 and b is 17 as given in the question. As a and b are not equal, condition of while loop is true, first
iteration starts. a is less than b so if condition is false, a = b - a is executed and a becomes 17 - 4 = 13.
Condition of while loop is true so second iteration starts. Again, if condition is false. This time a becomes 17 - 13 =
4. Like this, the value of a keeps oscillating between 13 and 4 resulting in an infinite loop.
Question 3
void test3(char c)
{
if 'm' is passed to c.
Answer
Output
109
Explanation
This method prints the ASCII code of its argument. When 'm' is passed to this method, its ASCII code which is 109 gets
printed as the output.
Question 4
if(x.compareTo(y) > 0)
System.out.println(x);
else
System.out.println(y);
Answer
Output
AMIT
Explanation
will be ASCII Code of 'I' - ASCII Code of 'A' ⇒ 73 - 65 ⇒ 8. The if condition is true so string x which is "AMIT" gets printed as
The first differing characters of "AMIT" and "AMAN" are 'I' and 'A', respectively. So output of "AMIT".compareTo("AMAN")
the output.
Question 1
A method is a program module that is used simultaneously at different instances in a program. It helps a user to reuse the
same module multiple times in the program. Whenever you want to use a method in your program, you need to call it
through its name. Some of the components/features of a method are as described below:
(b) It is the value passed to the method at the time of its call.
(c) It is a return type that indicates that no value is returned from the method.
Answer
(c) void
(d) Polymorphism
Question 1
Define a method. What is meant by method prototype?
Answer
A program module used at different instances in a program to perform a specific task is known as a method or a function.
First line of method definition that contains the access specifier, return type, method name and a list of parameters is
called method prototype.
Question 2
What are the two ways of invoking methods?
Answer
Pass by value.
Pass by reference.
Question 3
When a method returns the value, the entire method call can be assigned to a variable. Do you agree with the statement?
Answer
Yes, when a method returns a value, we can assign the entire method call to a variable. The given example illustrates the
same:
int c = a + b;
return c;
System.out.println(z);
Question 4
When a method is invoked how many values can be returned from the method?
Answer
Question 5
Debug the errors and rewrite the following method prototypes:
Answer
Question 6
Write down the main method which calls the following method:
int square(int a)
return(a * a);
Answer
int sq = square(4);
Question 7
What happens when a method is passed by reference? Explain.
Answer
Pass by reference means that the arguments of the method are a reference to the original objects and not a copy. So any
changes that the called method makes to the objects are visible to the calling method. Consider the example given below:
class PassByReferenceExample {
a[i] = i;
System.out.println();
obj.demoRef(arr);
10 20 30 40 50
0 1 2 3 4
Here demoRef changes the values of array a and these changes are reflected in the array in the main method as well.
Question 8
In what situation does a method return a value?
Answer
For a method to return a value, it should have a return type other than void in its method prototype and it should return a
value of the corresponding type using the return statement in the method body.
Question 9
Differentiate between pure and impure methods.
Answer
Pure methods take objects and/or primitive data types as Impure methods change the state of
arguments but do not modify the objects. received objects.
Pure methods don't have side effects. Impure methods have side effects.
Question 10
Write a method which is used to swap the values of two memory locations.
Answer
(a) Swap the values of two memory locations by using a third variable:
int c = a;
a = b;
b = c;
(b) Swap the values of two memory locations without using a third variable:
a = a + b;
b = a - b;
a = a - b;
Question 11
Differentiate between call by value and call by reference.
Answer
Actual parameters are copied to formal parameters. Formal parameters refer to actual parameters. The
Any changes to formal parameters are not reflected changes to formal parameters are reflected onto
onto the actual parameters. the actual parameters.
All primitive data types are passed using Call by All reference data types like arrays and objects of
value. classes are passed using Call by reference.
Question 12
What are the advantages of defining a method in a program?
Answer
Methods help to manage the complexity of the program by dividing a bigger complex task into smaller, easily understood
tasks.
Question 13
What is meant by method overloading? In what way it is advantageous?
Answer
Method overloading is the process of defining methods within a class, that have the same name but differ in the number
and/or the data types of their arguments.
Method overloading is one of the ways in which Java implements the object oriented concept of Polymorphism.
With method overloading, programmers don't have to create and remember different names for functions doing the same
thing for different data types.
Question 14
Define the following:
Answer
(a) Return data type — Return data type specifies the type of value that the method should return. It is mentioned before
the method name in the method prototype. It can be any valid primitive or composite data type of Java. If no value is being
returned, it should be void.
(b) Access specifier — Access specifiers determine the type of access to the method. It can be either public, private or
protected.
(c) Parameter list — Parameter list is a comma-separated list of variables of a method along with their respective data
types. The list is enclosed within a pair of parentheses. Parameter list can be empty if the method doesn't accept any
parameters when it is called.
(d) Recursive method — A method that calls itself inside its body is called a recursive method.
(e) Method signature — Method signature comprises of the method name and the data types of the parameters. For
example, consider the given method:
int c = a + b;
return c;
Question 15
Explain the function of a return statement in Java programming.
Answer
A method returns a value through the return statement. Once a return statement is executed, the program control moves
back to the caller method skipping the remaining statements of the current method if any. A method can have multiple
return statements but only one of them will be executed. For example, consider the given method:
int c = a + b;
return c;
It uses a return statement to return a value of int type back to its caller.
Question 16
Differentiate between formal parameter and actual parameter.
Answer
They represent the values received by the called They represent the values passed to the called
method. method.
Question 17
What is the role of the keyword void in declaring methods?
Answer
The keyword 'void' signifies that the method doesn't return a value to the calling method.
Question 18
If a method contains several return statements, how many of them will be executed?
Answer
A method can have multiple return statements but only one of them will be executed because once a return statement is
executed, the program control moves back to the caller method, skipping the remaining statements of the current method.
Question 19
Which OOP principle implements method overloading?
Answer
Question 20
How are the following data passed to a method?
Primitive types
Reference types
Answer
By value
By reference
Question 1
Write a program in Java using a method Discount( ), to calculate a single discount or a successive discount. Use overload
methods Discount(int), Discount(int,int) and Discount(int,int,int) to calculate single discount and successive discount
respectively. Calculate and display the amount to be paid by the customer after getting discounts on the printed price of an
article.
Sample Input:
Printed price: ₹12000
Successive discounts = 10%, 8%
= ₹(12000 - 1200)
= ₹(10800 - 864)
Amount to be paid = ₹9936
import java.util.Scanner;
public class KboatSuccessiveDiscount
return priceAfterDisc;
return priceAfterDisc2;
obj.discount(price);
}
}
Output
Question 2
Write a program to input a three digit number. Use a method int Armstrong(int n) to accept the number. The method
returns 1, if the number is Armstrong, otherwise zero(0).
It is an Armstrong Number.
import java.util.Scanner;
num /= 10;
}
if (cubeSum == n)
return 1;
else
return 0;
int r = obj.armstrong(num);
if (r == 1)
else
Output
Question 3
Write a program to input a number and check and print whether it is a 'Pronic' number or not. Use a method int Pronic(int
n) to accept a number. The method returns 1, if the number is 'Pronic', otherwise returns zero (0).
(Hint: Pronic number is the number which is the product of two consecutive integers)
Examples:
12 = 3 * 4
20 = 4 * 5
42 = 6 * 7
import java.util.Scanner;
int isPronic = 0;
if (i * (i + 1) == n) {
isPronic = 1;
break;
}
return isPronic;
int r = obj.pronic(num);
if (r == 1)
else
Output
Question 4
Write a program to enter a two digit number and find out its first factor excluding 1 (one). The program then find the
second factor (when the number is divided by the first factor) and finally displays both the factors.
Hint: Use a non-return type method as void fact(int n) to accept the number.
Sample Input: 21
The first factor of 21 is 3
Sample Output: 3, 7
Sample Input: 30
The first factor of 30 is 2
Sample Output: 2, 15
import java.util.Scanner;
return;
}
int i;
if (n % i == 0)
break;
int sf = n / i;
obj.fact(num);
Output
Question 5
Write a method fact(int n) to find the factorial of a number n. Include a main class to find the value of S where:
S=n!m!(n−m)!S=m!(n−m)!n!
where, n! = 1 x 2 x 3 x .......... x n
import java.util.Scanner;
f *= i;
return f;
System.out.print("Enter m: ");
int m = in.nextInt();
System.out.print("Enter n: ");
int n = in.nextInt();
System.out.println("S=" + s);
Output
Question 6
Write a program using a method called area() to compute area of the following:
Display the menu to display the area as per the user's choice.
import java.util.Scanner;
switch(choice) {
case 'a':
double r = in.nextDouble();
break;
case 'b':
break;
case 'c':
double l = in.nextDouble();
double b = in.nextDouble();
double ra = l * b;
break;
default:
System.out.println("Wrong choice!");
Output
Question 7
Write a program using method name Glcm(int,int) to find the Lowest Common Multiple (LCM) of two numbers by GCD
(Greatest Common Divisor) of the numbers. GCD of two integers is calculated by continued division method. Divide the
larger number by the smaller, the remainder then divides the previous divisor. The process is repeated till the remainder is
zero. The divisor then results in the GCD.
LCM = product of two numbers / GCD
import java.util.Scanner;
int x = a, y = b;
while (y != 0) {
int t = y;
y = x % y;
x = t;
}
int lcm = (a * b) / x;
int x = in.nextInt();
int y = in.nextInt();
obj.Glcm(x, y);
Output
Question 8
Write a program in Java to accept a word. Pass it to a method magic(String str). The method checks the string for the
presence of consecutive letters. If two letters are consecutive at any position then the method prints "It is a magic string",
otherwise it prints "It is not a magic string".
Sample Input: computer
Sample Output: It is not a magic string
Sample Input: DELHI
Sample Output: It is a magic string
import java.util.Scanner;
String t = str.toUpperCase();
isMagicStr = true;
break;
if (isMagicStr)
else
obj.magic(word);
Output
Question 9
Write a program using a method Palin( ), to check whether a string is a Palindrome or not. A Palindrome is a string that
reads the same from the left to right and vice versa.
Sample Input: MADAM, ARORA, ABBA, etc.
import java.util.Scanner;
String s = in.nextLine();
isPalin = false;
break;
if (isPalin)
else
Output
Question 10
Write a program in Java to accept a String from the user. Pass the String to a method Display(String str) which displays the
consonants present in the String.
Sample Input: computer
Sample Output:
c
m
p
t
r
import java.util.Scanner;
String t = str.toUpperCase();
char ch = t.charAt(i);
ch != 'E' &&
ch != 'I' &&
ch != 'O' &&
ch != 'U') {
System.out.println(str.charAt(i));
String s = in.nextLine();
obj.display(s);
Output
Question 11
Write a program in Java to accept a String from the user. Pass the String to a method Change(String str) which displays the
first character of each word after changing the case (lower to upper and vice versa).
Sample Input: Delhi public school
Sample Output:
d
P
S
import java.util.Scanner;
char ch = t.charAt(i+1);
if (Character.isUpperCase(ch))
ch = Character.toLowerCase(ch);
else if (Character.isLowerCase(ch))
ch = Character.toUpperCase(ch);
System.out.println(ch);
String s = in.nextLine();
obj.change(s);
Output
Question 12
Write a program in Java to accept the name of an employee and his/her annual income. Pass the name and the annual
income to a method Tax(String name, int income) which displays the name of the employee and the income tax as per the
given tariff:
Up to ₹2,50,000 No tax
import java.util.Scanner;
double tax;
tax = 0;
else
int i = in.nextInt();
obj.tax(n, i);
Output
Question 13
Write a program in Java to accept a String from the user. Pass the String to a method First(String str) which displays the
first character of each word.
Sample Input : Understanding Computer Applications
Sample Output:
U
C
A
import java.util.Scanner;
System.out.println(ch);
String s = in.nextLine();
obj.first(s);
Output
Question 14
Write a program to accept 10 numbers in a Single Dimensional Array. Pass the array to a method Search(int m[], int ns) to
search the given number ns in the list of array elements. If the number is present, then display the message 'Number is
present' otherwise, display 'number is not present'.
import java.util.Scanner;
if (m[i] == ns) {
found = true;
break;
if (found)
System.out.println("Number is present");
else
}
public static void main(String args[]) {
System.out.println("Enter 10 numbers");
arr[i] = in.nextInt();
obj.search(arr, num);
Output
Question 15
Write a class with the name Area using method overloading that computes the area of a parallelogram, a rhombus and a
trapezium.
Formula:
import java.util.Scanner;
return a;
double a = c * d1 * d2;
return a;
double x = c * (a + b) * h;
return x;
double ht = in.nextDouble();
double d1 = in.nextDouble();
double d2 = in.nextDouble();
double b = in.nextDouble();
double h = in.nextDouble();
Output
Question 16
Write a class with the name Perimeter using method overloading that computes the perimeter of a square, a rectangle and
a circle.
Formula:
Perimeter of a square = 4 * s
Perimeter of a rectangle = 2 * (l + b)
import java.util.Scanner;
double p = 4 * s;
return p;
double p = 2 * (l + b);
return p;
double p = c * pi * r;
return p;
double b = in.nextDouble();
double r = in.nextDouble();
Output
Question 17
Design a class overloading and a method display( ) as follows:
void display(String str, int p) with one String argument and one integer argument. It displays all the uppercase characters if
'p' is 1 (one) otherwise, it displays all the lowercase characters.
void display(String str, char chr) with one String argument and one character argument. It displays all the vowels if chr is 'v'
otherwise, it displays all the alphabets.
import java.util.Scanner;
public class Overloading
char ch = str.charAt(i);
if (p == 1 && Character.isUpperCase(ch)) {
System.out.println(ch);
System.out.println(ch);
char ch = str.charAt(i);
ch = Character.toUpperCase(ch);
System.out.println(str.charAt(i));
ch == 'E' ||
ch == 'I' ||
ch == 'O' ||
ch == 'U') {
System.out.println(str.charAt(i));
String s = in.nextLine();
System.out.println("p=1");
obj.display(s, 1);
System.out.println("\np!=1");
obj.display(s, 0);
System.out.println("\nchr='v'");
obj.display(s, 'v');
System.out.println("\nchr!='v'");
obj.display(s, 'u');
Output
Question 18
Design a class overloading a method calculate() as follows:
void calculate(int m, char ch) with one integer argument and one character argument. It checks whether the integer
argument is divisible by 7 or not, if ch is 's', otherwise, it checks whether the last digit of the integer argument is 7 or not.
void calculate(int a, int b, char ch) with two integer arguments and one character argument. It displays the greater of
integer arguments if ch is 'g' otherwise, it displays the smaller of integer arguments.
import java.util.Scanner;
if (ch == 's') {
if (m % 7 == 0)
else
else {
if (m % 10 == 7)
else
if (ch == 'g')
else
int n1 = in.nextInt();
obj.calculate(n1, 's');
obj.calculate(n1, 't');
n1 = in.nextInt();
int n2 = in.nextInt();
Output
Question 19
Design a class to overload a method compare( ) as follows:
void compare(int, int) — to compare two integers values and print the greater of the two integers.
void compare(char, char) — to compare the numeric value of two characters and print with the higher numeric value.
void compare(String, String) — to compare the length of the two strings and print the longer of the two.
import java.util.Scanner;
if (a > b) {
System.out.println(a);
else {
System.out.println(b);
int x = (int)a;
int y = (int)b;
if (x > y) {
System.out.println(a);
else {
System.out.println(b);
}
public void compare(String a, String b) {
int l1 = a.length();
int l2 = b.length();
System.out.println(a);
else {
System.out.println(b);
int n1 = in.nextInt();
int n2 = in.nextInt();
obj.compare(n1, n2);
char c1 = in.next().charAt(0);
char c2 = in.next().charAt(0);
in.nextLine();
obj.compare(c1, c2);
String s2 = in.nextLine();
obj.compare(s1, s2);
Output
Question 20
Design a class to overload a method series( ) as follows:
double series(double n) with one double argument and returns the sum of the series.
sum = (1/1) + (1/2) + (1/3) + .......... + (1/n)
double series(double a, double n) with two double arguments and returns the sum of the series.
sum = (1/a2) + (4/a5) + (7/a8) + (10/a11) + .......... to n terms
double series(double n) {
double sum = 0;
sum += term;
return sum;
double sum = 0;
int x = 1;
int e = x + 1;
sum += term;
x += 3;
return sum;
Output
Question 21
Design a class to overload the method display(.....) as follows:
void display(int num) — checks and prints whether the number is a perfect square or not.
void display(String str, char ch) — checks and prints if the word str contains the letter ch or not.
void display(String str) — checks and prints the number of special characters present in the word str.
if (diff == 0)
else
if (idx == -1)
else
int count = 0;
char ch = str.charAt(i);
if (!Character.isLetterOrDigit(ch) &&
!Character.isWhitespace(ch)) {
count++;
obj.display(18);
obj.display("https://www.knowledgeboat.com/");
}
}
Output
Question 22
Design a class to overload the method display(.....) as follows:
void display(String str, char ch) — checks whether the word str contains the letter ch at the beginning as well as at the end
or not. If present, print 'Special Word' otherwise print 'No special word'.
void display(String str1, String str2) — checks and prints whether both the words are equal or not.
void display(String str, int n) — prints the character present at nth position in the word str.
ch = Character.toUpperCase(ch);
if (temp.indexOf(ch) == 0 &&
System.out.println("Special Word");
else
System.out.println("No Special Word");
if (str1.equals(str2))
System.out.println("Equal");
else
System.out.println("Not Equal");
return;
System.out.println(ch);
obj.display("Tweet", 't');
obj.display("Tweet", "Massachusetts");
obj.display("Massachusetts", 8);
}
}
Output
Question 23
Design a class to overload a method volume( ) as follows:
double volume(double r) — with radius (r) as an argument, returns the volume of sphere using the formula:
V = (4/3) * (22/7) * r * r * r
double volume(double h, double r) — with height(h) and radius(r) as the arguments, returns the volume of a cylinder using
the formula:
V = (22/7) * r * r * h
double volume(double 1, double b, double h) — with length(l), breadth(b) and height(h) as the arguments, returns the
double volume(double r) {
return vol;
return vol;
}
double volume(double l, double b, double h) {
double vol = l * b * h;
return vol;
obj.volume(6));
obj.volume(5, 3.5));
Output