1) To reduce complexity: By dividing complex problems into small parts in the form of methods we can solve them easily.
2) Reuse: We can reuse a method several times wherever we need it.
3) Hiding details: The statements and variables are hidden in a particular method from other methods. Methods
are separate block of statements. The programmer need not bother about the variable names and statements of other methods.
Demo Program to Show the Uses
Find total area of two rectangles.
import java.util.*;
public class Rectangle
{
//area() method is executed two times (re-use)
public static double area
{
Scanner sc=new Scanner(System.in);
System.out.println(“Enter length and breadth");
double l=sc.nextDouble();
double b=sc.nextDouble();
double a=l*b;
return a;
}
public static void main()
{
double a1=area(); //re-use
double a2=area(); //re-use
double tot=a1+a2;
System.out.println(“Total area: ”+tot);
}
}
Definition, Syntax and Example
Define method.
A method is a named block of statements that carry out some specific tasks.
}
E.g.:
public static double area(double x, double y)
{
double a = x*y;
return a;
}
Note: The [ ] indicates that it is optional, i.e., not necessary to write.
Method Prototype / Method Header
Define method prototype with syntax and example.
A method prototype / header is the first line of the method definition that includes access specifier, modifier, return type, method name and list of parameters.
Syntax: [access_specifier] [modifier] returntype methodname([parameter list])
E.g.: public static double area(double x, double y)
The Access Specifiers / Visibility Modifiers
Define access specifiers (visibility modifiers)?
The way of accessing a method or variable or class from different methods of different classes in different
packages is referred to access specifiers.
They are public, protected and private.
Diagrammatic Representation of Packages
Packages abc and pqr
Description * There are two packages: abc and pqr. * In abc there are three classes: A, B and C.
* B is linked to A * In A there are two methods: area() and ab()
* In B and C also there are methods: ba() and ca() * In pqr there are three classes: P, Q and R
* Q is linked to same package class P * R is linked to different package class A
* area() can be specified in four different ways: 1) public static void area(), 2) protected static void area()
3) private static void area() and 4) static void area()
Which are the four accessibilities? Describe briefly each of them.
1) public: Accessible by any method of any class in any package.
E.g.: public static void area()
2) protected: Accessible by methods of same package classes and sub classes of the same class that are in other packages.
E.g.: protected static void area()
3) No specification (Default. This is also known as Friendly or Package). Accessible by methods of classes in the same package only.
E.g.: static void area()
4) private: Accessible by methods of same class only. Even methods of sub classes do not have access, though it is in same package.
E.g.: private static void area()
The static Modifier
Define static modifier
The static is a keyword to specify that a method or variable is common for the class not individual for objects.
E.g.: static void area()
static int b;
A Program to Demonstrate Use of static Keyword
Define a class Student. The name and totalMarks of each student are different. The totalSubjects (number of subjects)
is same to all students. Create two Student objects and input values of the objects.
import java.util.*;
public class Student
{
String name; //individual for each object
double totalMarks; //individual for each object
static int totalSubjects; //common for all objects
static Scanner sc = new Scanner(System.in); //the sc can be used in static and non-static methods
public void getNameMarks() //non-static individual for each object
{
System.out.println("Enter name and total marks");
name=sc.nextLine();
totalMarks=sc.nextDouble();
}
public static void gettotalSubjects() //common for all objects
{
System.out.println("Enter number of subjects");
totalSubjets=sc.nextInt();
}
public static void main()
{
Student s1 = new Student();
Student s2 = new Student();
s1.getNameMarks(); //object is required to call non-static method
s2.getNameMarks();
gettotalSubjects(); //No object to call it
}
}
Diagramatic Representation of Objects
* The s1 and s2 are objects. Objects are group of memory cells. * Non-static variables and non-static methods
are inside the groups. Each object gets individual copy of them. * The static variable and static methods outside the
groups and all objects share the single copy of them.
Two Types of Methods
There are two kinds of methods considering memory allocation.
They are member methods (instance methods) and class methods (static methods).
Example of member method: public void area() (Note: There is no static keyword.)
Example of class method: public static void area() (Note: There is static keyword.)
Member Method
Describe briefly about member method.
The method without static keyword is known as member method (i.e., method for objects) or instance method.
Separate Copies of a memeber method can be made for each objects.
Example of memeber method:
public void getNameMarks()
{ }
Class Method / Non-member method / static method
Describe briefly about class method.
The method with static keyword is known as class method (i.e., method common to all objects of a class)
or non-member method. There is only one copy of this method in memory.
Example of class method:
public static void gettotalSubjects()
{ }
Four Kinds of Variables
Which are the four kinds of variables?
Four kinds of variables are instance variables, class variables, local variables and argument variables.
Instance Variable / Data Member / Member Variable / Attributes / Characteristics
Describe briefly about instance variable.
The variable declared in class level without static keyword is instance variable. When objects are
created each object gets individual copy of this variable.
E.g.: public class Student
{
String name;
}
Class Variable (Static variable)
Describe briefly class variable.
The variable declared in class level with static keyword is class variable. Class variable is common
to all objects. Each object shares the single variable.
E.g.: public class Student
{
static int totalSubjects;
}
Local Variable
Describe briefly about local variable
Variable declared inside method body is local variable. A local variable has access in that method only.
E.g.: public static void area()
{
double a;
}
Argument Variable
Describe briefly about argument variables
Variables declared as arguments of a method are argument variables. Each argument variable should be
declared individually with comma separator (not ;). Argument variables have access in that method only.
E.g.: public static void area(double x, double y)
Static Scanner Object
What is the use of static Scanner object
Instead of creating Scanner object in various static methods we can create the object in class level
with static keyword. So we can avoid repetition.
E.g.: static Scanner br = new Scanner(System.in);
Return Type
What is meant by return type?
Data type of the value that is returned by the method is the return type of the method. If the type of the value
which is returned is double then the return type of the method is double. If the type of the value which is
returned is int then the return type is int. If a method does not return a value then the return type is void.
void Method
What is a void method?
The method does not return a value is void method
Method Name
What is the use of method name?
Method name is used to identify a method definition.
E.g.: public static double area(). The area is the method name.
Rules for Method Name
What are the care to be taken when a method is named
1) Identifiers can have only alphabets, digits, underscore and dollar sign.
h.c.f() is invalid; phone-bill() is in invalid. phone_bill() is valid.
2) They must not begin with a digit.
1stseries() is invalid. series1() is valid.
3) They must be a single word; space is not allowed.
phone Bill() is invalid.
Multiple words can be written as single word.
phoneBill() is valid.
4) They must not be a keyword or reserved word.
case() is invalid. Case() is valid.
5) Capital letters and small letters are treated different.
area() and Area() are different.
Conventions
What are the conventions when writing method names?
1) The method name should be meaningful.
2) Method name is in lowercase letters.
E.g.: area()
3) For multiple word names, the first letter of subsequent words can be uppercase letter.
E.g.: findArea(), calculateSalary().
4) The method name generally begins with a verb followed by a noun.
E.g.: findArea()
Parameters
What is meant by parameters?
Parameters are a comma separated list of variables or values in a method prototype
or method call inside their parenthesis. It is also known as arguments.
E.g.: (double x, double y) in method prototype. (l,b) in method call'
Actual Parameter and Formal Parameter
Describe actual parameter and formal parameter.
Parameter in the method call is actual parameter. Copies of actual values are passed
to formal parameter. E.g.: l,b in area(l,b);
Parameter in the function prototype is the formal parameter. Copies of the actual
values are received by formal parameter.
E.g.: double x, double y in area(double x, double y)
Is it necessary same variable names must be in actual parameter and formal parameter?
• Different variable names can be used in formal parameter and actual parameter because
values in variables are passed, not the variable name.
• Same variable names also can be used because both methods are different memory locations.
Different memory locations can hold variables with same name.
Method Signature
What is a method signature? Write syntax with an example.
The term method signature is referred to the method name with formal parameter.
Syntax: methodname(type variable1, type variable n)
E.g.: area(double x, double y)
The Method Body
Define method body.
Method body is statements enclosed in a pair of braces of method definition that carry out some specific tasks.
E.g.:
{
double a=l*b;
return a;
}
The return Statement
What is a return statement?
The statement that returns a value or returns the flow of execution from a method definition
to the method call is the return statement. E.g.: return a;
Examples of various return statements.
1) return a; Return of a value in a variable
2) return 1; Return of an int value
3) return true; Return of a boolean value
4) return “Even”; Return of a String value
5) return ‘A’; Return of a char value
6) return l*b; Return of value of an expression
7) return; Return of flow of execution.
It is optional in void functions.
How many values can be returned from a method?
Only one value can be returned from a method.
Method Call
What is a method call? Write syntax and example.
A method call is a statement that is used to execute a method definition.
Syntax: methodname([actual parameters]);
E.g.: area(l,b);
What is the care should be taken when a method returns a value?
If a method returns a value:
• The method call should be initialized / assigned to a variable of same data type of the returned value.
E.g.: double a = area(l,b);
• Or the method call should be in print statement.
E.g.: System.out.println(“Area = ” + area(l,b));
• Or it should be in if statement.
E.g.: if(area(l,b) > 100)
What is the care should be taken when a method is void type?
If the method is void type:
• Method call must not be with an assignment statement, in print statement and in if statement.
E.g.2: area(l,b);
Call By Value
What is call by value? Describe it with an example.
When a method is called by passing primitive values then it is call by value.
In call by value copies of values are passed to method definition.
Process is done with these copies and changes happen only on these copies and the original value remain unchanged.
E.g.:
public class Swap
{
static int a=8,b=6;
public static void byValue(int a, int b)
{
int c=a;
a=b;
b=c;
System.out.println("Result in byValue : a = "+a+", b = "+b);
}
public static void main()
{
System.out.println("Before method call: a = "+a+", b = "+b);
byValue(a,b);
System.out.println("After method call : a = "+a+", b = "+b);
}
}
Output:
Before method call : a = 8, b = 6
Result in byValue : a = 6, b = 8
After method call : a = 8, b = 6
Call By Reference
What is call by reference? Describe it with an example.
When a method is called by passing reference values like objects then it is known as call by reference.
Process is done with these reference values and the change that happens is reflected in the original data.
E.g.:
public class Swap
{
static int a=8,b=6;
public static void byReference(Swap ob)
{
int c=ob.a;
ob.a=ob.b;
ob.b=c;
System.out.println("Result in byReference: a = "+ob.a+", b = "+ob.b);
}
public static void main()
{
Swap obj = new Swap();
System.out.println("Before method call: a = "+ a+", b = "+ b);
byReference(obj);
System.out.println("After method call: a = "+a+", b = "+b);
}
}
Output:
Before method call : a = 8, b = 6
Result in byReference : a = 6, b = 8
After method call : a = 6, b = 8
Differentiate between Call By Value and Call By Reference.
When a method is called by a method call by passing primitive values then it is call by value.
When a method is called by a method call by passing reference values like objects then it is known
as call by reference.
In call by value copies of values are passed to method definition and these copies are received by
formal parameters. Process is done with these copies and changes happen only on these copies
and the original data remain unchanged.
In call by reference, reference of object or array is passed to method definition and this is
received by formal parameter. Process is done with this reference value and the change that
happens is reflected in the original data.
Arguments to the methods can be of two kinds. Which are they?
1) Primitive values. 2) Reference values.
How primitive values and objects and arrays are passed to methods?
Primitive values are passed by value (call by value)
and objects and arrays (reference type values) are passed by reference (call by reference).
What is the advantage of call by value?
Passing arguments by value is useful when the original values are not to be modified.
Call by value offers security that the function cannot harm original values.
What is the advantage of call by reference?
Passing arguments by reference is useful when the original values are to be modified.
Pure and Impure Methods
What is a pure method?
A pure method is the one that takes primitives as arguments but does not modify the original value of
the passed primitives.
E.g.:
public static void count(int c)
{
c=c+1;
}
Note: Value of c is modified in the method only. Original value is not modified.
What is an impure method?
An impure method is one that modifies the state of the received object.
E.g.:
public static void count(Number ob)
{
ob.c=ob.c+1;
}
What is a modifier method?
An impure method is also known as modifier method because it modifies the state of the received object.
Three Categories of Methods Considering Return Value
Which are the three categories of methods based on returning of values?
1) Computational methods: Methods that calculate some values and return the computed value.
For example, method to find average of some marks.
2) Manipulative methods: Methods that manipulate information and return a success or failure code.
For example boolean return type methods such as to check whether a number is even or odd.
3) Procedural methods: Methods that perform an action and has no explicit return value.
For example void return type methods such as to print something.
Various Categorizations of Methods
Which are the various categorizations of methods?
1) Considering defined by whom
a. Pre-defined methods
b. User-defined methods
2) Considering memory allocation
a. Member method / Instance methods
b. Class methods
3) Considering modification of original data
a) Pure methods
b) Impure methods
4) Considering return value
a) Computational methods
b) Manipulative methods
c) Procedural methods
Method Overloading
What is method overloading? Illustrate with an example.
Several different method definitions with same method name that are differentiable by number of arguments
or type of arguments is known as method overloading.
E.g.:
public class Shapes
{
public static void area(double x)
{
System.out.println("Area of circle : "+3.14*x*x);
}
public static void area(float x) //data type different
{
System.out.println("Area of square : "+x*x);
}
public static void area(double x, double y) //number of argument different
{
System.out.println("Area of rectangle: "+x*y);
}
public static void main()
{
area(10.0);
area(7.0f); //data type different
area(9.0,5.0); //number of argument different
}
}
Output:
Area of circle: 314.0
Area of square: 49.0
Area of rectangle: 45.0
Though method names are same a method call distinguishes its own method definition by matching
the actual argument with formal argument considering the data type and number of arguments.
How does a method call distinguish its method definition when method names are same?
By matching the actual argument with formal argument with data type and number of arguments,
a method call can distinguish its own method definition when method names are same.
What is the role of return type of method in method overloading?
There is no role for return type in method overloading; The role is for arguments.
How the method overloading become an important part of the OOP?
Polymorphism is one of the principles of OOP. Method overloading implements this principle.
So method overloading becomes an important part of the OOP.
Additional Questions
Method Prototypes
Define a prototype for method named direction() that receives a character
from NEWS as argument and returns the name of direction.
public static String direction(char c)
Write a method prototype for a method named response to receive true or false
from main() and returns “Yes” or “No”.
public static String response(boolean x)
Write a method prototype for a method named join to receive a word w and a sentence s from main() and returns the joined string str i.e., word follows sentence.
public static String join(String w, String s)
Method Dfenitions
Define a method named direction() that receives a character from NEWS as argument and returns the name of direction. Use switch statement.
public static String direction(char c)
{
switch(c)
{
case ‘N’ : return “North”;
case ‘E’ : return “East”;
case ‘W’ : return “West”;
case ‘S’ : return “South”;
default : return “Wrong character”;
}
}
Note: No need of break statement when there is return statement
Write a method named response to receive true or false as argument and returns “Yes” or “No”.
public static String response(boolean x)
{
if(x)
return “Yes”;
else
return “No”;
}
Write a method named join to receive a word w and a sentence s from main() and returns the joined string str i.e., word follows sentence.