0% found this document useful (0 votes)
48 views

17java Methods

method in java

Uploaded by

Yohannes Dejene
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
48 views

17java Methods

method in java

Uploaded by

Yohannes Dejene
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

JAVA - METHODS

http://www.tutorialspoint.com/java/java_methods.htm Copyright © tutorials point.com

A Java met hod is a collect ion of st at ement s t hat are grouped t oget her t o perform an operat ion.
When you call t he Syst em.out .print ln met hod, for example, t he syst em act ually execut es several
st at ement s in order t o display a message on t he console.

Now you will learn how t o creat e your own met hods wit h or wit hout ret urn values, invoke a met hod
wit h or wit hout paramet ers, overload met hods using t he same names, and apply met hod abst ract ion
in t he program design.

Creat ing Met hod:


Considering t he following example t o explain t he synt ax of a met hod:

public static int funcName(int a, int b) {


// body
}

Here,

public static : modifier.

int: ret urn t ype

funcName: funct ion name

a, b: formal paramet ers

int a, int b: list of paramet ers

Met hods are also known as Procedures or Funct ions:

Pro cedures: They don't ret urn any value.

Functio ns: They ret urn value.

Met hod definit ion consist s of a met hod header and a met hod body. The same is shown below:

modifier returnType nameOfMethod (Parameter List) {


// method body
}

The synt ax shown above includes:

mo difier: It defines t he access t ype of t he met hod and it is opt ional t o use.

returnT ype: Met hod may ret urn a value.

nameOfMetho d: This is t he met hod name. The met hod signat ure consist s of t he met hod
name and t he paramet er list .

Parameter List: The list of paramet ers, it is t he t ype, order, and number of paramet ers of a
met hod. These are opt ional, met hod may cont ain zero paramet ers.

metho d bo dy: The met hod body defines what t he met hod does wit h st at ement s.

Example:
Here is t he source code of t he above defined met hod called max(). This met hod t akes t wo
paramet ers num1 and num2 and ret urns t he maximum bet ween t he t wo:

/** the snippet returns the minimum between two numbers */


public static int minFunction(int n1, int n2) {
int min;
if (n1 > n2)
min = n2;
else
min = n1;

return min;
}

Met hod Calling:


For using a met hod, it should be called. There are t wo ways in which a met hod is called i.e. met hod
ret urns a value or ret urning not hing (no ret urn value).

The process of met hod calling is simple. When a program invokes a met hod, t he program cont rol
get s t ransferred t o t he called met hod. This called met hod t hen ret urns cont rol t o t he caller in t wo
condit ions, when:

ret urn st at ement is execut ed.

reaches t he met hod ending closing brace.

The met hods ret urning void is considered as call t o a st at ement . Let s consider an example:

System.out.println("This is tutorialspoint.com!");

The met hod ret urning value can be underst ood by t he following example:

int result = sum(6, 9);

Example:
Following is t he example t o demonst rat e how t o define a met hod and how t o call it :

public class ExampleMinNumber{

public static void main(String[] args) {


int a = 11;
int b = 6;
int c = minFunction(a, b);
System.out.println("Minimum Value = " + c);
}

/** returns the minimum of two numbers */


public static int minFunction(int n1, int n2) {
int min;
if (n1 > n2)
min = n2;
else
min = n1;

return min;
}
}

This would produce t he following result :

Minimum value = 6

The void Keyword:


The void keyword allows us t o creat e met hods which do not ret urn a value. Here, in t he following
example we're considering a void met hod methodRankPoints. This met hod is a void met hod which
does not ret urn any value. Call t o a void met hod must be a st at ement i.e.
methodRankPoints(255.7);. It is a Java st at ement which ends wit h a semicolon as shown below.

Example:
public class ExampleVoid {

public static void main(String[] args) {


methodRankPoints(255.7);
}

public static void methodRankPoints(double points) {


if (points >= 202.5) {
System.out.println("Rank:A1");
}
else if (points >= 122.4) {
System.out.println("Rank:A2");
}
else {
System.out.println("Rank:A3");
}
}
}

This would produce t he following result :

Rank:A1

Passing Paramet ers by Value:


While working under calling process, argument s is t o be passed. These should be in t he same order
as t heir respect ive paramet ers in t he met hod specificat ion. Paramet ers can be passed by value or
by reference.

Passing Paramet ers by Value means calling a met hod wit h a paramet er. Through t his t he argument
value is passed t o t he paramet er.

Example:
The following program shows an example of passing paramet er by value. The values of t he
argument s remains t he same even aft er t he met hod invocat ion.

public class swappingExample {

public static void main(String[] args) {


int a = 30;
int b = 45;

System.out.println("Before swapping, a = " +


a + " and b = " + b);

// Invoke the swap method


swapFunction(a, b);
System.out.println("\n**Now, Before and After swapping values will be same here**:");
System.out.println("After swapping, a = " +
a + " and b is " + b);
}

public static void swapFunction(int a, int b) {

System.out.println("Before swapping(Inside), a = " + a


+ " b = " + b);
// Swap n1 with n2
int c = a;
a = b;
b = c;

System.out.println("After swapping(Inside), a = " + a


+ " b = " + b);
}
}

This would produce t he following result :


Before swapping, a = 30 and b = 45
Before swapping(Inside), a = 30 b = 45
After swapping(Inside), a = 45 b = 30

**Now, Before and After swapping values will be same here**:


After swapping, a = 30 and b is 45

Met hod Overloading:


When a class has t wo or more met hods by same name but different paramet ers, it is known as
met hod overloading. It is different from overriding. In overriding a met hod has same met hod name,
t ype, number of paramet ers et c.

