Java method programming example
What is the method?
Method:-- a method is a collection of a
statement that perform some specific task and return the result to the caller.
We use the method in
java for different reasons:-
1. Reuse of our code.
2. Parameterize code
3. Top to a down programming approach
4. Conceptual units
5. Simplify our code
Type of method:-- there are two types described below.
Non –parameterized
method:- this type of method doesn’t have a provision to accept
external value and data.
Syntex:-
[access modifier] then [return type method]then[method name]then(parameter1 ,parameter2)
Public void display(int =a, String=c) {
//body of method
}
Parameterize
method:-- this type of
method have a provision to accept external values or data.
Syntex:-
[access modifier] then [return type method]then[method name]then(parameter1 ,parameter2)
Public void display(int =a, String=c) {
//body of method
}
Java return type
method and example
1.
Here
we use a return statement which is a type of jump statement.
2.
This
return statement returns the final
evaluated value of some data type as the type of our method.
3.
We
can create a method of all data types (primitive and non-primitive) so their
designed return value must match the
data type of the method.
4.
Method
which has the data type as void don’t need return value .hence we don’t write
return statement in void type method.
Programming Example:--
class MethodExample {
byte numOne,
numTwo;
void addnum()
{
System.out.println(“addition=” + (numOne+numTwo));
}
void subnum()
{
System.out.println(“substraction=” + (numOne+numTwo));
}
void multinum()
{
System.out.println(“multiple=” + (numOne+numTwo));
}
void divnum()
{
System.out.println(“division=” + (numOne+numTwo));
}
public static void
main (String args[]) {
MethodExample obj =
new MethodExample ();
obj.numOne= 10;
obj.numTwo= 23;
obj.addnum();
obj.subnum();
obj.multiple();
obj.div();
}
}
Programming
example :-
Class NumShow {
double [] show ()
{
double [] show
() {12.43D, 123.958d, 115.46D} ;
return show;
}
double [] show1
() {
double [] show1
() {20.43D, 23.58, 115.96D} ;
return show1 ;
}
Public static void
main (String args[]) {
NumShow s =
new NumShow ();
s.show();
s.show1();
}
}
1. Return type method:-
2.
Int show1
() { return
1; }
3.
byte show2
() { return
12; }
4.
long
show3 () {
return 1111111111L; }
5.
float show4
() { return
111.6f; }
6.
double show5
() { return
231.7566D; }
7.
boolean show6
() { return
true; }
8.
char show7
() { return
“p”; }
9.
String show8
() { return
“programming khata”; }
10.
Int
[] arrayshow9 ()
{
int[] arrayshow9={1,2,3,4,5,6,7,8,9,22,86,66,96};
return arrayshow9;
}
11.
void show10
() {
// no return type
}
0 Comments