Q. What is method in java?
Ans. A Method is a group of statements which can be executed
to perform a specific task. Methods are used for the concept of reuse ability.
In Java programs at least one Method, which is main().
Q. What are the uses of Methods in Java?
Ans.
1) Java
Methods are used to avoid rewriting same logic/code again and again in a
program.
2) We can
call the Methods number of times.
3) With the help of Methods we can easily track the large program
of java
Example of simple program of Method
Write
a simple program for Method
class demo
{
void
dis()
{
System.out.println("Hello
Safal");
}
}
class function
{
public static void main(String args[])
{
demo s
= new demo();
s.dis();
}
}
OUTPUT
Hello Safal
Note:-You can save the file
in second class name e.g. function.java
Example 2: -
class boxmethod
{
int l,b,h,v;
void input()
{
l = 1;
b = 2;
h = 3;
}
void vol()
{
v = l*b*h;
System.out.println("vol is "+v);
}
public static void
main(String k[])
{
boxmethod bx = new boxmethod();
bx.input();
bx.vol();
System.out.println("vol is "+bx.v);
}
}
OUTPUT
Vol is 6
Vol is 6
Example 3: -
Write a
simple program for method with parameter
class demo
{
void dis(int a)
{
System.out.println("value of a = "+a);
}
}
class fun_para
{
public static void
main(String args[])
{
demo s = new demo();
s.dis(5);
}
}
OUTPUT
Value of a = 5
Example 4: -
Write a program for method overloading.
class demo
{
void display()
{
System.out.println("Hello Safal");
}
void display(int a)
{
System.out.println(a);
}
}
class funover
{
public static void
main(String args[])
{
demo s = new demo();
s.display();
s.display(5);
}
}
OUTPUT
Hello Safal
5
Note:- This program you save the file in second class name e.g. funover.java
No comments:
Post a Comment