Question

So this might be an exceptionally dumb question, but before you burn this post to smolders, please hear me out XD. Below I've written three basic classes, all of which accomplish the same thing, but through various means:

Class A ( break ) -

import java.util.Scanner;
public class ClassA
{
    public static void main(String[] args)
    {
        Scanner in = new Scanner(System.in);
        while(true)
        {
            System.out.print("Enter a sentence (/q to quit): ");
            String sentence = in.nextLine();

            if(sentence.equals("/q"))
                break;
            else
                System.out.println("Thank you!");
        }
    }
}

Class B ( return ) -

import java.util.Scanner;
public class ClassB
{
    public static void main(String[] args)
    {
        Scanner in = new Scanner(System.in);
        while(true)
        {
            System.out.print("Enter a sentence (/q to quit): ");
            String sentence = in.nextLine();

            if(sentence.equals("/q"))
                return;
            else
                System.out.println("Thank you!");
        }
    }
}

Class C ( System.exit(0) ) -

import java.util.Scanner;
public class ClassC
{
    public static void main(String[] args)
    {
        Scanner in = new Scanner(System.in);
        while(true)
        {
            System.out.print("Enter a sentence (/q to quit): ");
            String sentence = in.nextLine();

            if(sentence.equals("/q"))
                System.exit(0);
            else
                System.out.println("Thank you!");
        }
    }
}

While I prefer Classes A and C, is there anything wrong with B? More specifically, is it bad practice to use a return statement to exit from the main method of a program? If so, why?

Thanks in advance!

Was it helpful?

Solution

Using return is exactly the right thing to do, because it makes your main easier to test -- your test framework doesn't need to intercept exit attempts.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top