Methods in Java
What are Methods?
A java method is a series of statements that perform
some repeated task. Java, being strictly object
oriented, any action can take place through methods
only. Think of a method as a subprogram that acts on
data and often returns a value.
There are two basic types of methods:
Built-in: Build-in methods are part of the compiler
package, such as [Link]( ) and
[Link](0).
User-defined: User-defined methods are created by
you, the programmer. These methods take-on names
that you assign to them and perform tasks that you
create.
Why do you need methods?
Allow several programmers to work independently on separate
concepts which can be assembled later to create the entire project.
allow for the repetition of sections of code without retyping the
code. In addition, methods can be saved and utilized again and again
in newly developed programs.
help to hide details of programs from the users.
• Functions need to be defined before they can be used
anywhere in the program.
The general form of function definition is :
[access-specifier]
[modifier] <returnType> <methodName>(<parmType> <parm
Name>) {
Method }
<bodyOfMethod>
definition
• Access-specifier can be public, protected and private.
• Modifier can be static, final, native, synchronized,
transient and volatile.
• Return type specifies the type of value the function returns.
• Method name must be a valid Java identifier.
• Parameter list is a comma separated list of variables .
Access-specifier, Modifier and
Parameters are optional
Function prototype
The first line of the function definition that tells the
program about the type of value returned by the function
and the type of arguments is called Prototype.
For instance:
public void demo(int a, char ch) → Function prototype
{
:
:
}
Function signature
The signature of a function/method refers to the number and
type of the arguments.
public void demo(int a, char ch)
{
:
:
} Function signature
Accessing a function/Function call
A function is called/invoked by providing the function name,
followed by the parameters being sent enclosed in parentheses.
public class Test
{ void main_prog( )
{ doIt( 1 ); →Function called
}
void doIt( int toDo )
{// Method logic goes here ... }
}
Example 1(No arguments & No return)
public class Main {
static void myMethod() {
[Link]("I just got executed!");
}
public static void main(String[] args) {
myMethod();
}
}
// Outputs "I just got executed!"
Example 2(with argument)
public class Main {
static void myMethod(String name) {
[Link](name + " Kapoor");
}
public static void main(String[] args) {
myMethod(“Karisma");
myMethod(“Ranbir");
myMethod(“Kareena");
}
}
// Karisma Kapoor
// Ranbir Kapoor
// Kareena Kapoor
Example 3(with more than one argument)
public class Main {
static void myMethod(String fname, int age) {
[Link](fname + " is " + age);
}
public static void main(String[] args) {
myMethod("Liam", 5);
myMethod("Jenny", 8);
myMethod("Anja", 31);
}
}
// Liam is 5
// Jenny is 8
// Anja is 31
Example 4(returning a value)
public class Main {
static int myMethod(int x) {
return 5 + x;
}
public static void main(String[] args) {
[Link](myMethod(3));
}
}
// Outputs 8 (5 + 3)
‘return’ statement
• return is a reserved keyword in Java i.e, we can’t use it
as an identifier.
• It is used to exit from a method, with or without a
value.
• There can be multiple return statement; however,
method can only return ONE value.
• Should be the last statement.
• Takes the control back to the calling method.
• Not mandatory, if method is returning void.
Example 5(returning a value to store in a var)
public class Main {
static int myMethod(int x, int y) {
return x + y;
}
public static void main(String[] args) {
int z = myMethod(5, 3);
[Link](z);
}
}
// Outputs 8 (5 + 3)
Actual/Formal
parameters
Formal parameter The parameter
defined in the parameter list of
the method and used in the
program.
Actual parameter The actual
expression or variable passed to
the program when it is called.
From the code snippet in the
previous slide, the value 1 passed
from the main_prog method to the
doIt() method is the actual
parameter, and the toDo parameter
in the doIt() method is the formal
parameter.
Example:
Instance variable/local variable/static variable
Instance(object) local Static(class)
• Variables • Variables that • Variables
declared within are accessible declared within
the class but only from the the class but
outside of any method or block outside of any
method in which they are method with the
• They are given declared. help of static
initial default • They are not keyword.
values given initial • They are given
• Individual copies default values. initial default
of each object. • Needn’t require values
specifying static • A single copy to
keyword with a be used by all
local variable objects.
Default values of instance/class variables
Type Default Value
byte 0 (of byte type)
short 0 (of short type)
int 0
long 0L
float 0.0F
double 0.0
char ‘\u0000’ (null character)
boolean fasle
String null
All reference types null
Static/Instance variables and methods
Static/Instance variable
Every object maintains its own copy of instance variables.
Static variables are shared. That means, only one copy is maintained, and
different objects share that copy.
It means, change made by one object is passed on to the next object.
A static variable can be accessed directly by the class name and doesn’t need any
object.
Static/Instance methods:
A static method can access only static variables, whereas instance methods
can access instance as well as static variables.
To invoke a static method within the class it is created, user does not need to
create an object. However, if it is called from any other class, reference to the
class is required. Hence, [Link]( ).
To invoke an instance method, user needs to create object.
public class Display
{
static int count=0;
int a=0;
void getCount(){
a=++count;
}
void giveCount(){
[Link]("a="+a);
EXAMPLE [Link]("count="+count);
}
public static void main(String args[]){
Display d1=new Display();
Display d2=new Display();
Display d3=new Display();
[Link]();
[Link]();
[Link]();
[Link]();
[Link]();
[Link](); } }
Pure Methods/Functions
The return value of the pure functions solely depends on its
arguments.
Hence, if you call the pure functions with the same set of
arguments, you will always get the same return values.
They do not modify the external state (not cause side effects)
and are not affected by external code. A side effect is any
change to the state of the program that occurs as a result of
calling the function. For example, if a function modifies a global
variable, that's a side effect.
Example of pure function - [Link](a, b)
Impure Methods/Functions
The return value of the impure functions does not solely depend
on its arguments.
Hence, if you call the impure functions with the same set of
arguments, you might get the different return values.
They modify the external state or cause side effects and are
affected by external code. They can modify instance and global
variables.
For example, [Link](), [Link]().
Method Overloading
Method Overloading in Java
If a class have multiple methods by same name but different parameters, it is
known as Method Overloading.
Suppose you have to perform addition of the given numbers but there can be any
number of arguments, if you write the method such as a(int,int) for two
parameters, and b(int,int,int) for three parameters then it may be difficult for you
as well as other programmers to understand the behaviour of the method
because its name differs. So, we perform method overloading to figure out the
program quickly.
Different ways to Overload a method
By changing number of arguments
By changing the data type Note: In java, Method Overloading is not
possible by changing the return type of the
method.
Method Overloading in Java
you cannot overload a method based on different return type but same argument
type and number in java.
In overloading it is must that the both methods have −
same name.
different parameters (different type or, different number or both).
• The return type doesn’t matter. If they don’t have different parameters, they both
are still considered as same method and a compile time error will be generated.
[Link] Overloading by changing the no. of arguments
class Calculation1{
void sum(int a,int b)
{ [Link](a+b); }
void sum(int a,int b,int c)
{ [Link](a+b+c); }
public static void main(String args[ ]){
Calculation1 obj=new Calculation1();
[Link](10,10,10);
[Link](20,20);
}
}
2. Method Overloading by changing data type of argument
class Calculation2{
void sum(int a,int b)
{ [Link](a+b); }
void sum(double a,double b)
{ [Link](a+b); }
public static void main(String args[]){
Calculation2 obj=new Calculation2();
[Link](10.5,10.5);
[Link](20,20);
}
}
Method Overloading and Type Promotion
Method Overloading and Type Promotion
class OverloadingCalculation{
void sum(int a,long b)
{ [Link](a+b); }
void sum(int a,int b,int c)
{ [Link](a+b+c); }
public static void main(String args[]){
OverloadingCalculation obj=new OverloadingCalculation();
[Link](20,20);
//now second int literal will be promoted to long
[Link](20,20,20); Note: Data type is not de-promoted
} implicitly for example double cannot be
} de-promoted to any type implicitly.