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.
Free AppAndroid App

Coursify Android App

Generate AI courses, take quick quizzes between classes, and master complex engineering concepts on the go.

← All Introduction to Java Programming modules