■ Java Reviewer (Definitions with Examples)
1. Designing Methods
Definition: A method is a block of code that performs a specific task and can be called when
needed.
Parts of a Method Declaration:
- Access modifier: Defines visibility (public, private, protected).
- Return type: Type of data returned (or void if none).
- Method name: Identifier for the method (e.g., runFast).
- Parameters: Input values inside parentheses.
- Method body: Code enclosed in { }.
Example:
public int add(int a, int b) { return a + b; }
Call: add(5, 3); // returns 8
Access Modifiers:
- public: Accessible anywhere.
- private: Accessible only inside the class.
- protected: Accessible in same package + subclasses.
- package-private: Accessible only within the package.
Example:
public void show() { } → Accessible everywhere.
private void hide() { } → Only in same class.
2. Static Methods and Fields
Static Variable Definition: A variable shared by all objects of a class (only one copy exists).
Example:
class Demo { static int count = 0; }
Every object of Demo shares the same count variable.
Static Method Definition: A method that belongs to the class, not an instance.
- Can be called without creating an object.
Example:
class MathUtil {
public static int square(int n) { return n * n; }
}
Call: [Link](4); // returns 16
Static vs Instance:
- Static methods/variables → accessed using class name.
- Instance methods/variables → need an object.
Example:
Demo d = new Demo();
[Link](); // needs object
[Link](); // no object needed
3. Method Overloading
Definition: Having multiple methods with the same name but different parameter lists.
Example:
void print(String s) { [Link](s); }
void print(int n) { [Link](n); }
print("Hello"); // calls first method
print(10); // calls second method
Pass-by-Value:
Java always passes a copy of the value to methods.
Example:
void change(int x) { x = 10; }
int num = 5;
change(num);
[Link](num); // still 5
Autoboxing:
Automatic conversion between primitive and wrapper class.
Example:
Integer i = 5; // int automatically boxed to Integer
If both primitive and wrapper methods exist, primitive is chosen first.