KTU OOP Java2024 Scheme • 60M ESE
MODULE 1/Section 1: Introduction to Java

Functions/Methods, Command-Line Arguments & Varargs (Variable-Length Arguments)

HIGH PRIORITY (Prep Guide)Official Syllabus~15 min study
Official KTU 2024 Syllabus Topics Covered Here
Functions and methodsCommand-line argumentsVariable-length arguments (varargs)
Java Version Note: Variable-length arguments (Varargs) were introduced in JDK 5 (Java 5), allowing a variable-arity parameter using ellipsis (...) syntax.

1. Topic Introduction

Breaking code into reusable methods keeps programs modular. Java also provides two flexible ways to pass input into methods: Command-Line Arguments (passing startup data into main from the terminal) and Varargs (letting any method accept zero, one, or many arguments of the same type without manually creating an array).

2. Start From Zero: Order Slip at Launch (args) vs Flexible Buffet Plate (varargs)

Command-Line Arguments are instructions written right beside the program launch command (java BillCalc 100 50)—Java automatically packs "100" and "50" into args[0] and args[1] inside main. **Varargs (int... nums)** is a flexible buffet plate: whether you pass sum(), sum(5), or sum(1, 2, 3, 4), Java quietly packs your items into an int[] array inside the method!

Key Takeaway: CLI arguments arrive as String[] args in main (convert with Integer.parseInt). Varargs (type... name) compiles into an array, MUST be the LAST parameter, and at most ONE varargs parameter is allowed per method.

3. Essential Exam Definitions

Method (Function in OOP)
A named block of code declared inside a class that defines an object's behavior, accepting zero or more parameters and optionally returning a value.
Command-Line Arguments
Space-separated tokens passed immediately after the class name when launching a program (java MyApp arg1 arg2), stored automatically as Strings in main(String[] args).
Varargs (Variable-Arity Method)
A method parameter declared with ellipsis (type... name) enabling the method to receive zero or more arguments of that type, treated internally as a standard array.

4. Detailed Technical Explanation & Syntax

1. Methods in Java: Syntax & Invocation

In procedural C, standalone subroutines are called 'functions'. Because Java forbids code outside classes, all functions belong to a class and are called methods.

Syntax: [modifiers] returnType methodName(paramList) { body }.

A static method belongs to the class (Math.sqrt(25) or helper() directly inside the same class), whereas an instance (non-static) method requires an object reference (obj.display()).

2. Command-Line Arguments (String[] args)

When you execute java SumArgs 15 25, Java sets args.length = 2, args[0] = "15", and args[1] = "25".

Notice: Unlike C's argv[0] (which stores the program name), in Java args[0] is ALWAYS the first actual argument, NOT the class name! Because all CLI arguments arrive as String, numeric math requires parsing via Integer.parseInt(args[0]) or Double.parseDouble(args[1]).

3. Varargs Rules, Overloading & Ambiguity Pitfalls

Prior to JDK 5, handling an unknown count of arguments required either writing multiple overloaded methods or manually constructing an array. Varargs (void vaTest(int... v)) solves this cleanly.

  • Rule 1: Inside the method, v is literally an array (v.length, for (int x : v) work identically).
  • Rule 2: A method may combine normal parameters with varargs, PROVIDED the varargs parameter is LAST: void log(String tag, int... ids) is valid; void bad(int... ids, String tag) is a COMPILE ERROR.
  • Rule 3: Only ONE varargs parameter is permitted per method (void bad(int... a, double... b) is illegal).
  • Overloading Varargs: You can overload vaTest(int... v) with vaTest(boolean... v) or a fixed method vaTest(int x) (Java matches exact non-varargs first when 1 int is passed!).
  • Ambiguity Trap 1: Calling vaTest() with ZERO arguments when BOTH vaTest(int... v) and vaTest(boolean... v) exist causes a COMPILE ERROR (ambiguous call!).
  • Ambiguity Trap 2: Overloading vaTest(int... v) with vaTest(int a, int... v) makes vaTest(10) ambiguous!

