bugl
bugl
HomeLearnPatternsPathsSearch
HomeLearnPatternsPathsSearch

Loading lesson path

Learn/Java/Java Methods
Java•Java Methods

Java Return

Flash cards

Review the key moves

1/4
Core idea

What is the main idea behind Java Return?

Lesson checks

Practice each idea before moving on

Short Mimo-style checks built from this lesson's code, terms, and sequence.

1Quick choice

Which statement best captures the main point of this lesson?

2Fill blank

Complete the missing token from the example code.

public ___ Main {
3Order

Put the learning moves in the order that makes the concept easiest to apply.

This example returns the sum of a method's two parameters :
If you want the method to return a value, you can use a primitive data type (such as int , char , etc.
In the earlier lesson , we used the void keyword in all examples (like static void myMethod(int x) ), which indicates that the method should not return a value.

Return Values

In the earlier lesson , we used the void keyword in all examples (like static void myMethod(int x) ), which indicates that the method should not return a value.

If you want the method to return a value, you can use a primitive data type (such as int , char , etc.) instead of void , and use the return keyword inside the method:

Example

public class Main {
  static
  int
  myMethod(int x) {
    return 5 + x;
  }
public static void main(String[] args) {
  System.out.println(myMethod(3));
}
}
// Outputs 8 (5 + 3)

This example returns the sum of a method's two parameters :

Example

public class Main {
  static int myMethod(int x, int y) {
    return x + y;
  }
public static void main(String[] args) {
  System.out.println(myMethod(5, 3));
}
}
// Outputs 8 (5 + 3)

You can also store the result in a variable (recommended, as it is easier to read and maintain):

Example

public class Main {
  static int myMethod(int x, int y) {
    return x + y;
  }
public static void main(String[] args) {
  int z = myMethod(5, 3);
  System.out.println(z);
}
}
// Outputs 8 (5 + 3)

Practical Example

Here is a simple and fun "game example" using a method that returns a value, to show the double of the numbers 1 through 5 (using a for loop):

Example

public class Main {
  // Method that doubles the number static int doubleGame(int x) {
  return x * 2;
}
public static void main(String[] args) {
  for (int i = 1; i <= 5; i++) {
    System.out.println("Double of " + i + " is " + doubleGame(i));
  }
}
}

Previous

Java Method Parameters

Next

Java Method Overloading