0
0
Javaprogramming~15 mins

Return values in Java - Mini Project: Build & Apply

Choose your learning style8 modes available
folder_codeReturn values
📖 Scenario: You are creating a simple calculator program that adds two numbers and returns the result.
🎯 Goal: Build a Java program with a method that takes two numbers, adds them, and returns the sum. Then print the returned value.
📋 What You'll Learn
Create a method called addNumbers that takes two int parameters and returns their sum as an int.
Call the addNumbers method from main with the numbers 7 and 5.
Store the returned value in a variable called result.
Print the value of result.
💡 Why This Matters
🌍 Real World
Returning values from methods is how programs get results from calculations or data processing.
💼 Career
Understanding return values is essential for writing reusable code and building functions that communicate results in software development.
Progress0 / 4 steps
1
Create the main class and method
Create a public class called Calculator with a main method inside it.
Java
💡 Need a hint?

Start by writing public class Calculator { and then add the main method inside.

2
Create the addNumbers method
Inside the Calculator class but outside the main method, create a public static method called addNumbers that takes two int parameters named a and b, and returns their sum as an int.
Java
💡 Need a hint?

Write a method with public static int addNumbers(int a, int b) and return the sum of a and b.

3
Call addNumbers and store the result
Inside the main method, call the addNumbers method with the arguments 7 and 5. Store the returned value in an int variable called result.
Java
💡 Need a hint?

Inside main, write int result = addNumbers(7, 5); to call the method and save the sum.

4
Print the result
Add a line inside the main method to print the value of the result variable using System.out.println.
Java
💡 Need a hint?

Use System.out.println(result); to show the sum on the screen.