chapter 6 but shorter Flashcards
(19 cards)
What is a method in Java?
A collection of statements grouped together to perform an operation.
Why use methods?
✅ Improves code readability
✅ Supports modular programming
✅ Reduces redundancy by reusing code
What is a static method?
A method that belongs to a class rather than an object (e.g., Math.sqrt(x)
).
What are the components of a method definition?
✅ Modifiers (e.g., public
, static
)
✅ Return type (e.g., void
, int
)
✅ Method name
✅ Parameter list (optional)
✅ Method body
How do you call a method in Java?
By using its name and providing necessary arguments.
What is the difference between an argument and a parameter?
✅ Parameter → A variable inside the method definition.
✅ Argument → The actual value passed when calling the method.
What is the purpose of the return
statement?
It terminates the method and sends a value back to the caller.
Can a method return more than one value?
No, but it can return an array or object to store multiple values.
What is method overloading?
Defining multiple methods with the same name but different parameters.
What is the scope of a local variable in a method?
A local variable exists only within the method where it is declared.
Example of variable scope?
```java
public static void example() {
int x = 10; // x exists only inside this method
}
System.out.println(x); // ERROR: x is out of scope!
~~~
✅ x
cannot be accessed outside example()
.
What happens when a method is called in relation to the stack frame?
✅ Java creates a new stack frame for the method’s variables.
✅ The method executes, then removes the stack frame when done.
Why is the call stack important?
It manages method execution and helps track return values.
Can a method contain loops and conditionals?
Yes, a method can have:
✅ Loops (for
, while
)
✅ Conditionals (if-else
)
How are arguments passed to methods in Java?
Primitive types (e.g., int
, double
) are passed by value.
What happens when an array is passed to a method?
The reference is passed, so the original array can be modified.
Example of passing an array?
```java
public static void modifyArray(int[] arr) {
arr[0] = 99; // Modifies the original array
}
int[] nums = {1, 2, 3};
modifyArray(nums);
System.out.println(nums[0]); // Output: 99
~~~
✅ The actual array is modified because arrays are passed by reference.
What is method abstraction?
Hiding method details while exposing only the necessary parts.
Why should we validate input parameters?
✅ Prevents bugs and incorrect calculations.
✅ Avoids unexpected errors during execution.