Home > Java > javaTutorial > Using parameters

Using parameters

WBOY
Release: 2024-07-28 07:58:02
Original
860 people have browsed it

Usando parâmetros

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:

  • ChkNum Class Example:
class ChkNum {
    boolean isEven(int x) {
        return (x % 2) == 0;
    }
}

Copy after login

Method isEven(int x) returns true if the passed value is even, false otherwise.

  • Example of Using the isEven Method: The ParmDemo class demonstrates the use of the isEven method.
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.");
    }
}

Copy after login

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.

  • Example with Multiple Parameters: Factor Class: Method isFactor(int a, int b) checks whether a is a factor of b. Usage of the isFactor Method: Arguments are passed 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");
    }
}
Copy after login

Different Types of Parameters:

Parameters can have different types and are specified individually.

int myMeth(int a, double b, float c) {
// ...
Copy after login

This summary covers the main points about using parameters in methods, including the syntax and practical examples with the isEven() and isFactor() method.

The above is the detailed content of Using parameters. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template