Calling Methods In Main // Java | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3

Calling Methods In Main // Java

Hello awesome coders! I've got a question. I'm going through the Java methods module and have noticed that they always declare a new variable and assign it to the desired method in main. Why's that? Is that good programming practice and why? Here's an example: class Program { public static void main(String[ ] args) { int res = max(7, 42); System.out.println(res); //Why not System.out.println(max(7,42))? We don't need to declare a new variable (res in this case)? } static int max(int a, int b) { if(a > b) { return a; } else { return b; } } }

12th Jan 2017, 10:45 PM
Daniel Stanciu
Daniel Stanciu - avatar
4 Answers
+ 2
I'll explain it with parts of your code.. If you would work with variables in your max function it would look like this int res = max(x,y); If you write System.out.println(max(x,y)); // This will be the line if an exception occurs. independent from where it got thrown (the println or the max function) If you write int res = max(x,y); // This line will be in the stacktrace if an exception is thrown here System.out.println(res); // This line will be in the stacktrace if an exception is thrown by the output
12th Jan 2017, 11:02 PM
Andreas K
Andreas K - avatar
+ 1
@AKC Thanks for your reply! Please can you expand a little, perhaps with an example?
12th Jan 2017, 10:57 PM
Daniel Stanciu
Daniel Stanciu - avatar
+ 1
Thanks @AKC!
12th Jan 2017, 11:04 PM
Daniel Stanciu
Daniel Stanciu - avatar
0
I think it can make it more clear where an exception occurs if you write it like that
12th Jan 2017, 10:48 PM
Andreas K
Andreas K - avatar