DEV Community

Harini
Harini

Posted on

Methods Examples in Java

Void method(With return)

public class Display{
    public static void main(String[] args){
        Display casio = new Display();
        casio.add();

    }
    public void add(){
        return;
    }
}
Enter fullscreen mode Exit fullscreen mode

Step-by-Step Execution

  1. Program starts from main()
  2. Display casio = new Display();
    • A new object of class Display is created.
  3. casio.add();
    • The add() method is called.
  4. Inside add():
    • return; simply exits the method
    • No value is returned because the method type is void
  5. Program ends

Output

Mark Calculation Program

public class Marks{

    public static void main(String[] args){
        int total = sumMarks(100,98,78,95,91);
        int avg = average(total);
        grade(avg);
    }

    public static int sumMarks(int m1,int m2,int m3,int m4,int m5){
        int total = m1 + m2 + m3 + m4 + m5;
        return total;
    }

    public static int average(int total){
        int avg = total/5;
        return avg;
    }

    public static void grade(int avg){
        if(avg>=90){
            System.out.println("A");
         }
        else if(avg>=80){
            System.out.println("B");
         }
        else if(avg>=70){
            System.out.println("C");
         }
        else if(avg>=60){
            System.out.println("D");
         }
        else if(avg>=50){
            System.out.println("E");
         }
        else{
            System.out.println("Fail");
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Step-by-Step Execution

  1. The program starts from the main() method.
  2. sumMarks(100,98,78,95,91) method is called.
  3. Inside sumMarks():
    • All marks are added β†’ 462
    • The value is returned to main()
  4. average(total) method is called.
  5. Inside average():
    • Average is calculated β†’ 462 / 5 = 92
    • The value is returned to main()
  6. grade(avg) method is called.
  7. Inside grade():
  8. Condition avg >= 90 is checked
  9. "A" is printed
    • The program ends successfully.

Output

Top comments (0)