Let s consider t he example shown before for finding minimum numbers of int eger t ype. If, let s say we
want t o find minimum number of double t ype. Then t he concept of Overloading will be int roduced t o
creat e t wo or more met hods wit h t he same name but different paramet ers.

The below example explains t he same:

public class ExampleOverloading{

public static void main(String[] args) {


int a = 11;
int b = 6;
double c = 7.3;
double d = 9.4;
int result1 = minFunction(a, b);
// same function name with different parameters
double result2 = minFunction(c, d);
System.out.println("Minimum Value = " + result1);
System.out.println("Minimum Value = " + result2);
}

// for integer
public static int minFunction(int n1, int n2) {
int min;
if (n1 > n2)
min = n2;
else
min = n1;

return min;
}
// for double
public static double minFunction(double n1, double n2) {
double min;
if (n1 > n2)
min = n2;
else
min = n1;

return min;
}
}

This would produce t he following result :

Minimum Value = 6
Minimum Value = 7.3

Overloading met hods makes program readable. Here, t wo met hods are given same name but wit h
different paramet ers. The minimum number from int eger and double t ypes is t he result .

Using Command-Line Argument s:


Somet imes you will want t o pass informat ion int o a program when you run it . This is accomplished by
passing command-line argument s t o main( ).

A command-line argument is t he informat ion t hat direct ly follows t he program's name on t he


command line when it is execut ed. To access t he command-line argument s inside a Java program is
quit e easy.t hey are st ored as st rings in t he St ring array passed t o main( ).

Example:
The following program displays all of t he command-line argument s t hat it is called wit h:

public class CommandLine {

public static void main(String args[]){


for(int i=0; i<args.length; i++){
System.out.println("args[" + i + "]: " +
args[i]);
}
}
}

Try execut ing t his program as shown here:

java CommandLine this is a command line 200 -100

This would produce t he following result :

args[0]: this
args[1]: is
args[2]: a
args[3]: command
args[4]: line
args[5]: 200
args[6]: -100

The Const ruct ors:


A const ruct or init ializes an object when it is creat ed. It has t he same name as it s class and is
synt act ically similar t o a met hod. However, const ruct ors have no explicit ret urn t ype.

Typically, you will use a const ruct or t o give init ial values t o t he inst ance variables defined by t he
class, or t o perform any ot her st art up procedures required t o creat e a fully formed object .

All classes have const ruct ors, whet her you define one or not , because Java aut omat ically provides a
default const ruct or t hat init ializes all member variables t o zero. However, once you define your own
const ruct or, t he default const ruct or is no longer used.

Example:
Here is a simple example t hat uses a const ruct or:

// A simple constructor.
class MyClass {
int x;

// Following is the constructor


MyClass() {
x = 10;
}
}

You would call const ruct or t o init ialize object s as follows:

public class ConsDemo {

public static void main(String args[]) {


MyClass t1 = new MyClass();
MyClass t2 = new MyClass();
System.out.println(t1.x + " " + t2.x);
}
}
Most oft en, you will need a const ruct or t hat accept s one or more paramet ers. Paramet ers are
added t o a const ruct or in t he same way t hat t hey are added t o a met hod, just declare t hem inside
t he parent heses aft er t he const ruct or's name.

Example:
Here is a simple example t hat uses a const ruct or:

// A simple constructor.
class MyClass {
int x;

// Following is the constructor


MyClass(int i ) {
x = i;
}
}

You would call const ruct or t o init ialize object s as follows:

public class ConsDemo {

public static void main(String args[]) {


MyClass t1 = new MyClass( 10 );
MyClass t2 = new MyClass( 20 );
System.out.println(t1.x + " " + t2.x);
}
}

This would produce t he following result :

10 20

Variable Argument s(var-args):


JDK 1.5 enables you t o pass a variable number of argument s of t he same t ype t o a met hod. The
paramet er in t he met hod is declared as follows:

typeName... parameterName

In t he met hod declarat ion, you specify t he t ype followed by an ellipsis (...) Only one variable-lengt h
paramet er may be specified in a met hod, and t his paramet er must be t he last paramet er. Any
regular paramet ers must precede it .

Example:
public class VarargsDemo {

public static void main(String args[]) {


// Call method with variable args
printMax(34, 3, 3, 2, 56.5);
printMax(new double[]{1, 2, 3});
}

public static void printMax( double... numbers) {


if (numbers.length == 0) {
System.out.println("No argument passed");
return;
}

double result = numbers[0];

for (int i = 1; i < numbers.length; i++)


if (numbers[i] > result)
result = numbers[i];
System.out.println("The max value is " + result);
}
}

This would produce t he following result :

The max value is 56.5


The max value is 3.0

The finalize( ) Met hod:


It is possible t o define a met hod t hat will be called just before an object 's final dest ruct ion by t he
garbage collect or. This met hod is called finalize( ), and it can be used t o ensure t hat an object
t erminat es cleanly.

For example, you might use finalize( ) t o make sure t hat an open file owned by t hat object is closed.

To add a finalizer t o a class, you simply define t he finalize( ) met hod. The Java runt ime calls t hat
met hod whenever it is about t o recycle an object of t hat class.

Inside t he finalize( ) met hod, you will specify t hose act ions t hat must be performed before an object
is dest royed.

The finalize( ) met hod has t his general form:

protected void finalize( )


{
// finalization code here
}

Here, t he keyword prot ect ed is a specifier t hat prevent s access t o finalize( ) by code defined
out side it s class.

This means t hat you cannot know when or even if finalize( ) will be execut ed. For example, if your
program ends before garbage collect ion occurs, finalize( ) will not execut e.

You might also like