Functions in Java
Functions in Java
The term method is used alternatively with function and means the same in Java
programming language. A larger block of code is broken down into smaller and
simpler modules called ‘member methods’ this is how the OOP language Java
implements ‘Modularity’.
Types of function
Userdefined functions are created by the user to carry out some specific tasks.
Name of the function is declared by the user.
Anatomy of a function
FUNCTION NAME ( )
{
Body of the function…
}
1
c. protected
d. friendly this is not a keyword and hence cannot be written explicitly.
2. These are keywords which redefines the functionality within the methods. They
can be final, native, static, synchronized, transient, volatile etc…
3. They specify what type of value a function can return, hence they can be of any
primitive of reference data types like int, byte, float, char, String or even class types.
In case the function doesn’t return any value the keyword ‘void’ is used.
4. Function name – This can be any valid identifier, but it is always advisable to take
logical and meaningful names, it should conventionally begin with a lowercase letter
and in case of multiple words join the words and begin each word in Uppercase
except for the first word.
e.g. toUpperCase( )
5. This is a comma separated list of variables along with associated data types. This
list can also be empty which indicates the function is non–argumentative.
e.g.
public static void add(int a, int b)
{
…
}
Function prototype
The first line of a function that consists of access specifier, modifier, return type,
function name and list of parameters enclosed within a pair of parenthesis is called
function prototype.
A function prototype describes the function interface to the compiler, by giving
details of number and type of arguments, return type etc…
e.g.
public static void compute(int a, int b)
{
…
…
}
Function signature
The function signature is a part of function prototype; it basically refers to the
argument list i.e. number, order and type of arguments.
e.g.
public static void compute(int a, int b)
{
2
…
…
}
Public members are accessible everywhere, within the same class as well as inside
other classes that inherits the base class or by creating objects of the former class in
the latter one even if they do not inherit, but private members are accessible only
within the same class.
obj1.x=10;
obj2.x=20; // the same variable ‘x’ has three different values simultaneously
obj3.x=30;
y = 100; // the variable ‘y’ being static is accessed directly and can have only
// one value
obj1.y=100;
obj2.y=200; // even if we try to access the variable ‘y’ through different objects
3
obj3.y=300; // the same ‘y’ gets overwritten and finally the last value prevails
}}
So, we see that if a member is static in nature it will have only one copy in the
physical memory of the computer, which can be accessed directly without the need
of creating objects. But if it is non-static then we need to create objects to specify
which instance we are referring to as it has multiple occurrences.
The formal parameters are those that appear at the point of function declaration or
function signature are called Formal parameters.
e.g.
public static void main( )
{
int x = 10, y = 20;
actual parameters add (x, y);
}
4
A function be of one of the four types depending on its argument list and return type
–
1. Non-argumentative & non-return type
Example
class ABCD
{
public static void main( )
{
display( );
}
public static void display( )
{
System.out.println(“Loyola School”);
}
}
2. Argumentative & non-return type
Example
class ABCD
{
public static void main( )
{
int x = 10;
display(x);
}
public static void display(int x)
{
System.out.println(“The value of x =” + x);
}
} // Note that a function which is void cannot return any value
3. Non-argumentative & return type
Example
class ABCD
{
public static void main( )
{
int x = display( );
System.out.println(“The value of x =” + x);
}
public static int display( )
{
int x = 10;
return x;
}
} // Note that the return type of the function and the variable associated
5
// with the keyword return must be identical, also note that the function
// at the point of invocation gets equated with a similar datatype.
6
1. Computational functions – The functions that computes or calculates certain
values or quantities and returns the answer to the calling method is called
Computational function.
e.g. Math.pow(a,b);
2. Manipulative functions – The functions which manipulates the data and returns
information to the calling function as success or failure code in the form of 0 & 1 or
true & false.
e.g. Character.isLetter( )
An impure function on the other hand modifies the state of its objects or
arguments.
They are also known as Modifier methods.
Pure Functionpublic static int maximum(int a, int b)
{
int c = Math.max(a,b);
return c;
}
Impure Functionpublic static int product(int a)
{
a = a * a;
return a;
}
Function Overloading
A function name having several definitions in the same scope that are differentiated
on the basis of function signature i.e. number of arguments, order of arguments, type
of arguments is said to be an overloaded function and the process of creating such
functions is called Function Overloading.
7
public static void area(int s)
{
System.out.println(“Area of square =” + (s*s));
}
public static void area(int l, int b)
{
System.out.println(“Area of rectangle =” + (l*b));
}
public static void area(double r)
{
System.out.println(“Area of circle =” + (3.1415 * r * r));
}
}
________________________________
CONSTRUCTORS
Constructor in java is a special type of method that is used to initialize the object.
Java constructor is invoked at the time of object creation. It constructs the values i.e. provides data for the
object that is why it is known as constructor.
Rules for creating java constructor, There are basically two rules defined for the constructor.
class Constr
{
int n;
Constr( )
{
n = 0;
} // invokes the constructor
8
1. Non Parameterized Constructors
2. Parameterized Constructors
A constructor that accepts no parameters are called non
parameterized constructors, non parameterized constructors that initialize the
instance variables to zero, null and empty values are called Default
Constructors. Above is an example of default constructor.
this keyword is used to refer to the object on which a method was invoked.
The method printX() will print 4 and not 3. This is because when we declare a variable in a
method with the same name as that of another instance variable, then when we refer to that
variable within the method, we get access to the variable defined in the method and not the
instance variable of the class. This is illustrated in the following diagram:
10
Constructor Overloading in Java
Constructor overloading is a technique in Java in which a class can have any number of constructors that
differ in parameter lists.The compiler differentiates these constructors by taking into account the number of
parameters in the list and their type.
class Student5{
int id;
String name;
int age;
Student5(int i,String n){
id = i;
name = n;
}
Student5(int i,String n,int a){
id = i;
name = n;
age=a;
}
void display(){System.out.println(id+" "+name+" "+age);}
public static void main(String args[]){
Student5 s1 = new Student5(111,"Karan");
Student5 s2 = new Student5(222,"Aryan",25);
s1.display();
s2.display(); }}
111 Karan 0
222 Aryan 25
11
Q) Does constructor return any value?
yes, that is current class instance (You cannot use return type yet it returns a value).
Yes, like object creation, starting a thread, calling method etc. You can perform any operation in the
constructor as you perform in the method.
_________________________________
12