Topics: User-Defined Methods
Que 1. What is Method?
Answer: A method in Java is a block of statements grouped together to perform a specific task. A method has a name, a return type, an optional list of parameters, and a body.
Que 2: How can you create a user-defined method in Java?
Answer: To create a user defined method in java, follow the given the structure:
return_type method_name(list of parameters separated by commas) {
statements
return statement
}
Que 3: Create a user defined method – calculate area of rectangle.
Answer: // Area of Rectangle
static double area_rectangle(double length, double breadth){
double area = length * breadth;
return area;
}
Que 4: Create a user defined method – calculate area of triangle.
Answer: // Area of Rectangle
static double area_triangle(double breadth, double height){
double area = (breadth * height ) / 2 ;
return area;
}
Que 5: What is static method?
Answer: The method which is declared static is called Static Method, It is also known as Class Method.
The static modifier allows us to call this method without an invoking object.
Que 6: Differentiate between Static and Non-static method?
Answer: Static method allows to call without an object of class, while non-static is invoked with the help of the instance of class.
Que 7: Write the statement to invoke a method?
Answer: To invoke / call a method, write the name of the method with appropriate arguments.
double a = rectangle_area(45.5, 78.5);
fd.prnMes(“Anjeev Singh”);
showMes(“Thanks for Watching”);
double SI = simpleint(5000, 10.5, 20);
Que 8. Write a user-defined method in java to perform the basic arithmetic operation:
(a) To find the sum of two numbers
(b) To find the difference of two numbers
(c) To find the product of two numbers
(d) To find the remainder.
(e) To find the quotient.
Answer:
static int add(int a , int b){
return (a+b);
}
static int difference(int a , int b){
return (a – b);
}
static int product(int a, int b){
return (a*b);
}
static int remainder(int a, int b){
return (a%b);
}
static int quotient(int a , int b){
return (a / b);
}
Que 9: Write a user defined a method, having return type void.
Answer:
void prnMes(String Mes){
System.out.println(Mes);
}
static void showMes(String Mes){
System.out.println(Mes);
}
Que 10: Define a static and non-static user defined method and its calling statement.
Answer:
void prnMes(String Mes){
System.out.println(Mes);
}
static void showMes(String Mes){
System.out.println(Mes);
}
Calling of Funtion:
FunctionDemo fd = new FunctionDemo();
fd.prnMes(“Anjeev Singh”); // non-static
showMes(“Thanks for Watching”); //static
Que 11: Write a user defined method to calculate Simple Interest and Compound Interest.
Answer:
static double simpleint(double p, double r, double t){
double si = (p*r*t)/100;
return si;
}
static double compoundint(double p,double r, double t){
double ci = p * Math.pow(1+r/100, t) – p;
return ci;
}