Methods of Java · Introduction to Java Programming

Passing Primitive Data Types to Methods

Watch lectures

Passing Primitive Data Types to Methods

1. Rule in One Line (beginner)

Primitives pass by value (photocopy!). Method gets a copy — changes die with method. Original NEVER changes!

2. Proof Code (exam trace!)

static void addOne(int x) { x = x + 1; } // edits COPY!
public static void main(String[] args) {
    int n = 10;
    addOne(n);
    System.out.println(n); // still 10! (original untouched!)
}

Swap fails too:

static void swap(int a, int b) { int t = a; a = b; b = t; } // copies swap, originals don't!
int x = 1, y = 2; swap(x, y); // x=1,y=2 still! (classic trap!)
main: n=10 → copy x=10 → x=11 (method) → die! → n still 10

Objects/arrays differ (address copy — shared! next topics!).

5. Exam Points

  • Trace (n unchanged) + failed swap — 5-7 marks, very frequent.
  • By-value diagram + fix — 3 marks, frequent.
Student FinanceWeb Platform

Pocketly — Personal Finance for Students

Keep your hostel and college expenses under control. Track accounts, log spending in seconds, and stay within your monthly budget.

← All Introduction to Java Programming modules