P
P
PRAIT2020-11-30 09:33:18
Java
PRAIT, 2020-11-30 09:33:18

Why do you still need return?

Hello everyone, do I understand correctly that return is needed in order to transfer the result of the method's actions to the calling class? And if so, why is return needed in the code below? After all, even without returning data, the code will work. I don't quite understand, please explain.

public class Program{
      
    public static void main (String args[]){
          
        daytime(7);     // Good morning
        daytime(13);    // Good after noon
        daytime(32);    // 
        daytime(56);    // 
        daytime(2);     // Good night
    }
    static void daytime(int hour){
         
        if (hour >24 || hour < 0)
            return;
        if(hour > 21 || hour < 6)
            System.out.println("Good night");
        else if(hour >= 15)
            System.out.println("Good evening");
        else if(hour >= 11)
            System.out.println("Good after noon");
        else
            System.out.println("Good morning");
    }
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey Gornostaev, 2020-11-30
@PRAIT

The return statement, as its name suggests, returns a result or control from a method.
PS It's amazing that you've been asking Java questions since 2018 and still haven't mastered the very basics.

A
Alexander, 2020-11-30
@AleksandrB

Specifically, this code does not require a return, because it violates the Single Responsibility Principle. The daytime method in your case is responsible for 2 actions at once - determining what we output and its output. It would be correct to have the following code:

static String daytime(int hour){
        if (hour >24 || hour < 0)
            throw new IllegalArgumentException("Bad argument");
        if(hour > 21 || hour < 6)
            return "Good night";
        else if(hour >= 15)
            return "Good evening";
        else if(hour >= 11)
            return "Good after noon";
        else
            return "Good morning";
    }

And the output should be carried out in the main
ps method, I haven’t written in Java in my life, if there are jambs in the syntax, correct

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question