Java Method Parameters

🔹 Java Method Parameters

Method parameters are values you pass to a method when calling it. They allow methods to receive input and perform operations with dynamic data.


✅ 1. Types of Parameters

  1. No Parameters – The method does not require any input.

  2. Single Parameter – The method accepts one input.

  3. Multiple Parameters – The method accepts two or more inputs.

  4. Variable-Length Parameters (Varargs) – The method accepts any number of arguments of the same type.


✅ 2. Example 1: No Parameters

public class Main {
static void greet() {
System.out.println("Hello! Welcome to Java.");
}

public static void main(String[] args) {
greet(); // Method call without parameters
}
}

📌 Output:

Hello! Welcome to Java.

✅ 3. Example 2: Single Parameter

public class Main {
static void greetUser(String name) {
System.out.println("Hello, " + name + "!");
}

public static void main(String[] args) {
greetUser("Alice");
}
}

📌 Output:

Hello, Alice!

✅ 4. Example 3: Multiple Parameters

public class Main {
static int addNumbers(int a, int b) {
return a + b;
}

public static void main(String[] args) {
int sum = addNumbers(5, 10);
System.out.println("Sum = " + sum);
}
}

📌 Output:

Sum = 15

✅ 5. Example 4: Variable-Length Arguments (Varargs)

public class Main {
static int sumNumbers(int... numbers) {
int sum = 0;
for (int num : numbers) {
sum += num;
}
return sum;
}

public static void main(String[] args) {
System.out.println(sumNumbers(1, 2, 3)); // 6
System.out.println(sumNumbers(10, 20, 30, 40)); // 100
}
}

📌 Notes:

  • int... numbers → Accepts 0 or more integers

  • Varargs must be last parameter if multiple parameters exist


✅ 6. Example 5: Passing Array as Parameter

public class Main {
static int sumArray(int[] arr) {
int sum = 0;
for (int num : arr) {
sum += num;
}
return sum;
}

public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40};
System.out.println("Sum = " + sumArray(numbers));
}
}

📌 Output:

Sum = 100

🧠 Key Points

  • Parameters allow methods to receive dynamic input.

  • Can be of primitive type, objects, arrays, or varargs.

  • Order matters when calling a method with multiple parameters.

  • Varargs provide flexibility for any number of arguments.

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *