-1

I am a beginner in learning Java,

I Know this method is working,

public static double max(double num1, double num2) { 
   return Math.max(num1, num2);

}

I am asking why not using directly something like that:

public static double max(double num1, double num2) { 
     System.out.println (Math.max(num1, num2));

It is not working as far as I know

How could we know and predetermin that the method we write would need a "return" or "System.out.println" ?

Gamal Thomas
  • 103
  • 3
  • Do you know that every time you call `max`, you'll *always* want to only print the result to the screen? If you print the value out, it can't be used for any other purpose; like being used in another max equation later. – Carcigenicate Jul 11 '20 at 16:32
  • 1
    Does this answer your question? [Differences between System.out.println() and return in Java](https://stackoverflow.com/questions/25456472/differences-between-system-out-println-and-return-in-java) – Carcigenicate Jul 11 '20 at 16:33
  • I know that we would need system.print.out to show the result. I wonder when we use the return or system.print.out when creating our method? it seems a bit confusing. – Gamal Thomas Jul 11 '20 at 16:36
  • Unless you have a good reason to print inside the method, `return` the data from the method and let the code calling the method decide what they want to do with the returned data. If the caller wants to print the data out, let them do it. – Carcigenicate Jul 11 '20 at 16:37

1 Answers1

1

In fact, the second piece of code won't run at all. This is because the function isn't returning anything despite the fact that in the function header it says it will return a double. It should actually be this (note the void):

public static void max(double num1, double num2) { 
    System.out.println (Math.max(num1, num2));
}

Besides that, the point of the first one is that it only does what it says it does. It returns the max of the two numbers; nothing else. The second one is called max but for some reason it writes to the console. With the first one, you can do anything you like with the max value. With the second, you can only print it to console.

Emile Akbarzadeh
  • 326
  • 2
  • 14
  • Thank you so much but what are some examples of ***"with the first one you can do anything you like with the max value"***? – Gamal Thomas Aug 20 '20 at 07:18