Method/Function:
What is a Method :
A method is a collection of
statements (or a block of statements) that can be used to perform a specific
task.
A method is a group of statements that can be
used to perform a specific task.
Example:
For instance, adding two numbers 10 + 20 = 30 à task
public static void main(String
args[])
{
// args- is array name
// main
is- method `
stmt1;
stm2;
stmt3;
}
Types of Methods:
- User-defined
method
- Predefined
method
1. User-Defined method:
If method is defined by
programmer is called User-Defined
method:
Syntax for Writing a Method:
Method with No Arguments:
AccessSpecifier
nonAccessSpecifier returnType methodName() //// Method heading
{
// Beginning of the method
stmt1; // Method body
stmt2;
stmt3;
} // End of the method
Access specifier --> public, private, protected, default
non AcessSpecifier --> static
Return type -->
void, int, float, char, boolean, String, array, etc.
public static void main(String
args[])
Examples:
1.write 'add' method?
//
Method name :
public static void add() //
Method heading
{ // startig of method
stmt-1; // Method body
stmt-2;
} // end of method
2.Write substraction()?
// sub
// Method name : substraction
public static void substraction()
{
}
3.write method name multiplication, return type: int
public static int
multiplication()
{
}
HW write method name 'Division'
, return type: float
public static float division() //
Method name : division
{
}
HW write method name Division ,
return type: char
public static char divison()
{
}
HW write method name
getFirstName , return type: String
HW write method name
clickLoginButton, return type: void
Method call:
To execute the statements inside
a method, the method must be called by its name.
If we
want to execute statements inside the Method-
we must call method by it's name.
Syntax:
- methodName();
Examples:
- Call add Method:
add();
call substraction() --> substraction();
call Mulitplication() --> Mulitplication();
ex1 :Addition:
package MethodBasics;
public class AdditionBasics {
// method is defined in side the class
//
define add() and call below stmts
public
static void add() {
System.out.println("performing
addition - stmt-1");
System.out.println("stmt-2");
}
public
static void main(String[] args)
{
System.out.println("in
main method");
//
Call method
// syntax: methodname();
add();
System.out.println("after
add -");
}
}
o/p:
in main method
performing addition - stmt-1
stmt-2
after add -
ex2: Define M1() , M2() and
Calling M1() , M2():
package MethodBasics;
public class MethodBasics2
{
//
Define Method name M1 () and call below
stmts
public
static void M1()
{
System.out.println("stmt-1");
System.out.println("stmt-2");
}
//Define
Method - M2 and call below stmts
public
static void M2()
{
System.out.println("stmt-3");
System.out.println("stmt-4");
}
public
static void main(String[] args)
{
//
If we want to execute any method stmts, we must call specific method
// with out calling method, we cannot execute
method stmts
//
call M1
M1();
//
Call M2
M2();
}
}
o/p:
stmt-1
stmt-2
stmt-3
stmt-4
-We can define/ write any number
of methods inside the class
M1(),M2(), M3(), M4()...
Ex3: Define add () and call it:
package MethodBasics;
public class
AddMethodWithOutArgs3 {
//ex: Define add () and call it:
public
static void add()
{
// 10 + 20
int res = 10 + 20;
// 30
// res = 30
System.out.println("Addition
result="+ res);
// Addition result= 30
}
public
static void main(String[] args)
{
System.out.println("inside
main()");
//
Calling add()
add();// ctrl wil go to add()
System.out.println("after
add ()");
}
o/p:
inside main()
Addition result=30
after add ()
ex4: Define Substraction() and call
it?
package MethodBasics;
public class SubtractionBasics1 {
// Define
Subtraction()
public static void
subtraction()
{
int
result = 20-10;
//
//
System.out.println("Result
fo substrcation ="+ result);
}
public
static void main(String[] args)
{
System.out.println("inside
main()");
//
call substraction()
subtraction();
System.out.println("after
sub ()");
}
}
o/p:
inside main()
Result fo substrcation =10
after sub ()
ex5: Define add() , substraction()
Note:
We can define every method inside
class only.
We can define 1 or 2 methods or multiple
methods inside class.
package MethodBasics;
public class SubtractionBasics1 {
public
static void add()
{
// 10 + 20
int res = 10 + 20;
// 30
// res = 30
System.out.println("Addition
result="+ res);
// Addition result= 30
}
//
Define Subtraction()
public
static void subtraction()
{
int
result = 20-10;
// 10
// result
=10
System.out.println("Result
fo substrcation ="+ result);
//
10
}
public
static void main(String[] args)
{
System.out.println("inside
main()");
//
call add ()
add();
//
call substraction()
subtraction();
System.out.println("after
sub ()");
}
}
o/p:
inside main()
Addition result=30
Result fo substrcation =10
after sub ()
HW Define
multiplication method and display
o/p
HW Define Division method (get Quotient number - / )and display o/p ?
HW Define Remainder Method (get remainder value - % ) and display o/p?
Methods with
Input Arguments in Java:
Arguments :
·
Arguments are used to pass data or inputs to a
method.
·
They are also called parameters.
Syntax :
Method
without Arguments:
- No arguments means no
variables are passed inside the parentheses ().
public static void add() //
add() without args
{
}
Method
with One Integer Argument:
- This method accepts one
integer argument.
// // Method with 1 int argument/parameter
MethodName(int a)// // Method with 1 int argument/parameter
{
}
Method with
Two Arguments:
This method accepts two integer
arguments.
1 int arg , 1 int arg
// Method with 2 arguments/ param
// arguments -- i/p's to method
(or) declaring variable
M2(int a, int b)
{
}
Method with
Three Arguments:
This method accepts three
arguments of different types.
Method with one integer argument,
one float argument, and one char argument.
Define Method -M1 with 1 int arg,
1 float arg, 1 char arg
M1(int a, float f, char ch)// M1
method has 3 arguments
{
}
Pass 1 arguments / parameter in method
heading
pass 2 arguments/
parameter in method heading
pass 3...
n
no of args in method heading
// pass any no of arguments / parameters-
and any data type (int, float,double, char,boolean, etc)
Calling
Methods with Arguments/ parameter
Ex1:
M1(int a) // M1 () contains - 1 arg/parameter
{
}
method Call :
-->
M1(10);// // Passing the value 10 as an argument
M1(); --invalid method call
ex2:
M2 (int a , int b ) // 2 args
{
}
method call --> M2(10,20);// // Passing the values 10 and 20
as arguments
Note:
·
No of
arguments /parameters in method heading =
number of values in method call must be same
For example, if method has 2 arguments,
in method call also, we must also pass 2 values..
M2(10);// invalid as we passed only one value but in method heading 2 args
if 2 args in method heading, we
must pass 2 values in method call also.
ex3:
M3 (int a, float f, char ch) // 3 args
{
}
method Call --> M3(10, 2.45f ,'A');// // Passing the values
10, 2.45f, and 'A' as arguments
The data types of the values in
the method call must match the data types of the arguments in the method
definition.
M3 ('A', 10, true ); //
--> check valid /invalid-->
invalid
// VALUEs must match with data type
M3 ('A', 10, true ); // invalid
M3(10,2.3f, 'B',20);// invalid
passing 4 values , but method
heading contains 3 args- so we must pass 3 values only in method call but not 4 values
ex:
Define Method Input arguments and call Method :
package MethodBasics;
public class MethodWith1InputArgs
{
// Method M2 with 1 int args
public static void M2(int a)
{// 10
so a = 10
//
System.out.println("in
M2");//
System.out.println("a=
" + a);
// a= 10
}
public
static void main(String[] args) {
//
call method M2()
M2(10);// ctrl will goes to M2()
// call
method M2 any no of times
}
}
o/p:
in M2
a= 10
Calling method 2 times:
package MethodBasics;
public class MethodWith1InputArgs
{
// Method M2 with 1 int args
public static void M2(int a)
{// 20 so a =
20
//
System.out.println("in
M2");//
System.out.println("a=
" + a);
// a= 20
}
public
static void main(String[] args) {
//
call method M2()
M2(10);// ctrl will goes to M2()
// call
method M2 any no of times
M2(20);
}
}
o/p:
in M2
a= 10
in M2
a= 20
passing invalid float value:
package MethodBasics;
public class MethodWith1InputArgs
{
//
Define M1 with 1 int arg
public
static void M1(int a)
{
System.out.println("in
side M1 -");
System.out.println("M1
-with 1 int arg");
System.out.println("a="+
a);
}
public
static void main(String[] args) {
// Method call:
// ---------------------
// M1(10);
// M1(2.45f);//Error: invalid
we should not pass float value / Decimal no in method call
//as
we have M1 (int a) . So we must pass it value in the method call
}
}
Method with 2
i/p arguments:
package MethodBasics;
public class
MethodWith2InputArgs1 {
//
Define/ write M1 with 2 args 1 int, 1
int arg
public
static void M1(int a, int b)
{
System.out.println("M1
With 2 args");
System.out.println("a="+
a);
System.out.println("b="+
b);
}
public
static void main(String[] args)
{
System.out.println("in
main()");
//
Call M1
M1(10,20);
System.out.println("after
M1 ()");
}
}
o/p:
in main()
M1 With 2 args
a=2
b=3
after M1 ()
ex: Define 'add' method with 2 i/p arguments and call add()?
package MethodBasics;
public class AddMethodWith2args {
// ex: Define 'add' method with 2 i/p
arguments and call add()?
// ----------------------------------
//
add() with 2 args
public
static void add(int a, int b)
{
// 10 20 .
so a =10 , b =20
System.out.println("called
add()");
int
c = a + b;
// 10 +20
// 30
// c = 30
System.out.println("c="+
c);
// c= 30
}
public
static void main(String[] args)
{
//call
add() by passing 2 value
add(10,20);
}
}
o/p:
called add()
c=30
HW WAP to define
substraction and Pass 2 arguments and display result
package MethodBasics;
public class
substractionMethod2Args {
// WAP
to define substraction and Pass 2
arguments and display result
public
static void substraction(int a, int b)
{// 50 40 . so
a= 50 b = 40
System.out.println("called
Substraction()");
int
result = a -b;
// 50-40
// 10
// result =
10
System.out.println("Substraction
results="+result);
//
10
}
public
static void main(String[] args) {
//
Call substraction
//
call method substraction- passing 2 values
substraction(50,40);
}
}
o/p:
called Substraction()
Substraction results=10
HW WAP to define Multiplication
and Pass 2 arguments and display result
HW WAP to define Multiplication
and Pass 3 arguments and display
result 2*3 *4
HW WAP to define Division and
Pass 2 arguments and display result
Note:
// add(3.5f,4);// Error :
The method add(int, int) in the type
MethodWith2Args is not applicable for the arguments (float, int)
Method with
Return Types:
Syntax:
returnType M1() {
// Method body
return value/variable/expression;
}
return:
a predefined keyword in Java used to get the output from a method, returning
some value from the method.
Syntax:
return value/variable/expression;
// ex :
return 10;
// ex:
return a;
// ex3:
return a+b;
Note:
·
Method return type and Return value must be same
.
Return Examples:
// Example 1: Returning a
constant value
public static int M1() {
return 10;
}
// Example 2: Returning a float
constant value
public static float M2() {
return 10.45f;
}
// Example 3: Returning a
character constant value
public static char M3() {
return 'B';
}
// Example 4: Returning a string
constant value
public static String M4() {
return "Ram";
}
// Example 5: Returning a
variable value
public static int M5(int a) {
return a;
}
// Example 6: Returning an
expression
public static int M6(int a, int
b) {
return a + b;
}
Return
Type and Return Value: The return type of the method must match the type of the return value.
- Example: If the method
return type is int, the returned value must be
an integer.
- Example: If the method
return type is float, the returned value must be
a float.
- Example: If the method
return type is char, the returned value must be
a character.
- Example: If the method
return type is String, the returned value must be
a string.
// Define add() - pass 2 int -args
-perform addition and return
result ?
package MethodBasics;
public class
AddWith2ArgsReturnResult {
//
Define add() - pass 2 int -args -perform
addition and return result ?
// public static void
add(int a, int b)// void method cannot return any value
// void means nothing--void method cannot
return any value
// void methos - dont write return stmt
/ return keyword inside void method
public
static int add(int a, int b)
{// 2 3
so a = 2 b =3
System.out.println("Called
add()");
int
result = a+ b;
// 2 +
3
// 5
// result = 5
System.out.println("result
= "+result);
// result = 5
// return type int, so we must write return stmt
return
result ;
// return
5 ;
}
public
static void main(String[] args) {
// call
add by passing 2,3 and store result into variable i.e x
int
x = add(2,3);
// 5
// x=
5
System.out.println("x="+
x);
// 5
System.out.println("after
add ");
}
}
o/p:
Called add()
result = 5
x=5
after add
Return constant val :
--> return val; --> return 10; return 20;
package MethodBasics;
public class
AddWith2ArgsReturnResult {
//
Define add() - pass 2 int -args -perform
addition and return result ?
// public static void
add(int a, int b)// void method cannot return any value
// void means nothing--void method cannot return
any value
// void methos - dont write return stmt
/ return keyword inside void method
public
static int add(int a, int b)
{// 2 3
so a = 2 b =3
System.out.println("Called
add()");
int
result = a+ b;
// 2 +
3
// 5
// result = 5
System.out.println("result
= "+result);
// result = 5
// return type int, so we must write return stmt
return
100; // this method gives/ returns o/p
100
// return result ;
// return
5 ; // this method gives/ returns o/p 5
}
public
static void main(String[] args) {
// call
add by passing 2,3 and store result into variable i.e x
int
x = add(2,3);
// 100
// x=
100
System.out.println("x="+
x);
//
System.out.println("after
add ");
}
}
o/p:
Called add()
result = 5
x=100
after add
--------------------
return 25;
return varNAme;
return expre;
package MethodBasics;
public class
AddWith2ArgsReturnResult {
//
Define add() - pass 2 int -args -perform
addition and return result ?
// public static void
add(int a, int b)// void method cannot return any value
// void means nothing--void method cannot
return any value
// void methos - dont write return stmt
/ return keyword inside void method
public
static int add(int a, int b)
{// 2 3
so a = 2 b =3
System.out.println("Called
add()");
// int result
= a+ b;
//
return exp;
return
a+b;
// 2 + 3
// 5
// return 5;// this metod gives/returns o.p:
5
}
public
static void main(String[] args) {
// call
add by passing 2,3 and store result into variable i.e x
int
x = add(2,3);
// 5
// x=
5
System.out.println("x="+
x);
// 5
System.out.println("after
add ");
}
}
o/p:
Called add()
x=5
after add
-------------------------------------
Note:
return
a+b; // gives int o/p, return type must be int
// if we are returning float o/p,
return type must be float
// char o/p, char
Method
ReturnType Float :
package MethodBasics;
//
Note : if Method return type is float,
we must return float val/ float var
// return type must be written just before the
method name
// ex"
void, int, float, char, boolean, String also
package MethodBasics;
public class
MethodReturnTypeFloat {
//
Define add () pass 2 float args and return type float
//
//
//result =
System.out.println("result="+
result);
//
//
// return 3.45f;
public
static void main(String[] args) {
//
call add () - pass 2.5f and 1.5f
// 4.0
we are not storing result into
any variable
// call add () - pass 2.5f and
1.5f and store into int variable x
// 4.0f
error: Type mismatch: cannot convert from float to int
//
// call add () - pass 2.5f and
1.5f and store into float variable x
// x=
//
display x
}
}
o/p:
result=4.0
result=4.0
x=4.0
Method Return Type Char :
package MethodBasics;
public class MethodReturnCharVal
{
//
Define add() and return type 'char' and
return 'A'
// public static void add()// void method- cannot return any
value
public
static char add()//
{
//
Method with return type char - so method return char val o/p
System.out.println("in
side add");
//
return the result
return
'A';
// gives o/p :
'A'
}
public
static void main(String[] args) {
//
call add() and don't store result into
var
add();
// 'A'
// call add() and store result into variable i.e ch
char
result = add();
//
// display result
System.out.println("result
="+ result);
}
}
o/p:
in side add
in side add
ch=A
Important Points:
The return
statement is the last executable statement inside a method.
Any statements written after the return statement will be considered unreachable code
and will cause a compile-time error.
Example of Unreachable Code:
public static int M7() {
return 10;
// System.out.println("This will cause
an error"); // Unreachable code
// System.out.println("after return
stmt");//Unreachable code
// return 20; // Unreachable code
}
// once we write return stmt, dont write any
stmts after return stmt
// return ch;// Unreachable code
A method should have a single return statement. Multiple return statements in a single method can cause
confusion and errors.
//
We cannot write multiple return stmts inside method
public
static char add() // Method with return type char - so method return char val
o/p
{
System.out.println("in
side add");
return
'A';// gives o/p : 'A'
// System.out.println("after return
stmt-1");// Unreachable code
// System.out.println("after return stmt
-2");//Unreachable code
// return 'B';// Error :
}
Note:
// return 10,20,30;// in valid
// return ch,res;// in valid
return val/var/expression:
return 10;
int b=20;
return b; return val of variable b
//
return a+b-2; // evaluates expression and result is
returned
HW WAP to define method to perform division and return the o/p and display the o/p inside main()
HW WAP to define method to get Remainder val and return the o/p and display the o/p inside main()
HW WAP to define method to perform subtsraction and return the o/p and o/p+ 200 from main()
WAP to define method i.e
checkEvenNo and pass argument as int no,
if it is even no, return boolean value i.e true,
else retun false
value and display the result in main()?
boolean
checkEven(int no)
{
}
package MethodBasics;
public class EvenNoBasics {
// WAP
to define method i.e checkEvenNo
and pass argument as int no,
// if it is even no, return boolean
value i.e true,
// else retun false value and display
the result in main()?
//
public
static boolean checkEvenNo(int no)
{// 3 . so no = 3
//
check given no is even or not
if(no%2
== 0) // is didvisle by 0 and remainer
== 0 --> even no
{
// 3%2
//
1 == 0 - false - enters else
System.out.println("Given
no ="+ no + " is even
no");
return
true;
}
else
{
System.out.println("Given
no ="+ no + " is not even
no");
// 3 is not even no
return
false;
}
}
public
static void main(String[] args) {
System.out.println("in
side main ()");
//
call checkEvenNumber pass -2
checkEvenNo(2);
// true
// true 10 ,20
//
call checkebenno () pass -2 and store
result into some variable result
boolean result = checkEvenNo(2);
// true
// // result
= true
// // this method gives
o/p/ return o/p boolean value i.e true
// // return value i.e true will be stored in
left side varible i.e result .
//So
Result variable contains 'true' value
//
display result
System.out.println("result="+result);
///
true
//
call checkebenno () pass -3 and store
result into some variable result
boolean result2 = checkEvenNo(3);
// false
// result2
=
//
this method gives o/p/ return o/p boolean value i.e false
// return value i.e false will be stored in
left side varible i.e result .
//
So Result variable contains 'false value
//
display the result
System.out.println("result2="+result2);
// false
}
}
Identifying Method Return Type:
- Hover to Identify: If
unsure of a method's return type, hover the mouse over the method name
(e.g.,
checkOddNumber) in your IDE. The IDE will display the return type, such aschar.
(Or)
If
we don’t know what method return value, Move the mouse over on method name i.e
checkOddNumber, it displays return type i.e char.
So left side , we must declare 'char' variable
only but not int, float,boolean
2.Go to method
definition, Check return type i.e char.
So left side, we must declare char variable only but not int, float, boolean
System.out.println("Method
returns char value ="+result);
//
'N'
HW WAP to define method to check given no is odd no and return some char o/p
if it is odd no -- return char
'Y'
else
'N'
Return type String :
HW WAP to define method i.e
checkEvenNo and pass argument as int no,
//if it is even no,
return "Yes" value
// else return "No" value
and display the result in main()?
void Methods in
Java:
· void: Represents "nothing".
· void Method: A method that does not return nothing
any value.
If a method's return type is void, that method returns nothing i.e it
does not return any value.
void is predefined k/w in java
void can be used before method
name.
It indicates that the method will
perform an action but will not return any result.
When to use:
When we don’t want to get any o/p from method,
we will go for void
When we don’t want to return any
o/p from method, we will go for void
· No need to
store a return value, as there is none.
· Example: methodName();
package MethodBasics;
public class VoidMethodBasics {
//define
void add() and pass 2 int args
public
static void add(int a, int b)
{// 2 3
so a = 2 , b =3
// void method
// cannot return any value // cannot give o/p
//
// a= b=
int
result= a+b;
// 2 + 3
// 5
// result =
5
//
display result
System.out.println("result="+
result);
// 5
// return the result
// return 10; //CE: Void methods cannot return any value
// if method return type is void, Don’t write return stmt inside void method
}
public
static void main(String[] args) // main
is void method - cannot return any value
{
//
TODO Auto-generated method stub
//call
add() pass 2,3
add(2,3);
//
call add() ,pass 2,3 ans store result into some variable i.e result
// int res = add(2,3);//// Type mismatch: cannot convert from void to
int
//int
res = add(2,3);//error : this method
does not return any o/p. so dont store result into left side var
// if method return type is void, dont store o/p into some variable / dont
declare any variable left side
// void v
= add(2,3);// Error: void is an invalid type for the variable v
System.out.println("ends");
}
}
o/p:
res=5
ends
No comments:
Post a Comment