Primitive parameters
- Java course
- Beginner
- Lesson 77/116
- 4 min
Learn to pass primitive parameters.
Primitive type parameters
When you pass primitive types (int, double, boolean...) as method parameters, a copy of the value goes into the method. This is called pass by value.
static void doubleIt(int x) {
x = x * 2;
}
int n = 5;
doubleIt(n);
// n is still 5Even if you change x inside the method, the original n is not affected. Because x is a separate copy of n. This behavior prevents unexpected side effects.
Consequence of pass by value
A method with a primitive parameter cannot change the caller's variable. This makes code easier to follow: knowing what the method does is enough; it will not break the outside.
static void zero(int v) {
v = 0;
}
int n = 9;
zero(n);
System.out.println(n);
// prints 9If you want a method to change an outside value, you must either pass an array or object, or use the return value. With a primitive, this is not possible.
Practice Square root approximation
Define a static double method called approxSqrt; parameter int n, body return Math.sqrt(n);. Call approxSqrt(16) from main and print the result.
Starter code
public class Main {
public static void main(String[] args) {
// Call the method with 16 and print the result
}
// Define the approxSqrt method here
}Sample solution
static double approxSqrt(int n) {
return Math.sqrt(n);
}
// inside main:
System.out.println(approxSqrt(16));Expected output
4.0
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match type to example
| Term | Meaning |
|---|---|
int |
42 |
double |
3.14 |
boolean |
true |
char |
'A' |
2 Fill in the blank: primitive parameter
static void half(____ x) {
System.out.println(x / 2);
}
static void half(int x) {
System.out.println(x / 2);
}
Explanation: int is a primitive type; a copy is passed as parameter.
3 What is the value of n after calling doubleIt(n)?
static void doubleIt(int x) {
x = x * 2;
}
int n = 5;
doubleIt(n);- It doubles
- It stays the same (pass by value) Correct answer
- It is zeroed
- It throws an error
Explanation: The copy of the primitive parameter changes; the original is untouched.