0% found this document useful (0 votes)
12 views12 pages

Functions in Java

Uploaded by

deepa
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
12 views12 pages

Functions in Java

Uploaded by

deepa
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 12

FUNCTIONS / METHODS

A function is a block or portion of code within a larger program which consists of


some declarations and executable statements, which performs a specific task and is
relatively independent of the remaining code.

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’.

Advantages of using Functions –


1. To cope with the complexity of code by breaking down complex bigger code into
smaller and simpler ones.
2. Hiding details (thus implementing Abstraction)
3. Reusability of Code
4. Makes debugging of errors easy.

Types of function

1. Predefined /In-built functions


2. User defined functions
Predefined functions are available with the programming language and are
transferred into the memory as soon as the software/function is loaded.
Eg.Math.sqrt(16),Math.pow(5,2).

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…
}

Let us now see all the components individually –


1. These are keywords which define the accessibility of the function, if nothing is
mentioned then by default it is ‘friendly’ friendly is not a keyword. They are of 4 types
a. Public
b. private

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


}

Understanding the keywords public & private


In a function the access specifier indicate the scope of visibility of that particular
function, this means whether the data members and member methods are accessible
only within the class, or other classes within the same package or other classes in
other packages.

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.

Understanding the keyword static


A static data member is also known as a class variable, such variables have only one
instance inside the class and we cannot create multiple instances through multiple
objects.
On the other hand if a member is non-static then such members are called instance
variables, which mean we can have multiple instances of such variables through
multiple objects.
e.g.
class Exmp1
{
int x; // non-static or instance variable which can have multiple instances
static int y; // static variable or class variable which has only one instance

public static void main( )


{
Exmp1 obj1 = new Exmp1( );
Exmp1 obj2 = new Exmp1( ); // three different objects through which we can
Exmp1 obj3 = new Exmp1( ); // have three different values of ‘x’

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.

How to access a function?


A function can be accessed or invoked from other functions by simply writing the
name of the function along with the argument list (if any) otherwise the argument list
is kept empty.
e.g.
class ABCD
{
public static void main( )
{
int x = 10, y = 20;
function call add (x, y);
}

public static void add(int x, int y)


{
System.out.println(x+y);
}
}
Actual & Formal Parameters / Arguments
The actual parameters are those that appear at the point of function invocation or
function call are called Actual parameters.

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);
}

formal parameters public static void add(int x, int y)


{
System.out.println(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.

4. Argumentative & return type


Example
class ABCD
{
public static void main( )
{
int x = 10;
int y = display( x );
System.out.println(“The square value of x =” + y);
}
public static int display(int x)
{
int y = x * x;
return y;
}
}

The return statement


A function terminates as soon as the last statement of the function is encountered or
the return keyword is encountered.
It is not necessary that return keyword should be used only in functions that has a
return type, even functions that are void can use the return keyword to terminate the
function and shift the program control to the calling function but make sure that the
return statement does not have anything preceding the keyword ‘return’.
e.g.
class ABCD
{
public static void main( )
{
call( );
}

public static void call( )


{
System.out.println(“Inside the method call”);
return ; // return statement has nothing following it
}
}
Three types of functions:

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( )

3. Procedural Functions – The functions that perform certain tasks like


reading from source files, reading from terminals, displaying data to the
terminal are called procedural functions. They generally do not have any
return type.
e.g. System.out.println( );
Pure & Impure functions
A pure function is one that takes objects and/or primitive data as
arguments but does not modify the objects hence the return value of such
functions are either primitive data or an entirely new object created inside
the function. They are also known as Accessor methods.

An impure function on the other hand modifies the state of its objects or
arguments.
They are also known as Modifier methods.
Pure Functionpublic static int maximum(int a, int b)
{
int c = Math.max(a,b);
return c;
}
Impure Functionpublic 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.

Function overloading implements Polymorphism.


e.g.
class Overload
{

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.

1. Constructor name must be same as its class name


2. Constructor must have no explicit return type

class Constr
{
int n;
Constr( )
{
n = 0;
} // invokes the constructor

public static void main( )


{
Constr obj = new Constr( );
System.out.println(obj.n);
}
}
Types of Constructors

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.

A parameterized constructor accepts parameters or values in its argument list


which initialize the various instance data members of the class.
class Constr
{
int n;
Constr(int val)
{
n = val;
} // invokes the constructor
public static void main( )
{ int v = 25;
Constr obj = new Constr(v); }}

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:

If we want to access the instance variable, we do it with this.x.


public class MyNumber {
int x = 3;
public void setX() {
x = 4;
System.out.printn(x);
9
System.out.printn(this.x);
}
}
The above program will print,
4
3
Here is an example program with the keyword this used in a constructor and two set
methods.

public class Student {


int rollNumber;
int marks;
public Student(int rollNumber, int marks) {
this.rollNumber = rollNumber;
this.marks = marks;
}
public void setRollNumber(int rollNumber) {
this.rollNumber = rollNumber;
}
public void setMarks(int marks) {
this.marks = marks;}}

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.

Example of Constructor Overloading

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

Difference between constructor and method in java


There are many differences between constructors and methods. They are given below.

Java Constructor Java Method


Constructor is used to initialize the state of an object. Method is used to expose
behaviour of an object.
Constructor must not have return type. Method must have return
type.
Constructor is invoked implicitly. Method is invoked
explicitly.
The java compiler provides a default constructor if Method is not provided by
compiler in any case.
you don't have any constructor .
Constructor name must be same as the class name. Method name may or may
not be same as class name.

11
Q) Does constructor return any value?

yes, that is current class instance (You cannot use return type yet it returns a value).

Q)Can constructor perform other tasks instead of initialization?

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

You might also like