5. Working Principle: How Varargs Resolution & CLI Parsing Execute

  1. At compile time, javac converts sum(10, 20, 30) into sum(new int[]{10, 20, 30}) and sum() into sum(new int[0]).
  2. If an exact non-varargs overload matches (sum(int x) for sum(10)), Java picks the exact match over varargs (sum(int... v)).

7. Complete Java Code Examples & Tracing

Methods, Safe Command-Line Arguments & Varargs OverloadingVarargsAndCliDemo.java
Demonstrates checking args.length, combining normal + varargs parameters, exact-match preference over varargs, and varargs traversal.
1public class VarargsAndCliDemo {
2 // 1. Normal parameter followed by varargs (must be last!)
3 static void printScores(String subject, int... scores) {
4 int sum = 0;
5 for (int s : scores) { // scores behaves as int[]
6 sum += s;
7 }
8 System.out.println(subject + " -> count: " + scores.length + ", sum: " + sum);
9 }
10
11 // 2. Overloading varargs with exact 1-arg non-varargs method
12 static void test(int x) {
13 System.out.println("Exact match test(int): " + x);
14 }
15
16 static void test(int... v) {
17 System.out.println("Varargs test(int...) count: " + v.length);
18 }
19
20 public static void main(String[] args) {
21 // Safe CLI argument check (works even with 0 CLI args)
22 if (args.length >= 2) {
23 int n1 = Integer.parseInt(args[0]);
24 int n2 = Integer.parseInt(args[1]);
25 System.out.println("CLI Sum: " + (n1 + n2));
26 } else {
27 System.out.println("CLI Args passed: " + args.length);
28 }
29
30 printScores("OOP", 55, 58, 60);
31 printScores("Empty"); // 0 varargs passed -> scores.length is 0
32
33 test(42); // Prefers exact non-varargs test(int)
34 test(1, 2, 3); // Calls varargs test(int...)
35 }
36}
Expected Output
CLI Args passed: 0
OOP -> count: 3, sum: 173
Empty -> count: 0, sum: 0
Exact match test(int): 42
Varargs test(int...) count: 3
Keywords:staticString[] args...Integer.parseInt
Common Exam & Coding Mistakes
  • Placing varargs before a regular parameter: void f(int... a, String b) (illegal!).
  • Declaring two varargs parameters in one method.
  • Assuming args[0] holds the Java program's class name like C's argv[0].

Real-World Applications

  • System.out.printf(String format, Object... args) in Java's own standard library uses varargs.
  • CLI utilities accept configuration flags and file paths via String[] args.

Important KTU Exam Points

  • Always state the 3 golden rules of Varargs: (1) uses ..., (2) must be the LAST parameter, (3) only ONE varargs per method.
  • Know a clear Varargs Ambiguity example (vaTest() when both vaTest(int...) and vaTest(boolean...) exist).
  • In CLI programs, remember args[0] is the FIRST argument (NOT program name), and Integer.parseInt() converts strings to integers.

Memory Techniques & Revision

  • Varargs = 'Last & Lonely': Must be LAST parameter, and ONLY ONE allowed.

Common Pitfalls to Avoid

  • Writing int ...v or int... v? Both compile, though int... v is standard readable convention.
  • Forgetting ArrayIndexOutOfBoundsException if user runs program without expected CLI args.

KTU-Style Questions & Exam-Ready Answers

Structured specifically for KTU Part A (3-mark) and Part B (6/9-mark) evaluation rubrics.

Introduction: Varargs (variable-length arguments), introduced in JDK 5, simplify defining methods that accept zero or more arguments of the same type using ... syntax.

  • Internal Working: void show(int... v) compiles v as an implicit int[] array.
  • Rules: (1) Varargs must be the LAST parameter if combined with normal parameters (void m(String s, int... v)); (2) Only ONE varargs parameter is allowed per method.
  • Ambiguity Pitfall: Overloading vaTest(int... v) and vaTest(boolean... v) compiles, but calling vaTest() with zero arguments causes an ambiguous call compile error because both match an empty argument list.
static int sum(int... nums) {
int total = 0;
for (int x : nums) total += x;
return total;
}

Quick Understanding Check

1. When running java Demo alpha beta, what is stored in args[0]?

2. Which method header is INVALID in Java?