Function in java


Function is defined as a bundle of code to perform a specific task. It will be executed, when it is called. It is used for code reusability and to reduce the lines of code.








Types of Function



  1. No argument no return type
  2. With argument no return type
  3. No argument with return type
  4. With argument with return type







1. No argument no return type



This type consists of no parameter and no return type.




Example
public class Main
{
         public static void main(String[] args) 
         {
                  Main obj = new Main();

                  obj.science();
         }

         public void science()
         {
                 System.out.print("physics");
         }
}


Output



physics







2. With argument no return type



This type consists of parameter but no return type.




Example
public class Main
{
        public static void main(String[] args) 
        {
             Main obj = new Main();

             obj.science(25);
        }

        public void science(int marks)
        {
             System.out.print("science marks:"+marks);
        }
}


Output



science marks:25







3. No argument with return type



This type does not consists of parameter but contain return type.




Example
public class Main
{
        public static void main(String[] args) 
        {
            Main obj = new Main();

            System.out.print("science marks:"+obj.science());
        }

        public int science()
        {
            int marks = 25;

            return marks;
        }
}


Output



science marks:25







4. With argument with return type



This type consists of both parameter and return type.




Example
public class Main
{
       public static void main(String[] args) 
       {
            Main obj = new Main();

            System.out.print("science marks:"+obj.science(25));
       }

       public int science(int marks)
       {
            return marks;
       }
}


Output



science marks:25