Immutable Objects, Variable Scope, and Recursion 1. Immutable Objects and Their Effect On Passing by Reference
Immutable Objects, Variable Scope, and Recursion 1. Immutable Objects and Their Effect On Passing by Reference
Example:
public void changeString(String str) {
str = "New Value";
}
Calling changeString(myStr); will not change the value of myStr outside the method.
This gives immutability a strong role in maintaining predictable, side-effect-free
code, especially in concurrent applications where multiple threads may access the
same object.
In contrast, mutable objects (like arrays or user-defined classes) allow their fields to
be changed even when passed by reference. Developers must be careful with
mutable objects to avoid unintended side effects.
1
- Block Scope: Variables declared inside loops, if statements, or other code blocks
are only accessible within those blocks.
Example:
public class Example {
int classLevel = 10; // Class scope
3. Recursion
Recursion is a programming technique where a method calls itself to solve a
problem. Each recursive call breaks the problem into smaller subproblems until a
base case is reached, which halts further recursive calls.
While recursion simplifies the logic for problems like tree traversal, Fibonacci
series, and backtracking algorithms, it can lead to stack overflow if not implemented
carefully. It's essential to define a base case and ensure it will eventually be met.