6️⃣

11.6 Method Parameters

 
Method parameters allow you to customize the behavior of your function. They are variables that you can use inside of the method body. (They are the things inside of the parentheses in your method signature.)
 
For example, let’s say I have a method called scoopIceCream(). I want to be able to use my method to scoop ice cream for any flavor, so to generalize its behavior I can declare it like so:
public static void scoopIceCream (String flavor) { System.out.println("Here's a scoop of " + flavor + " ice cream!"); }
 
flavor is a parameter of the scoopIceCream() method. Depending on the argument I pass into the flavor parameter, the scoopIceCream() method will print a slightly different message. However, the fundamental part of the method is the same - it will always print a message related to scooping ice cream.
 
Also notice that I must declare the type of the parameter before the parameter’s name. In this case, flavor is of type String.
 
Here is an example of calling the scoopIceCream() method with different arguments.
public static void main(String[] args) { scoopIceCream("chocolate"); scoopIceCream("vanilla"); scoopIceCream("strawberry"); }
 
Output of the code above:
Here's a scoop of chocolate ice cream! Here's a scoop of vanilla ice cream! Here's a scoop of strawberry ice cream!
 
You can also have a method that takes multiple parameters. You just need to separate parameters with commas, like so (pay attention to highlighted code):
public static void main(String[] args) { // scoopIceCream with multiple parameters scoopIceCream("chocolate", true); scoopIceCream("vanilla", false); scoopIceCream("strawberry", true); } public static void scoopIceCream(String flavor, boolean wantCone) { if (wantCone) { System.out.println( "Here's a scoop of " + flavor + " ice cream on a cone!" ); } else { System.out.println("Here's a scoop of " + flavor + " ice cream!"); } }
 
Output of the code above:
Here's a scoop of chocolate ice cream on a cone! Here's a scoop of vanilla ice cream! Here's a scoop of strawberry ice cream on a cone
 
 
⚖️
Copyright © 2021 Code 4 Tomorrow. All rights reserved. The code in this course is licensed under the MIT License. If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact classes@code4tomorrow.org for inquiries.