SlideShare una empresa de Scribd logo
1 de 11
Java - Methods
A Java method is a collection of statements that are grouped together to perform
an operation. When you call the System.out.println() method, for example, the
system actually executes several statements in order to display a message on the
console.
Now you will learn how to create your own methods with or without return
values, invoke a method with or without parameters, and apply method
abstraction in the program design.
Creating Method
Considering the following example to explain the syntax of a method −
Syntax
public static int methodName(int a, int b)
{
// body
}
Here,
 public static − modifier
 int − return type
 methodName − name of the method
 a, b − formal parameters
 int a, int b − list of parameters
Method definition consists of a method header and a method body. The same is
shown in the following syntax −
Syntax
modifier returnType nameOfMethod (Parameter List) {
// method body
}
The syntax shown above includes −
 modifier − It defines the access type of the method and it is optional to
use.
 returnType − Method may return a value.
 nameOfMethod− This is the method name. The method signature
consists of the method name and the parameter list.
 ParameterList − The list of parameters, it is the type, order, and number
of parameters of a method. These are optional, method may contain zero
parameters.
 method body − The method bodydefines what the method does with the
statements.
Example
Here is the source codeof the above defined method called min(). This method
takes two parameters num1 and num2 and returns the maximum between the two
−
/** 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;
}
Method Calling
For using a method, it should be called. There are two ways in which a method
is called i.e., method returns a value or returning nothing (no return value).
The process ofmethod calling is simple. When a program invokes a method, the
program control gets transferred to the called method. This called method then
returns control to the caller in two conditions, when −
 the return statement is executed.
 it reaches the method ending closing brace.
The methods returning void is considered as call to a statement. Lets consideran
example −
System.out.println("This is tutorialspoint.com!");
The method returning value can be understood by the following example −
int result = sum(6, 9);
Following is the example to demonstrate how to define a method and how to call
it −
Example
Live Demo
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 will produce the following result −
Output
Minimum value = 6
The void Keyword
The void keyword allows us to create methods which do notreturn a value. Here,
in the following example we're considering a void method methodRankPoints.
This method is a void method, which does not return any value. Call to a void
method must be a statement i.e. methodRankPoints(255.7);. It is a Java
statement which ends with a semicolon as shown in the following example.
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 will produce the following result −
Output
Rank:A1
Passing Parameters by Value
While working under calling process, arguments is to be passed. These should
be in the same order as their respective parameters in the method specification.
Parameters can be passed by value or by reference.
Passing Parameters by Value means calling a method with a parameter. Through
this, the argument value is passed to the parameter.
Example
The following program shows an example of passing parameter by value. The
values of the arguments remains the same even after the method invocation.
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 will produce the following result −
Output
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
Method Overloading
When a class has two or more methods by the same name but different
parameters, it is known as method overloading. It is different from overriding.
In overriding, a method has the same method name, type, number of parameters,
etc.
Let’s consider the example discussed earlier for finding minimum numbers of
integer type. If, let’s say we want to find the minimum number of double type.
Then the concept of overloading will be introduced to create two or more
methods with the same name but different parameters.
The following example explains the same −
Example
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 will produce the following result −
Output
Minimum Value = 6
Minimum Value = 7.3
Overloading methods makes program readable. Here, two methods are given by
the same name but with different parameters. Theminimum number from integer
and double types is the result.
Using Command-Line Arguments
Sometimes you will want to pass someinformation into a program when you run
it. This is accomplished by passing command-line arguments to main( ).
A command-line argument is the information that directly follows the program's
name on the command line when it is executed. To access the command-line
arguments inside a Java program is quite easy. They are stored as strings in the
String array passed to main( ).
Example
The following program displays all of the command-line arguments that it is
called with −
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 executing this program as shown here −
$java CommandLine this is a command line 200 -100
This will produce the following result −
Output
args[0]: this
args[1]: is
args[2]: a
args[3]: command
args[4]: line
args[5]: 200
args[6]: -100
The this keyword
this is a keyword in Java which is used as a reference to the object of the current
class, with in an instance method or a constructor. Using this you can refer the
members of a class such as constructors, variables and methods.
Note − The keyword this is used only within instance methods or constructors
In general, the keyword this is used to −
 Differentiate the instance variables from local variables if they have same
names, within a constructor or a method.
class Student {
int age;
Student(int age) {
this.age = age;
}
}
 Call one type of constructor (parametrized constructor or default) from
other in a class. It is known as explicit constructor invocation.
class Student {
int age
Student() {
this(20);
}
Student(int age) {
this.age = age;
}
}
Example
Here is an example that uses this keyword to access the members of a class.
Copy and paste the following program in a file with the
name, This_Example.java.
public class This_Example {
// Instance variable num
int num = 10;
This_Example() {
System.out.println("This is an example program
on keyword this");
}
This_Example(int num) {
// Invoking the default constructor
this();
// Assigning the local variable num to the
instance variable num
this.num = num;
}
public void greet() {
System.out.println("Hi Welcome to
Tutorialspoint");
}
public void print() {
// Local variable num
int num = 20;
// Printing the local variable
System.out.println("value of local variable num
is : "+num);
// Printing the instance variable
System.out.println("value of instance variable
num is : "+this.num);
// Invoking the greet method of a class
this.greet();
}
public static void main(String[] args) {
// Instantiating the class
This_Example obj1 = new This_Example();
// Invoking the print method
obj1.print();
// Passing a new value to the num variable
through parametrized constructor
This_Example obj2 = new This_Example(30);
// Invoking the print method again
obj2.print();
}
}
This will produce the following result −
Output
This is an example program on keyword this
value of local variable num is : 20
value of instance variable num is : 10
Hi Welcome to Tutorialspoint
This is an example program on keyword this
value of local variable num is : 20
value of instance variable num is : 30
Hi Welcome to Tutorialspoint
Variable Arguments(var-args)
JDK 1.5 enables you to pass a variable number of arguments of the same type to
a method. The parameter in the method is declared as follows −
typeName... parameterName
In the method declaration, you specify the type followed byan ellipsis (...). Only
one variable-length parameter may be specified in a method, and this parameter
must be the last parameter. Any regular parameters 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 will produce the following result −
Output
The max value is 56.5
The max value is 3.0
The finalize( ) Method
It is possible to define a method that will be called just before an object's final
destruction by the garbage collector. This method is called finalize( ), and it can
be used to ensure that an object terminates cleanly.
For example, you might use finalize( ) to make sure that an open file owned by
that object is closed.
To add a finalizer to a class, you simply define the finalize( ) method. The Java
runtime calls that method whenever it is about to recycle an object of that class.
Inside the finalize( ) method, you will specify those actions that must be
performed before an object is destroyed.
The finalize( ) method has this general form −
protected void finalize( ) {
// finalization code here
}
Here, the keyword protected is a specifier that prevents access to finalize( ) by
code defined outside its class.
This means that you cannot know when or even if finalize( ) will be executed.
For example, if your program ends before garbage collection occurs, finalize( )
will not execute.

Más contenido relacionado

La actualidad más candente

Interfaces and abstract classes
Interfaces and abstract classesInterfaces and abstract classes
Interfaces and abstract classesAKANSH SINGHAL
 
Polymorphism presentation in java
Polymorphism presentation in javaPolymorphism presentation in java
Polymorphism presentation in javaAhsan Raja
 
Cs2312 OOPS LAB MANUAL
Cs2312 OOPS LAB MANUALCs2312 OOPS LAB MANUAL
Cs2312 OOPS LAB MANUALPrabhu D
 
Java method present by showrov ahamed
Java method present by showrov ahamedJava method present by showrov ahamed
Java method present by showrov ahamedMd Showrov Ahmed
 
java-06inheritance
java-06inheritancejava-06inheritance
java-06inheritanceArjun Shanka
 
Object Oriented Programming Lab Manual
Object Oriented Programming Lab Manual Object Oriented Programming Lab Manual
Object Oriented Programming Lab Manual Abdul Hannan
 
Exception Handling in C#
Exception Handling in C#Exception Handling in C#
Exception Handling in C#Abid Kohistani
 
Introduction to Matlab Scripts
Introduction to Matlab ScriptsIntroduction to Matlab Scripts
Introduction to Matlab ScriptsShameer Ahmed Koya
 
Applets - lev' 2
Applets - lev' 2Applets - lev' 2
Applets - lev' 2Rakesh T
 
An Introduction to MATLAB for beginners
An Introduction to MATLAB for beginnersAn Introduction to MATLAB for beginners
An Introduction to MATLAB for beginnersMurshida ck
 
Lab manual object oriented technology (it 303 rgpv) (usefulsearch.org) (usef...
Lab manual object oriented technology (it 303 rgpv) (usefulsearch.org)  (usef...Lab manual object oriented technology (it 303 rgpv) (usefulsearch.org)  (usef...
Lab manual object oriented technology (it 303 rgpv) (usefulsearch.org) (usef...Make Mannan
 
(2) c sharp introduction_basics_part_i
(2) c sharp introduction_basics_part_i(2) c sharp introduction_basics_part_i
(2) c sharp introduction_basics_part_iNico Ludwig
 

La actualidad más candente (20)

Interface
InterfaceInterface
Interface
 
Interfaces and abstract classes
Interfaces and abstract classesInterfaces and abstract classes
Interfaces and abstract classes
 
Polymorphism presentation in java
Polymorphism presentation in javaPolymorphism presentation in java
Polymorphism presentation in java
 
Cs2312 OOPS LAB MANUAL
Cs2312 OOPS LAB MANUALCs2312 OOPS LAB MANUAL
Cs2312 OOPS LAB MANUAL
 
Java method present by showrov ahamed
Java method present by showrov ahamedJava method present by showrov ahamed
Java method present by showrov ahamed
 
Method of java
Method of javaMethod of java
Method of java
 
java-06inheritance
java-06inheritancejava-06inheritance
java-06inheritance
 
Operators in java
Operators in javaOperators in java
Operators in java
 
Object Oriented Programming Lab Manual
Object Oriented Programming Lab Manual Object Oriented Programming Lab Manual
Object Oriented Programming Lab Manual
 
Unit 7 Java
Unit 7 JavaUnit 7 Java
Unit 7 Java
 
JAVA AWT
JAVA AWTJAVA AWT
JAVA AWT
 
Exception Handling in C#
Exception Handling in C#Exception Handling in C#
Exception Handling in C#
 
Introduction to Matlab Scripts
Introduction to Matlab ScriptsIntroduction to Matlab Scripts
Introduction to Matlab Scripts
 
Applets - lev' 2
Applets - lev' 2Applets - lev' 2
Applets - lev' 2
 
An Introduction to MATLAB for beginners
An Introduction to MATLAB for beginnersAn Introduction to MATLAB for beginners
An Introduction to MATLAB for beginners
 
Lab manual object oriented technology (it 303 rgpv) (usefulsearch.org) (usef...
Lab manual object oriented technology (it 303 rgpv) (usefulsearch.org)  (usef...Lab manual object oriented technology (it 303 rgpv) (usefulsearch.org)  (usef...
Lab manual object oriented technology (it 303 rgpv) (usefulsearch.org) (usef...
 
Class 10
Class 10Class 10
Class 10
 
Java chapter 3
Java chapter 3Java chapter 3
Java chapter 3
 
(2) c sharp introduction_basics_part_i
(2) c sharp introduction_basics_part_i(2) c sharp introduction_basics_part_i
(2) c sharp introduction_basics_part_i
 
MATLAB Programming
MATLAB Programming MATLAB Programming
MATLAB Programming
 

Similar a Methods in Java

EContent_11_2023_04_09_11_30_38_Unit_3_Objects_and_Classespptx__2023_03_20_12...
EContent_11_2023_04_09_11_30_38_Unit_3_Objects_and_Classespptx__2023_03_20_12...EContent_11_2023_04_09_11_30_38_Unit_3_Objects_and_Classespptx__2023_03_20_12...
EContent_11_2023_04_09_11_30_38_Unit_3_Objects_and_Classespptx__2023_03_20_12...vekariyakashyap
 
9. DBMS Experiment Laboratory PresentationPPT
9. DBMS Experiment Laboratory PresentationPPT9. DBMS Experiment Laboratory PresentationPPT
9. DBMS Experiment Laboratory PresentationPPTTheVerse1
 
Lecture 4_Java Method-constructor_imp_keywords
Lecture   4_Java Method-constructor_imp_keywordsLecture   4_Java Method-constructor_imp_keywords
Lecture 4_Java Method-constructor_imp_keywordsmanish kumar
 
Java Foundations: Methods
Java Foundations: MethodsJava Foundations: Methods
Java Foundations: MethodsSvetlin Nakov
 
Procedure and Functions in pl/sql
Procedure and Functions in pl/sqlProcedure and Functions in pl/sql
Procedure and Functions in pl/sqlÑirmal Tatiwal
 
Working with Methods in Java.pptx
Working with Methods in Java.pptxWorking with Methods in Java.pptx
Working with Methods in Java.pptxmaryansagsgao
 
Methods In C-Sharp (C#)
Methods In C-Sharp (C#)Methods In C-Sharp (C#)
Methods In C-Sharp (C#)Abid Kohistani
 
Classes function overloading
Classes function overloadingClasses function overloading
Classes function overloadingankush_kumar
 
Introduction to Basic C programming 01
Introduction to Basic C programming 01Introduction to Basic C programming 01
Introduction to Basic C programming 01Wingston
 
Presentation on Function in C Programming
Presentation on Function in C ProgrammingPresentation on Function in C Programming
Presentation on Function in C ProgrammingShuvongkor Barman
 

Similar a Methods in Java (20)

EContent_11_2023_04_09_11_30_38_Unit_3_Objects_and_Classespptx__2023_03_20_12...
EContent_11_2023_04_09_11_30_38_Unit_3_Objects_and_Classespptx__2023_03_20_12...EContent_11_2023_04_09_11_30_38_Unit_3_Objects_and_Classespptx__2023_03_20_12...
EContent_11_2023_04_09_11_30_38_Unit_3_Objects_and_Classespptx__2023_03_20_12...
 
Computer programming 2 Lesson 15
Computer programming 2  Lesson 15Computer programming 2  Lesson 15
Computer programming 2 Lesson 15
 
9. DBMS Experiment Laboratory PresentationPPT
9. DBMS Experiment Laboratory PresentationPPT9. DBMS Experiment Laboratory PresentationPPT
9. DBMS Experiment Laboratory PresentationPPT
 
Lecture 4_Java Method-constructor_imp_keywords
Lecture   4_Java Method-constructor_imp_keywordsLecture   4_Java Method-constructor_imp_keywords
Lecture 4_Java Method-constructor_imp_keywords
 
Java Foundations: Methods
Java Foundations: MethodsJava Foundations: Methods
Java Foundations: Methods
 
Procedure and Functions in pl/sql
Procedure and Functions in pl/sqlProcedure and Functions in pl/sql
Procedure and Functions in pl/sql
 
Methods.ppt
Methods.pptMethods.ppt
Methods.ppt
 
11. java methods
11. java methods11. java methods
11. java methods
 
Working with Methods in Java.pptx
Working with Methods in Java.pptxWorking with Methods in Java.pptx
Working with Methods in Java.pptx
 
Methods In C-Sharp (C#)
Methods In C-Sharp (C#)Methods In C-Sharp (C#)
Methods In C-Sharp (C#)
 
Classes function overloading
Classes function overloadingClasses function overloading
Classes function overloading
 
Introduction to Basic C programming 01
Introduction to Basic C programming 01Introduction to Basic C programming 01
Introduction to Basic C programming 01
 
Presentation on Function in C Programming
Presentation on Function in C ProgrammingPresentation on Function in C Programming
Presentation on Function in C Programming
 
Major Java 8 features
Major Java 8 featuresMajor Java 8 features
Major Java 8 features
 
Java execise
Java execiseJava execise
Java execise
 
Array Cont
Array ContArray Cont
Array Cont
 
Java method
Java methodJava method
Java method
 
C Programming Unit-2
C Programming Unit-2C Programming Unit-2
C Programming Unit-2
 
Methods intro-1.0
Methods intro-1.0Methods intro-1.0
Methods intro-1.0
 
Functions in C.pptx
Functions in C.pptxFunctions in C.pptx
Functions in C.pptx
 

Más de Kavitha713564

THE PACKAGES CONCEPT IN JAVA PROGRAMMING.pptx
THE PACKAGES CONCEPT  IN JAVA PROGRAMMING.pptxTHE PACKAGES CONCEPT  IN JAVA PROGRAMMING.pptx
THE PACKAGES CONCEPT IN JAVA PROGRAMMING.pptxKavitha713564
 
The Java Server Page in Java Concept.pptx
The Java Server Page in Java Concept.pptxThe Java Server Page in Java Concept.pptx
The Java Server Page in Java Concept.pptxKavitha713564
 
Programming in python in detail concept .pptx
Programming in python in detail concept .pptxProgramming in python in detail concept .pptx
Programming in python in detail concept .pptxKavitha713564
 
The Input Statement in Core Python .pptx
The Input Statement in Core Python .pptxThe Input Statement in Core Python .pptx
The Input Statement in Core Python .pptxKavitha713564
 
The Datatypes Concept in Core Python.pptx
The Datatypes Concept in Core Python.pptxThe Datatypes Concept in Core Python.pptx
The Datatypes Concept in Core Python.pptxKavitha713564
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in javaKavitha713564
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in javaKavitha713564
 
Input output files in java
Input output files in javaInput output files in java
Input output files in javaKavitha713564
 
Arrays,string and vector
Arrays,string and vectorArrays,string and vector
Arrays,string and vectorKavitha713564
 

Más de Kavitha713564 (11)

THE PACKAGES CONCEPT IN JAVA PROGRAMMING.pptx
THE PACKAGES CONCEPT  IN JAVA PROGRAMMING.pptxTHE PACKAGES CONCEPT  IN JAVA PROGRAMMING.pptx
THE PACKAGES CONCEPT IN JAVA PROGRAMMING.pptx
 
The Java Server Page in Java Concept.pptx
The Java Server Page in Java Concept.pptxThe Java Server Page in Java Concept.pptx
The Java Server Page in Java Concept.pptx
 
Programming in python in detail concept .pptx
Programming in python in detail concept .pptxProgramming in python in detail concept .pptx
Programming in python in detail concept .pptx
 
The Input Statement in Core Python .pptx
The Input Statement in Core Python .pptxThe Input Statement in Core Python .pptx
The Input Statement in Core Python .pptx
 
The Datatypes Concept in Core Python.pptx
The Datatypes Concept in Core Python.pptxThe Datatypes Concept in Core Python.pptx
The Datatypes Concept in Core Python.pptx
 
Packages in java
Packages in javaPackages in java
Packages in java
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Basic of java
Basic of javaBasic of java
Basic of java
 
Input output files in java
Input output files in javaInput output files in java
Input output files in java
 
Arrays,string and vector
Arrays,string and vectorArrays,string and vector
Arrays,string and vector
 

Último

Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Disha Kariya
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajanpragatimahajan3
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfchloefrazer622
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...Sapna Thakur
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 

Último (20)

Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajan
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdf
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 

Methods in Java

  • 1. Java - Methods A Java method is a collection of statements that are grouped together to perform an operation. When you call the System.out.println() method, for example, the system actually executes several statements in order to display a message on the console. Now you will learn how to create your own methods with or without return values, invoke a method with or without parameters, and apply method abstraction in the program design. Creating Method Considering the following example to explain the syntax of a method − Syntax public static int methodName(int a, int b) { // body } Here,  public static − modifier  int − return type  methodName − name of the method  a, b − formal parameters  int a, int b − list of parameters Method definition consists of a method header and a method body. The same is shown in the following syntax − Syntax modifier returnType nameOfMethod (Parameter List) { // method body } The syntax shown above includes −  modifier − It defines the access type of the method and it is optional to use.  returnType − Method may return a value.
  • 2.  nameOfMethod− This is the method name. The method signature consists of the method name and the parameter list.  ParameterList − The list of parameters, it is the type, order, and number of parameters of a method. These are optional, method may contain zero parameters.  method body − The method bodydefines what the method does with the statements. Example Here is the source codeof the above defined method called min(). This method takes two parameters num1 and num2 and returns the maximum between the two − /** 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; } Method Calling For using a method, it should be called. There are two ways in which a method is called i.e., method returns a value or returning nothing (no return value). The process ofmethod calling is simple. When a program invokes a method, the program control gets transferred to the called method. This called method then returns control to the caller in two conditions, when −  the return statement is executed.  it reaches the method ending closing brace. The methods returning void is considered as call to a statement. Lets consideran example − System.out.println("This is tutorialspoint.com!"); The method returning value can be understood by the following example −
  • 3. int result = sum(6, 9); Following is the example to demonstrate how to define a method and how to call it − Example Live Demo 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 will produce the following result − Output Minimum value = 6 The void Keyword The void keyword allows us to create methods which do notreturn a value. Here, in the following example we're considering a void method methodRankPoints. This method is a void method, which does not return any value. Call to a void method must be a statement i.e. methodRankPoints(255.7);. It is a Java statement which ends with a semicolon as shown in the following example. Example public class ExampleVoid {
  • 4. 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 will produce the following result − Output Rank:A1 Passing Parameters by Value While working under calling process, arguments is to be passed. These should be in the same order as their respective parameters in the method specification. Parameters can be passed by value or by reference. Passing Parameters by Value means calling a method with a parameter. Through this, the argument value is passed to the parameter. Example The following program shows an example of passing parameter by value. The values of the arguments remains the same even after the method invocation. 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);
  • 5. 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 will produce the following result − Output 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 Method Overloading When a class has two or more methods by the same name but different parameters, it is known as method overloading. It is different from overriding. In overriding, a method has the same method name, type, number of parameters, etc. Let’s consider the example discussed earlier for finding minimum numbers of integer type. If, let’s say we want to find the minimum number of double type. Then the concept of overloading will be introduced to create two or more methods with the same name but different parameters. The following example explains the same − Example
  • 6. 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 will produce the following result − Output
  • 7. Minimum Value = 6 Minimum Value = 7.3 Overloading methods makes program readable. Here, two methods are given by the same name but with different parameters. Theminimum number from integer and double types is the result. Using Command-Line Arguments Sometimes you will want to pass someinformation into a program when you run it. This is accomplished by passing command-line arguments to main( ). A command-line argument is the information that directly follows the program's name on the command line when it is executed. To access the command-line arguments inside a Java program is quite easy. They are stored as strings in the String array passed to main( ). Example The following program displays all of the command-line arguments that it is called with − 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 executing this program as shown here − $java CommandLine this is a command line 200 -100 This will produce the following result − Output args[0]: this args[1]: is args[2]: a args[3]: command args[4]: line args[5]: 200 args[6]: -100 The this keyword
  • 8. this is a keyword in Java which is used as a reference to the object of the current class, with in an instance method or a constructor. Using this you can refer the members of a class such as constructors, variables and methods. Note − The keyword this is used only within instance methods or constructors In general, the keyword this is used to −  Differentiate the instance variables from local variables if they have same names, within a constructor or a method. class Student { int age; Student(int age) { this.age = age; } }  Call one type of constructor (parametrized constructor or default) from other in a class. It is known as explicit constructor invocation. class Student { int age Student() { this(20); } Student(int age) { this.age = age; } } Example Here is an example that uses this keyword to access the members of a class. Copy and paste the following program in a file with the name, This_Example.java. public class This_Example { // Instance variable num
  • 9. int num = 10; This_Example() { System.out.println("This is an example program on keyword this"); } This_Example(int num) { // Invoking the default constructor this(); // Assigning the local variable num to the instance variable num this.num = num; } public void greet() { System.out.println("Hi Welcome to Tutorialspoint"); } public void print() { // Local variable num int num = 20; // Printing the local variable System.out.println("value of local variable num is : "+num); // Printing the instance variable System.out.println("value of instance variable num is : "+this.num); // Invoking the greet method of a class this.greet(); } public static void main(String[] args) { // Instantiating the class This_Example obj1 = new This_Example(); // Invoking the print method obj1.print();
  • 10. // Passing a new value to the num variable through parametrized constructor This_Example obj2 = new This_Example(30); // Invoking the print method again obj2.print(); } } This will produce the following result − Output This is an example program on keyword this value of local variable num is : 20 value of instance variable num is : 10 Hi Welcome to Tutorialspoint This is an example program on keyword this value of local variable num is : 20 value of instance variable num is : 30 Hi Welcome to Tutorialspoint Variable Arguments(var-args) JDK 1.5 enables you to pass a variable number of arguments of the same type to a method. The parameter in the method is declared as follows − typeName... parameterName In the method declaration, you specify the type followed byan ellipsis (...). Only one variable-length parameter may be specified in a method, and this parameter must be the last parameter. Any regular parameters 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");
  • 11. 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 will produce the following result − Output The max value is 56.5 The max value is 3.0 The finalize( ) Method It is possible to define a method that will be called just before an object's final destruction by the garbage collector. This method is called finalize( ), and it can be used to ensure that an object terminates cleanly. For example, you might use finalize( ) to make sure that an open file owned by that object is closed. To add a finalizer to a class, you simply define the finalize( ) method. The Java runtime calls that method whenever it is about to recycle an object of that class. Inside the finalize( ) method, you will specify those actions that must be performed before an object is destroyed. The finalize( ) method has this general form − protected void finalize( ) { // finalization code here } Here, the keyword protected is a specifier that prevents access to finalize( ) by code defined outside its class. This means that you cannot know when or even if finalize( ) will be executed. For example, if your program ends before garbage collection occurs, finalize( ) will not execute.