0

so here is the code : i fully understand the code but i am confused why return is used and i do know what return keyword does . i tried running the code without using return but the result was same

import java.util.Scanner;

public class Calculator {

    public static void main (String[] args) {
        Scanner sc= new Scanner(System.in);
        int day, num1, num2;
        System.out.println("* * * * * * * * * * * *" +"\n" + "1. For addition" +"\n" + "2. For Subtraction" +"\n" + "3. For multipication" +"\n" + "4. For division" +"\n" +"* * * * * * * * * * * *");
        System.out.println("Please enter your 1st num");
        num1= sc.nextInt();
        System.out.println("Please enter your 2nd num");
        num2= sc.nextInt();
        System.out.println("Please enter your choice");
        day= sc.nextInt();
        if(day==4 && num2==0) {
            System.out.println("0 is not valid");
            return;
        };
        switch(day) {
            case 1: System.out.println(num1+num2);break;
            case 2: System.out.println(num1-num2);break;
            case 3: System.out.println(num1*num2);break;
            case 4: System.out.println(num1/num2);break;
            default : System.out.println("Wrong input");break;
        }
    }
}

Why is return used at the if condition line ?

Suraj Bhetwal
  • 29
  • 1
  • 3

2 Answers2

1

If you read the println, it says "0 is not valid". I am assuming (and you should as well) that the rest of the code cannot run given the input, so the return statement exits the program before it fails.

Lawrence Aiello
  • 4,560
  • 5
  • 21
  • 35
1

return statement from a void method will terminate the method and in this case, when you call it in public static void main it terminates the whole application.

Your code has a validity check and when the validation fails, your application writes an error message and quits.

Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
Michal Krasny
  • 5,434
  • 7
  • 36
  • 64