Friday 2 September 2016

Methods in Java



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();
          }
}

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);
}
}

Example 3: -
program for function return value or string
class program12
{
          public String name;
public void nonpara1()
          {
                   System.out.printf("\nYour name is %s",name);
          }
public void setstring(String nm)
          {
                   name = nm;
          }
public String nonpara2()//string return
          {
                    return name;
          }
}
class char1
{
public static void main(String args[])
{
          program12 p = new program12();
          p.setstring("Safal");
          p.nonpara1();
          String abc = p.nonpara2();
          System.out.printf("\nYour name is %s",abc);
          System.out.printf("\nYour name is "+p.nonpara2());
}
}

Example 4: -
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);
          }
}
Example 5: -
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);
          }
}

No comments:

Post a Comment