Result of a method

Module 1. Java Syntax
Level 9 , Lesson 2
Available

1. The return statement

Think you've already learned all about Java methods? Whatever you think you know, you still don't know the half of it.

Let's start with something simple. For example, Java has a return statement that lets you instantly terminate the method that calls it. Here's the statement:

return;

It's simple: the solitary word return followed by a semicolon. As soon as the program executes this statement, the current method exits immediately, and the calling continues.

If return is called in the main method, then the main method will immediately end, and with it the entire program.

Example:

class Solution
{
   public static void fill(int[] data, int from, int to, int value)
   {


     if (from < 0 || to > data.length)
       return;

     for (int i = from; i < to; i++)
     {
       data[i] = value;
     }
   }

   public static void main(String[] args)
   {
     int[] months = {1, 2, 3, 4, 5, 6, 7, 8 ,9, 10, 11, 12};
     fill(months, 2, 10, 8);
   }
}


The fill method fills part of the passed array with value.
The part of the array to be filled is defined by the indices from and to.
If from is less than 0 or if to is greater than the length of the array, then the method terminates immediately.

The above program has a fill method that fills the array passed to it with value. It does not fill the entire array, only the part specified by the indices from and to.

At the beginning of the fill method, the passed values are checked to ensure that they are valid. If from is less than 0, or if to is greater than the length of the array, then the fill method terminates immediately (executes a return statement).

This return statement is useful: practically every method in Java has one, and here's why.


9
Task
New Java Syntax, level 9, lesson 2
Locked
Octal converter
The public static toOctal(int) method must convert the integer received as an input parameter from the decimal numeral system into octal. And conversely, the public static toDecimal(int) method converts from the octal system into decimal. The methods only work with positive numbers. If the input par

2. Methods with a result, void

Remember we once figured out that there are statements, and there are expressions. An expression, unlike a statement, has a value that can be used somewhere.

And, in Java, methods can have a value. And this is very good news: methods are not only able to do something based on the input parameters, but also, for example, to evaluate something and return the result of the calculation.

By the way, you have already encountered such methods:

double delta = Math.abs(d1 - d2);
The abs() method returns a double
Scanner console = new Scanner(System.in);
int x = console.nextInt();

The nextInt() method returns an int
String str = "Hello";
String s2 = str.toUpperCase();

The toUpperCase() method returns a String
int[] data = {1, 4, 5, 6, 7, 8, 11};
int[] array = Arrays.copyOf(data, 4);

The copyOf() method returns an int[]

Each method can only return one value of one predetermined type. The return type is determined when the method is declared:

public static Type name(parameters)
{
  method body
}

Where name is the name of the method, parameters is the list of method parameters, and type is the type of the result that the method returns.

For methods that return nothing, there is a special placeholder type: void.

Are you writing your own method and don't want to return anything to the calling method? Just declare the method's type as void, and the problem is solved. There are also lots of methods like this in Java.


3. Returning a result

We just figured out how to declare a method that returns the result of a calculation, but how do we result this result in the method itself?

The return statement helps us out here once again. Passing a result from a method looks like this:

return value;

Where return is a statement that terminates the method immediately. And value is the value that the method returns to the calling method when it exits. The type of value must match the type specified in the method declaration.

Example 1. The method calculates the minimum of two numbers:

int min(int a, int b)
{
   if (a < b)
     return a;
   else
     return b;
}
The method returns the minimum of two numbers.

If a < b
return a
Otherwise
return b

Example 2. The method duplicates the string passed to it n times:

String multiple(String str, int times)
{
   String result = "";
   for (int i = 0; i < times; i++)
     result = result + " "+ str;
   return result;
}
The method takes two parameters — a string and the number of times that the string should be repeated.
An empty string is created for the future result.

In a loop with times iterations, a space and the str string is added to the result string.

The string result is returned as the result of the method.

Example 3: The method calculates the maximum of two numbers using the ternary operator:

int max(int a, int b)
{
   return (a > b ? a : b);
}
The method returns the maximum of two numbers.

return (if a > b, then a, otherwise b)

9
Task
New Java Syntax, level 9, lesson 2
Locked
Binary converter
The public static toBinary(int) method must convert the integer received as an input parameter from the decimal numeral system to binary and return its string representation. And conversely, the public static toDecimal(String) method converts from the string representation of a binary number to a de
9
Task
New Java Syntax, level 9, lesson 2
Locked
Hexadecimal converter
The public static toHex(String) method must convert the integer received as an input parameter from the decimal numeral system to hexadecimal and return its string representation. And conversely, the public static toDecimal(String) method converts from the string representation of a hexadecimal numb
9
Task
New Java Syntax, level 9, lesson 2
Locked
Binary to hexadecimal converter
The public static toHex(String) method must convert the string representation of a binary number, received as an input parameter, from the binary numeral system to hexadecimal and return its string representation. And conversely, the public static toBinary(String) method converts from the string rep
Comments (13)
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION
haalk3n Level 6, Romania
29 February 2024
Hate this website. I HATE IT.
Jesú Level 14, Madrid, Spain
8 March 2024
Why do you hate it? The explanations are very comprehensive. If you just don't like to code the exercises here, you should really download IntelliJ and use their plugin.
Pekotski Level 16, Zurich, Switzerland
17 October 2023
Also I find it strange that we are dealing with return in methods without even as much as few words on how to print return values? How are people supposed to test their solutions if they don't see the values returned?
Pekotski Level 16, Zurich, Switzerland
17 October 2023
Why is this solution failing? cube(a) * cube(a) * cube(a);
Parsa Level 62, Bangalore, India Expert
22 October 2023
I think because it specifically mentioned cube should be called twice.
curi0usmind Level 10, Switzerland Expert
1 August 2023
Why do we need this return?

     if (from < 0 || to > data.length)
       return;
Can't we just write

 if (from > 0 && to < data.length) {
     for (int i = from; i < to; i++)
     {
       data[i] = value;
     }
}
Xm Level 24, Israel
21 September 2023
No, because if "from" < 0 then data[some negative number] will be error, as array can't be with negative capacity
Parsa Level 62, Bangalore, India Expert
22 October 2023
The correct equivalent would be

if (from >= 0 && to <= data.length) 
But I guess that's beside the point. I suppose they just wanted to illustrate the point of returning void.
Rachit Goel Level 7, Darien, United States
21 December 2022
For the cube question, why is this solution wrong? public class Solution { public static void main(String[] args) { } public static long cube(long num){ return num^3; } }
Gummy C Level 11, United States of America, United States
3 January 2023
I don't think Java understands that. From what I googled you can use Math.pow(), but I dont think we can use that here.
Hiyo Level 24
17 January 2023
^ operator in Java means "XOR"
D3rk Level 21
17 April 2023
I guess you can use: Math.pow(num, 3) or simply: return num*num*num;
Alexander Anderson Level 22, United States of America, United States
16 November 2022
What is this?