Lesson 3 User Defined Methiods
Lesson 3 User Defined Methiods
Question 1
Question 2
1. Pass by value.
2. Pass by reference.
Question 3
When a function returns the value, the entire function call can be assigned to a variable. Do you
agree with the statement?
Yes, when a function returns a value, we can assign the entire function call to a variable.
Below example illustrates the same:
When a function is invoked how many values can be returned from the function?
Question 5
Answer
Answer
Answer
Answer
Question 6
Write down the main function which calls the following function:
int square(int a)
{
return(a*a);
}
Answer
Pass by reference means that the arguments of the function are a reference to the original
objects and not a copy. So any changes that the called function makes to the objects are
visible to the calling function. Consider the below example:
class PassByReferenceExample {
public void demoRef(int a[]) {
for (int i = 0; i < 5; i++) {
a[i] = i;
}
}
Question 8
For a function to return a value, it should have a return type other than void in its function
prototype and it should return a value of the corresponding type using the return statement
in the function body.
Question 9
Pure functions doesn't have side effects. Impure functions have side effects.
Question 10
Write a function which is used to swap the values of two memory locations.
Answer
Answer
Question 11
All primitive data types are passed All reference data types like arrays and objects of classes are passed
using Call by value. using Call by reference.
Question 12
Question 13
Function overloading is the process of defining functions/methods within a class, that have
the same name but differ in the number and/or the data types of their arguments.
Advantages of function overloading are:
1. Function overloading is one of the ways in which Java implements the object
oriented concept of Polymorphism.
2. With Function overloading, programmers don't have to create and remember
different names for functions doing the same thing for different data types.
Question 14
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.
A function that calls itself inside its body is called a Recursive function.
Method signature comprises of the method name and the data types of the parameters. For
example, consider the below method:
Question 15
A function returns a value through the return statement. Once a return statement is
executed, the program control moves back to the caller function skipping the remaining
statements of the current function if any. A function can have multiple return statements
but only one of them will be executed. For example, consider the below method:
It uses a return statement to return a value of int type back to its caller.
Question 16
Question 17
The keyword 'void' signifies that the function doesn't return a value to the calling function.
Question 18
If a function contains several return statements, how many of them will be executed?
A function 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
function skipping the remaining statements of the current function.
Question 19
Question 20
• Primitive types
By value
• Reference types
By reference
Question 1
void test1(int n)
{
for(int x=1; x<=n; x++)
if(n%x == 0)
System. out.println(x);
}
if 12 is passed to n.
Output
1
2
3
4
6
12
Explanation
Question 2
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)
{
System.out.println( (int) c);
}
if 'm' is passed to c.
Output
109
Explanation
This function prints the ASCII code of its argument. When 'm' is passed to this function, its
ASCII code which is 109 gets printed as the output.
Question 4
Output
AMIT
Explanation
The first differing characters of "AMIT" and "AMAN" are 'I' and 'A', respectively. So output of
"AMIT".compareTo("AMAN") 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 output.
Solutions to Unsolved Java Programs
Question 1
import java.util.Scanner;
obj.discount(price);
}
}
Output
Question 2
Write a program to input a number. Use a function int Armstrong(int n) to accept the number.
The function returns 1, if the number is Armstrong, otherwise zero(0).
Sample Input: 153
Sample Output: 153 ⇒ 13 + 53 + 33 = 153
It is an Armstrong Number.
import java.util.Scanner;
if (cubeSum == n)
return 1;
else
return 0;
}
if (r == 1)
System.out.println(num + " is an Armstrong number");
else
System.out.println(num + " is not an Armstrong number");
}
}
Output
Question 3
Write a program to input a number and check and print whether it is a 'Pronic' number or not.
Use a function int Pronic(int n) to accept a number. The function 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;
return isPronic;
}
if (r == 1)
System.out.println(num + " is a pronic number");
else
System.out.println(num + " is not a pronic number");
}
}
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 divide by the first factor) and finally
displays both the factors.
Hint: Use a non-return type function 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;
int i;
for (i = 2; i <= n; i++) {
if (n % i == 0)
break;
}
int sf = n / i;
Output
Question 5
Write a function 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)!)
where, n! = 1 x 2 x 3 x .......... x n
import java.util.Scanner;
public class KboatFactorial
{
public long fact(int n) {
long f = 1;
return f;
Output
Question 6
Write a program using a function called area() to compute area of the following:
(a) Area of circle = (22/7) * r * r
(b) Area of square= side * side
(c) Area of rectangle = length * breadth
Display the menu to display the area as per the user's choice.
import java.util.Scanner;
switch(choice) {
case 'a':
System.out.print("Enter radius of circle: ");
double r = in.nextDouble();
double ca = (22 / 7.0) * r * r;
System.out.println("Area of circle = " + ca);
break;
case 'b':
System.out.print("Enter side of square: ");
double side = in.nextDouble();
double sa = side * side;
System.out.println("Area of square = " + sa);
break;
case 'c':
System.out.print("Enter length of rectangle: ");
double l = in.nextDouble();
System.out.print("Enter breadth of rectangle: ");
double b = in.nextDouble();
double ra = l * b;
System.out.println("Area of rectangle = " + ra);
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 lcm = (a * b) / x;
Output
Question 8
Write a program in Java to accept a word. Pass it to a function magic(String str). The function
checks the string for the presence of consecutive letters. If two letters are consecutive at any
position then the function 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;
if (isMagicStr)
System.out.println("It is a magic string");
else
System.out.println("It is not a magic string");
}
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;
Output
Question 10
Write a program in Java to accept a String from the user. Pass the String to a function
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;
Output
Question 11
Write a program in Java to accept a String from the user. Pass the String to a function
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;
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 function 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;
public class KboatEmployeeTax
{
public void tax(String name, int income) {
double tax;
if (income <= 250000)
tax = 0;
else if (income <= 500000)
tax = (income - 250000) * 0.1;
else if (income <= 1000000)
tax = 30000 + ((income - 500000) * 0.2);
else
tax = 50000 + ((income - 1000000) * 0.3);
Output
Question 13
Write a program in Java to accept a String from the user. Pass the String to a function
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;
}
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter a string: ");
String s = in.nextLine();
Output
Question 14
Write a program to accept 10 numbers in a Single Dimensional Array. Pass the array to a
function 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;
Output
Question 15
Write a class with the name Area using function overloading that computes the area of a
parallelogram, a rhombus and a trapezium.
Formula:
import java.util.Scanner;
Output
Question 16
Write a class with the name Perimeter using function 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;
Output
Question 17
1. 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.
2. 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;
1. 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.
2. 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;
}
}
Output
Question 19
Write a menu driven program using a method Number() to perform the following tasks:
1. Accept a number from the user and display it in its Binary Equivalents.
For example:
Sample Input: (21)10
Sample Output: (10101)2
2. Accept a binary number from the user and display it in its Decimal Equivalents.
For example:
Sample Input: (11101)2
Sample Output: (29)10
import java.util.Scanner;
long b = Long.parseLong(str);
return b;
}
long binary2Decimal(long n) {
long decimal = 0;
int base = 1;
long t = n;
while (t > 0) {
int d = (int)(t % 10);
decimal += d * base;
base *= 2;
t /= 10;
}
return decimal;
}
void number() {
Scanner in = new Scanner(System.in);
System.out.println("Enter 1 to display number in Binary
Equivalent");
System.out.println("Enter 2 to display number in Decimal
Equivalent");
System.out.print("Enter your choice: ");
int c = in.nextInt();
switch (c) {
case 1:
System.out.print("Enter a decimal number: ");
int num = in.nextInt();
long binNum = decimal2Binary(num);
System.out.println("Binary Equivalent");
System.out.println(binNum);
break;
case 2:
System.out.print("Enter a binary number: ");
long ipNum = in.nextLong();
long decNum = binary2Decimal(ipNum);
System.out.println("Decimal Equivalent");
System.out.println(decNum);
break;
default:
System.out.println("Incorrect Choice");
break;
}
}
}
Output
Question 20
1. void manip(String str, int p) with one String argument and one integer argument. It
displays the characters of even positions of String, if p is an even number otherwise, it
displays the characters of odd positions.
2. void manip(int a, char ch) with one integer argument and one character argument. It
computes the square root of the integer arguments if ch is 's', else it computes the cube
root of the integers.
import java.util.Scanner;
if (p % 2 == 0) {
s = 1;
}
for (int i = s; i < len; i = i + 2) {
char ch = str.charAt(i);
System.out.println(ch);
}
}
double res = 0;
if (ch == 's') {
res = Math.sqrt(a);
}
else {
res = Math.cbrt(a);
}
System.out.println(res);
}
Output
Question 21
1. void compare(int, int) — to compare two integers values and print the greater of the two
integers.
2. void compare(char, char) — to compare the numeric value of two characters and print
with the higher numeric value.
3. 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);
}
if (x > y) {
System.out.println(a);
}
else {
System.out.println(b);
}
int l1 = a.length();
int l2 = b.length();
Output
Question 22
1. void polygon(int n, char ch) — with one integer and one character type argument to draw
a filled square of side n using the character stored in ch.
2. void polygon(int x, int y) — with two integer arguments that draws a filled rectangle of
length x and breadth y, using the symbol '@'.
3. void polygon() — with no argument that draws a filled triangle shown below:
Example:
Output
Question 23
1. double series(double n) with one double argument and returns the sum of the series.
sum = (1/1) + (1/2) + (1/3) + .......... + (1/n)
2. 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
Output
Question 24
1. void display(int num) — checks and prints whether the number is a perfect square or not.
2. void display(String str, char ch) — checks and prints if the word str contains the letter ch
or not.
3. void display(String str) — checks and prints the number of special characters present in
the word str.
if (diff == 0)
System.out.println(num + " is a perfect square");
else
System.out.println(num + " is not a perfect square");
if (idx == -1)
System.out.println(ch + " not found");
else
System.out.println(ch + " found");
int count = 0;
int len = str.length();
Output
Question 25
1. 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'.
2. void display(String str1, String str2) — checks and prints whether both the words are
equal or not.
3. void display(String str, int n) — prints the character present at nth position in the word str.
if (temp.indexOf(ch) == 0 &&
temp.lastIndexOf(ch) == (len - 1))
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");
Question 26
1. void Joystring(String s, char ch1, char ch2) with one string argument and two character
arguments that replaces the character argument ch1 with the character argument ch2 in
the given String s and prints the new string.
Example:
Input value of s = "TECHNALAGY"
ch1 = 'A'
ch2 = 'O'
Output: "TECHNOLOGY"
2. void Joystring(String s) with one string argument that prints the position of the first space
and the last space of the given String s.
Example:
Input value of s = "Cloud computing means Internet based computing"
Output:
First index: 5
Last Index: 36
3. void Joystring(String s1, String s2) with two string arguments that combines the two
strings with a space between them and prints the resultant string.
Example:
Input value of s1 = "COMMON WEALTH"
Input value of s2 = "GAMES"
Output: COMMON WEALTH GAMES
(Use library functions)
Output
Question 27
1. 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
2. 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
3. double volume(double 1, double b, double h) — with length(l), breadth(b) and height(h)
as the arguments, returns the volume of a cuboid using the formula:
V = l*b*h ⇒ (length * breadth * height)
Output