Get startedGet started for free

Adding parameters

1. Adding parameters

In the last video, we learned about custom methods. Now, let's make those methods a bit more flexible by adding parameters.

2. Parameters

Parameters allow us to pass input values into a method so that it can use them in its logic. Instead of writing a method that always prints the same thing or always returns the same result, we can design it to respond to the input we give it. This makes our code even more reusable and useful.

3. sayHello(String name)

Let's go back to our `sayHello()` method. Right now, it just prints a hardcoded, or predefined, message. But what if we want it to greet different people by name? We can update it to take a String parameter - for example, `sayHello(String name)`. Inside the method, we can use the name parameter to build a personalized message, like `"Hello, Alice!"` or `"Hello, Sam!"` depending on what we pass in.

4. getSquare(int number)

The same idea applies to our `getSquare()` method. Before, it didn't take any input - it just returned the square of the hard-coded number 5. Now, we can give it an `int` parameter, like `getSquare(int number)`, and return `number times number`. This way, we can reuse the same method with different inputs and get different results each time.

5. Calling methods with parameters

When we call methods with parameters, we pass the values inside the parentheses. For example, we'd call `sayHello("Alice")` or `getSquare(2)`, and the method would use the value we passed in.

6. More parameters - of any type

We can add as many parameters as we want, all of them can be of different types. Here is an example of a method for printing user details and a method for adding two numbers together.

7. Recap

Adding parameters makes our methods much more powerful and flexible. Instead of writing multiple versions of the same method for different inputs, we just write it once and let the parameter handle the variation.

8. Let's practice!

Next, you'll update our greeting method so that it takes a name, and build a calculator method that accepts two numbers and multiplies them together. Let's give it a try!