Arguments and Parameters:
Arguments: Values passed to a method when it is called.
Parameters: Variables within the method that receive arguments.
Parameter Declaration:
Declared within parentheses after the method name.
They have the same declaration syntax as normal variables.
They are local to the method and have the task of receiving arguments.
Simple Example with Parameter:
class ChkNum { boolean isEven(int x) { return (x % 2) == 0; } }
Method isEven(int x) returns true if the passed value is even, false otherwise.
class ParmDemo { public static void main(String args[]) { ChkNum e = new ChkNum(); if(e.isEven(10)) System.out.println("10 is even."); if(e.isEven(9)) System.out.println("9 is even."); if(e.isEven(8)) System.out.println("8 is even."); } }
The method is called with different values and the argument is passed in parentheses.
Multiple Parameters:
A method can have more than one parameter, separated by commas.
See class Factor.java from the book
public class IsFact { public static void main(String args[]) { Factor x = new Factor(); if(x.isFactor(2, 20)) System.out.println("2 is factor"); if(x.isFactor(3, 20)) System.out.println("this won't be displayed"); } }
Different Types of Parameters:
Parameters can have different types and are specified individually.
int myMeth(int a, double b, float c) { // ...
This summary covers the main points about using parameters in methods, including syntax and practical examples with the isEven() and isFactor() method.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3