Designing Methods Vocabulary

Method Declaration Structure and Syntax

  • Definition of Method Declaration: A method declaration specifies all the information required to call a method in Java.

  • Components of a Method Declaration:

    • Access Modifier: Specifies the visibility and access level of the method (e.g., public). Optional.

    • Optional Specifier: Provides additional behavior or constraints for the method (e.g., final). Optional.

    • Return Type: The data type of the value returned by the method, or void if the method does not return any value. Required.

    • Method Name: The identifier used to call the method (e.g., nap). Required.

    • Parameter List: A comma-delimited list of input parameters preceded by their data types and enclosed in parentheses (). Required, but can be empty (). Example: (int minutes).

    • Optional Exception List: Indicates that the method might throw one or more specified exception types using the throws keyword (e.g., throws Exception). Optional.

    • Method Body: Everything enclosed between opening and closing curly braces {} containing the executable code and local variable declarations. Required, but can be empty {}.

  • Comprehensive Method Declaration Example:

  public final void nap(int minutes) throws Exception {
      // statements
  }
  ```

- **Summary Table of Declaration Elements**:
  - **Access modifier**: Example value `public` | Required: No
  - **Optional specifier**: Example value `final` | Required: No
  - **Return type**: Example value `void` | Required: Yes
  - **Method name**: Example value `nap` | Required: Yes
  - **Parameter list**: Example value `(int minutes)` | Required: Yes, but can be empty `()`
  - **Optional exception list**: Example value `throws Exception` | Required: No
  - **Method body**: Example value `{ //statements }` | Required: Yes, but can be empty `{}`

- **Method Invocation Syntax**:
  - To call a method, type its name followed by the argument values enclosed in parentheses.
  - Calling example for `nap`: `nap(15);` (passes a single integer argument of `1515`).

- **Method Naming Conventions**:
  - Single-word names must be a verb written in lowercase (e.g., `run`).
  - Multi-word names must begin with a verb in lowercase, followed by adjectives, nouns, or other words using camelCase syntax where subsequent words start with capital letters (e.g., `runFast`).


# Java Access Modifiers and Optional Specifiers

- **Access Control Levels**:
  - Access modifiers determine whether other classes can access a particular field or invoke a specific method.
  - Java provides two (22) distinct levels of access control:
    - **Top Level**: Can be either `public` or `package-private` (no modifier).
    - **Member Level**: Can be `public`, `private`, `protected`, or `package-private` (no modifier).

- **The Four Access Modifiers**:
  - **`public`**: Allows the method or field to be visible and accessible to all classes across all packages everywhere.
  - **`private`**: Specifies that the member can only be accessed within the exact class in which it is declared.
  - **`protected`**: Specifies that the member can only be accessed within its own package, as well as by subclasses located in different packages.
  - **`package-private` (no modifier)**: Declared by omitting any modifier keyword. Specifies that the member can only be accessed within its own package.

- **Common Optional Specifiers**:
  - **`static`**: Used to designate class methods and class variables rather than instance members.
  - **`abstract`**: Used when declaring a method signature that does not contain a body implementation.
  - **`final`**: Used to declare that a method cannot be overridden by any subclass.


# Static Fields and Static Methods

- **Static Variables (Class Variables)**:
  - A static variable or class variable is any field declared with the `static` modifier.
  - The `static` modifier informs the compiler that exactly one (11) copy of this variable exists in memory, regardless of how many times the class is instantiated.
  - All instances of the class share the exact same static variable.

- **Static Variable Code Example**:

java public class StaticVarDemo { static int count = 0;

  public void increment() {
      count++;
  }

  public static void main(String args[]) {
      StaticVarDemo obj1 = new StaticVarDemo();
      StaticVarDemo obj2 = new StaticVarDemo();

      obj1.increment();
      System.out.println("Obj1: count = " + obj1.count);

      obj2.increment();
      System.out.println("Obj1: count = " + obj1.count);
      System.out.println("Obj2: count = " + obj2.count);
  }

}   ```

  • Execution Output:

    • Obj1: count = 1

    • Obj1: count = 2

    • Obj2: count = 2

  • Detailed Analysis: count is a static variable initialized to 00, and increment() increments count by 11. In main(), two (22) objects are instantiated: obj1 and obj2. When obj1 invokes increment(), count becomes 11. When obj2 subsequently invokes increment(), count becomes 22. Printing obj1.count and obj2.count both produce 22 because only a single shared copy of count exists across all instances.

    • Static Methods:

  • A static method belongs to the class itself rather than to any specific instance of the class.

  • It can be invoked directly without creating an instance of the class.

  • It can access static members of the class and modify their values.

    • Main Purposes of Static Methods:

  • Utility or Helper Methods: Designed for methods that do not rely on or require any object state. Using static methods eliminates the overhead of instantiating an object merely to call a routine.

  • Shared State Access: For managing state shared across all instances of a class (such as a global counter). Methods that interact strictly with this shared state should also be static.

    • Static Member Calling Syntax:

  • Static methods and static variables should be called by prefixing the member name with the class name (ClassName.memberName).

  • Example of Static Invocation: ```java class NumberClass { public static int num = 0; public static void displayNumber() { System.out.print(num); } }

    public class NumberClassDemo { public static void main(String[] args) { System.out.print(NumberClass.num); NumberClass.displayNumber(); } }     ```

  • Output: 00

    • Accessing Static Members via Class Instances:

  • An instance of an object can also be used to call a static method or modify a static variable, though it alters the single class-wide value.

  • Example of Instance Modification of Static Variable: ```java public class NumberClass { public static int num = 0;

    public static void main(String[] args) {
        NumberClass.num = 4;
        NumberClass nc1 = new NumberClass();
        NumberClass nc2 = new NumberClass();
    nc1.num = 6;
    nc2.num = 5;
    System.out.print(NumberClass.num);
    

    }

    }
        ```

  • Output: 5

  • Detailed Analysis: Because num is a static variable, setting NumberClass.num = 4, then nc1.num = 6, and finally nc2.num = 5 overwrites the single variable in memory. The final printed value of NumberClass.num is 55.

Information Passing and Pass-by-Value Mechanics

  • Parameters vs. Arguments:

    • Parameters: The variables declared in the method signature or header.

    • Example parameter list in method declaration: public double computeSalePrice(double origPrice, double discountRate) { }

    • Arguments: The actual concrete values passed into the method when it is called.

    • Example argument invocation: computeSalePrice(37.50, 0.15) where 37.5037.50 and 0.150.15 are arguments.

  • Pass-by-Value Principles:

    • Java is strictly a pass-by-value language.

    • When an argument is passed to a method, a copy of the argument's variable is created, and the method operates exclusively on that copy.

    • Changes made to parameter variables inside the method body do not affect the original variables in the calling environment.

  • Pass-by-Value Code Example:

  public static void main(String[] args) {
      int num = 1;
      newNumber(2);
      System.out.println(num);
  }

  public static void newNumber(int num) {
      num = 3;
  }
  ```
  - **Output**: `1`
  - **Detailed Analysis**: In `main()`, `num` is initialized to 11. When `newNumber(2)` is invoked, the argument 22 is copied into `newNumber`'s local parameter `num`. Setting `num = 3` inside `newNumber` only modifies the local parameter copy. The variable `num` in `main()` remains unchanged at 11.


# Method Overloading and Signature Rules

- **Method Signatures**:
  - A method signature is uniquely defined by the method's name together with its ordered parameter types.
  - Example: For `public double computeSalePrice(double origPrice, double discountRate)`, the method signature is `computeSalePrice(double, double)`.

- **Method Overloading Definition**:
  - Method overloading occurs when multiple methods in the same class share the exact same method name but possess different method signatures (i.e., different parameter list types or numbers of parameters).
  - Overloaded methods are differentiated by the compiler based on the number, sequence, and data types of arguments passed into them.

- **Valid Overloading Example**:

java
public void draw(String s) { }
public void draw(int i) { }
public void draw(int i, double f) { }
  ```

  • Valid invocation calls:

    • draw("Circle"); -> matches draw(String)

    • draw(10); -> matches draw(int)

    • draw(10, 5.0); -> matches draw(int, double)

    • Overloading Compilation Restrictions:

  • You cannot declare more than one (11) method with the same name and identical parameter counts and types.

  • You cannot declare two (22) methods with identical signatures even if they specify different return types. Return type alone is insufficient to overload a method.

  • Invalid Code Example (Does Not Compile):
    java
    public void draw(int i) { }
    public int draw(int i) { } // Compilation Error: duplicate method signature
        

Autoboxing in Method Overloading

  • Autoboxing Definition:

    • Autoboxing is the automatic conversion that the Java compiler performs between primitive data types and their corresponding object wrapper classes (e.g., converting int to Integer, or double to Double).

  • Autoboxing Resolution Rules in Method Calling:

    • Rule 1 (Primitive Type Absent): When a primitive parameter version of an overloaded method is not present, Java automatically performs autoboxing to bind to the object wrapper version.
      ```java cascade
      public void draw(Integer i) {
      System.out.print("Integer");
      }

    // Calling statement:
    draw(10);
        ```

    • Output: Integer

    • Rule 2 (Primitive Type Present): When an exact primitive parameter version is present alongside a wrapper version, Java selects the primitive parameter method directly and does not perform autoboxing.
      ```java
      public void draw(Integer i) {
      System.out.print("Integer");
      }

    public void draw(int i) {
    System.out.print("int");
    }

    // Calling statement:
    draw(10);
        ```

    • Output: int









Method Declaration Structure & Syntax
  • Method Declaration Components:

    • Access Modifier (Optional): Visibility (public, private, protected, package-private).

    • Optional Specifier (Optional): Extra constraints (final, static, abstract).

    • Return Type (Required): Data type returned, or void if none.

    • Method Name (Required): Identifier (e.g., nap).

    • Parameter List (Required): Input types & names in (); can be empty ().

    • Optional Exception List (Optional): Exceptions thrown via throws keyword.

    • Method Body (Required): Code inside {}; can be empty {}.

  • Declaration & Invocation Example:

  public final void nap(int minutes) throws Exception {
      // statements
  }
  • Invocation Call: nap(15);

    • Naming Conventions:

  • Single-word: Lowercase verb (e.g., run).

  • Multi-word: camelCase starting with lowercase verb (e.g., runFast).

Access Modifiers & Optional Specifiers
  • Access Control Levels:

    • Top Level: public, package-private.

    • Member Level: public, private, protected, package-private.

  • The Four Access Modifiers:

    • public: Accessible everywhere.

    • private: Accessible only inside declared class.

    • protected: Accessible in package and subclasses in other packages.

    • package-private (Default): Accessible only within same package.

  • Common Optional Specifiers:

    • static: Belongs to class (shared state), not instances.

    • abstract: Method signature without body implementation.

    • final: Prevents method overriding by subclasses.

Static Fields and Methods
  • Static Variables (Class Variables):

    • Declared with static; exactly one (11) copy shared across all instances.

  • Static Variable Example:

  public class StaticVarDemo {
      static int count = 0;

      public void increment() {
          count++;
      }

      public static void main(String args[]) {
          StaticVarDemo obj1 = new StaticVarDemo();
          StaticVarDemo obj2 = new StaticVarDemo();

          obj1.increment();
          System.out.println("Obj1: count = " + obj1.count);

          obj2.increment();
          System.out.println("Obj1: count = " + obj1.count);
          System.out.println("Obj2: count = " + obj2.count);
      }
  }
  • Output:

    • Obj1: count = 1

    • Obj1: count = 2

    • Obj2: count = 2

    • Static Methods:

  • Invoked directly via class (ClassName.methodName()).

  • Used for utility routines or managing shared class state.

    • Instance Modification Example:

  public class NumberClass {
      public static int num = 0;

      public static void main(String[] args) {
          NumberClass.num = 4;
          NumberClass nc1 = new NumberClass();
          NumberClass nc2 = new NumberClass();
          nc1.num = 6;
          nc2.num = 5;
          System.out.print(NumberClass.num);
      }
  }
  • Output: 5

Information Passing (Pass-by-Value)
  • Parameter vs. Argument:

    • Parameter: Declared variable in method header (e.g., double origPrice).

    • Argument: Concrete value passed during invocation (e.g., 37.5037.50).

  • Pass-by-Value Principle:

    • Java strictly passes copies of arguments. Modifying local parameters does not alter caller variables.

  • Pass-by-Value Example:

    ```java

    public static void main(String[] args