CodeGym /Courses /Java Syntax /Calling methods, returning values

Calling methods, returning values

Java Syntax
Level 2 , Lesson 7
Available

"OK, let's try another approach. I'll show you how calling methods works, and then you try to go through the previous lesson again, OK?"

"Let's do it."

"Great. I'll tell you about calling functions/methods and the values they return (return values)."

"Commands, or statements, are grouped into methods so they can be executed as a single block, like a single complex command. To do this, you need to write the method (function) name and then list the method's arguments inside parentheses."

Example
package com.codegym.lesson2;
public class MethodCall
{
    public static void main(String[] args)
    {
         print4("I like to move it, move it.");
    }

    public static void print4(String s)
    {
        System.out.println(s);
        System.out.println(s);
        System.out.println(s);
        System.out.println(s);
    }
}

"In the example above, we wrote a function that will display the passed string on the screen four times. Then we called the print4 function in line 6."

"When the program reaches line 6, it will jump to line 9, assigning the value 'I like to move it, move it' to the variable s."

"Then lines 11-14 will be executed. The function will finish, and the program will resume on line 7."

"I see."

"Not only can you pass arguments (values) to a function—a function can return the result of its work (return value). This is done with the keyword return. This is how it looks:"

Example 1.
Determine the minimum of two numbers.
public class MethodCall
{
   public static void main(String[] args)
   {
      int a = 5, b = 7;
      int m = min(a, b);
      System.out.println("The minimum is "+ m);
   }

   public static int min(int c, int d)
   {
      int m2; if (c < d) m2 = c; else m2 = d;

      return m2;
   }
}
Here's how it works:
public class MethodCall
{
   public static void main(String[] args)
   {
      int a = 5, b = 7;
      int c = a, d = b;
      int m2;
      if (c < d)
           m2 = c;
      else
           m2 = d;

      int m = m2;
      System.out.println("The minimum is "+ m);
   }
}

"I think it's starting to make sense! The code in the left and right columns is actually the same. It's just that the code on the left has a standalone function."

"The function computes a certain value and uses the return statement to pass that value to whatever called it. At least, that's how I see it."

"And you're right!"

"But what is this void type?"

"Some functions just do something without computing or returning any value, like our main() method. A special return type–void–was created for such functions."

"Why not just declare nothing if a function doesn't return anything?"

"Remember how we declare any variable? Type and name. For functions, we declare a type, name, and parentheses. A function name followed by parentheses is how you call the function."

"So, it was easier to invent a 'void type' than to divide functions into two categories – those that return values and those that do not?"

"Exactly! You're really smart, my boy."

"How do we return a void type?"

"We don't. It works like this. When executing the return statement, the Java machine computes the value of the expression to the right of the word 'return', stores this value in a special part of the memory, and immediately ends the function. The stored value is used where the function was called, as the result of calling the function. You can see it in the example I gave earlier."

"You mean the part where int m = min(a, b) is transformed into m = m2?"

"Yes. After the function is finished, everything works as if the function's return value was written in its place. Repeat this phrase in your mind and look at the code in the last example."

"I think this only seems easy. It's actually difficult. I've only understood parts of it."

"That's OK. On the first try, you can only understand things you already know. The more things you don't understand, the deeper you are plunging into something new, and the better your results will be. It will become clearer with time."

"Well, if you say so. Let's keep going."

Comments (74)
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION
Lunita Level 4, Dominican Republic
23 December 2022
Well, I've only understood parts of this lesson. Let's keep going and hoping I'll grasp everything later on.
Castro Level 3, Mexico, Mexico
3 February 2022
lo intente un par de veces y tienes que seguir el codigo paso a paso, cuando abres las llaves estas automaticamente crean una llave de cierre, tiene que eliminar la llave de cierre que se crea automaticamente.
Víctor Alfonso Martínez Gómez Level 3, Manizales, Colombia
10 August 2021
Ojo cada espacio, coma y demás cuanta
27 July 2021
Hola, repito el código exactamente igual y no me toma, porque sera?
Anonymous #10774868 Level 2, San Salvador
29 July 2021
Es igual, cada que hay lección que te repite escribir el código idéntico no te lo reconoce, siempre te quita materia oscura al pasar a la siguiente lección. saludos. => Pregunta como hiciste para que apareciera tu nombre y no así de feo como a mi?.
25 August 2021
Hola, yo me suscribí con mi gmail y me tomo los datos directamente, pero yo creería que lo puedes cambiar.
Lunita Level 4, Dominican Republic
23 December 2022
Me pasaba lo mismo y era que yo tenía un espacio de más en el método main
David Level 5
12 July 2021
The code entry validation is not working properly and we are loosing a tremendous time to figure. Please imrove the checking this way: TRIM both expected and actual results to save us some time.
Lunita Level 4, Dominican Republic
23 December 2022
Maybe you have extra spaces or lines somewhere.
Momcilo Injac Level 4, Novi Sad, Serbia
1 July 2021
I've improved the code in this lecuter :D

public class MethodCall
{
    public static void main(String[] args)
    {
         print4("I like to move it, move it.");
    }

    public static void print4(String s)
    {
        System.out.println(s);
        System.out.println(s);
        System.out.println(s);
        s = s.substring(0, Math.min(s.length(), 17));
        System.out.println(s + "!");
    }
}

Tom Haydock Level 4, Raleigh, United States
25 January 2021
"I shall return." - Gen. Douglas MacArthur 😎
Ru Level 2, Crown Point, United States
16 January 2021
It was very strange, because you had to follow it in the EXACT order. Not just have the same, but it has to be in order, meaning you can't have both parenthesis at the same time, you have to type one side and then type the other side as you get there.
JavaDude Level 3, Amstelveen, Netherlands
13 March 2023
this is the answer. somehow the auto closing brackets or curly braces are detected as wrong input. making the automated closing tags obsolete. when you type (a , b) or any of the class's {, always remove the } or ) that appears after { or (. It sucks, I know. Had to do this task twice, beacause it would not detect the entry as correct.
Kemka Ihemelandu Level 5, Baltimore, United States
26 December 2020
I've copied it the EXACT same, and yet it still won't work. I don't understand why. Can anyone please help?
Ahmad Level 7, Detroit, United States
30 December 2020
I just did it and it worked for me. Maybe you have extra spaces or lines somewhere.
Agent Smith Level 38
2 August 2020
Just for fun, you can actually write min method with just 1 line of code like this:
public static int min(int c, int d) {
    return (c < d) ? c : d;
}
It's called the "ternary operator". It can reduce the amount of code you write and often improve readibility. Or you can use Java API (which is essencially a bunch of prewritten classes):
Math.min(a, b);
So in practice there is no need (except as an exercise) to manually create such a method at all, since it already exists in Java.