Saturday, 19 September 2015

Java Tutorial : Java Parameters

Master Core Java Concepts!

Subscribe to Ram N Java for clear explanations, practical code examples, and essential Java tutorials!

Subscribe Now on YouTube

What Are Parameters in Java?

In Java, parameters are variables defined in a method or constructor declaration. They act as placeholders that receive values (called arguments) passed by the caller when the method is invoked.

An important distinction in Java terminology is that parameters are always classified as variables, not fields. They are scoped strictly to the execution of the method or constructor in which they appear.

Defining Methods with Parameters

When a method needs input data from the outside world to perform its calculations or operations, you declare parameters within the parentheses following the method name:

class Student {
  // Method declaring two parameters: marksScoredInScience and marksScoredInEnglish
  public int getTotalMarks(int marksScoredInScience, int marksScoredInEnglish) {
    int totalMarks = marksScoredInScience + marksScoredInEnglish;
    return totalMarks;
  }
}

Passing Arguments and Receiving Results

In the driver program, when getTotalMarks(50, 40) is called, the values 50 and 40 are passed as arguments to the corresponding parameters:

public class StudentDemo {
  public static void main(String[] args) {
    Student student = new Student();

    // Calling method and passing arguments (50, 40)
    int totalMarks = student.getTotalMarks(50, 40);

    System.out.println("Total marks: " + totalMarks);
  }
}

// Output:
// Total marks: 90

Key Takeaways

✔️ Variables, Not Fields: Parameters belong strictly to the method or constructor signature, not class fields.

✔️ Dynamic Inputs: Allow methods to perform dynamic calculations based on the arguments supplied by the caller.

✔️ Scope: Exist only during the method execution and go out of scope once the method returns.


Watch More Java Tutorials:

No comments:

Post a Comment

Tutorials