Curriculum
Course: Java Basic
Login

Curriculum

Java Basic

Java Home

0/1

Java Introduction

0/1

Java Get Started

0/1

Java Syntax

0/1

Java Comments

0/1

Java Type Casting

0/1

Java Operators

0/1

Java Booleans

0/1

Java Switch

0/1

Java Break / Continue

0/1

Java Errors and Exception

0/1
Text lesson

Parameters

Parameters and Arguments

Methods in Java can receive information through parameters, which essentially function as variables within the method’s scope.

Parameters are designated within the parentheses following the method name, where you can include multiple parameters, separated by commas.

In the subsequent example, there’s a method that accepts a String parameter named fname. Upon method invocation, we provide a first name, which the method utilizes to print the full name.

Example

public class Main {
  static void myMethod(String fname) {
    System.out.println(fname + " Refsnes");
  }

  public static void main(String[] args) {
    myMethod("Liam");
    myMethod("Jenny");
    myMethod("Anja");
  }
}
// Liam Refsnes
// Jenny Refsnes
// Anja Refsnes

 

In the example above, fname represents a parameter, while LiamJenny, and Anja are considered arguments when passed to the method.

Multiple Parameters

You can include any number of parameters according to your requirements.

Example

public class Main {
  static void myMethod(String fname, int age) {
    System.out.println(fname + " is " + age);
  }

  public static void main(String[] args) {
    myMethod("Liam", 5);
    myMethod("Jenny", 8);
    myMethod("Anja", 31);
  }
}

// Liam is 5
// Jenny is 8
// Anja is 31

 

It’s important to note that when dealing with multiple parameters, the method call should provide an equal number of arguments as there are parameters, and these arguments must be supplied in the same order as the parameters.

A Method with If…Else

It’s a common practice to incorporate if…else statements within methods.

Example

public class Main {

  // Create a checkAge() method with an integer variable called age
  static void checkAge(int age) {

    // If age is less than 18, print "access denied"
    if (age < 18) {
      System.out.println("Access denied - You are not old enough!");

    // If age is greater than, or equal to, 18, print "access granted"
    } else {
      System.out.println("Access granted - You are old enough!");
    }

  }

  public static void main(String[] args) {
    checkAge(20); // Call the checkAge method and pass along an age of 20
  }
}

// Outputs "Access granted - You are old enough!"