Return Data Types in Java

  • Definition: The return data type specifies the type of value a method will return.
  • Types of Return Data Types:
    • void → No return value
    • Primitive types → int, float, char, etc.
    • Non-primitive types → String, Array, Class Object, etc.
  • Example:
class Example {
      int add(int a, int b) { // Method returning an int
          return a + b;
      }
  }

How to Create Methods

Method Definition

  • A method is a block of code designed to perform a task.
  • Syntax:
returnType methodName(parameters) {
      // Method body
      return value; // (if returnType is not void)
  }
  • Example:
class Example {
      void display() { // Method with no return value
          System.out.println("Hello World");
      }
  }

this Keyword in Java

  • Definition: this refers to the current instance of a class.
  • When to Use this?
    • To differentiate between instance variables and parameters with the same name.
    • To call another constructor in the same class.
    • To return the current class instance.
  • Example:
class Example {
      int num;
      Example(int num) {
          this.num = num; // Using `this` to refer to instance variable
      }
  }
  • When NOT to Use this?
    • In static methods (since static methods belong to the class, not an instance).
    • Outside non-static methods.

Global Elements in Java

Variables

  • Static Variables (shared across all objects, belongs to the class)
class Example {
      static int count = 0;
  }
  • Non-Static Variables (unique to each object)
class Example {
      int id;
  }

Methods

  • Static Methods (can be called without an object)
class Example {
      static void show() {
          System.out.println("Static method");
      }
  }
  • Non-Static Methods (requires an object to be called)
class Example {
      void show() {
          System.out.println("Non-static method");
      }
  }

Why Do We Need Methods?

  • Code Reusability: Avoid repeating code.
  • Modular Structure: Divides the program into smaller, manageable parts.
  • Readability & Maintainability: Improves program clarity and debugging efficiency.

This covers return data types, method creation, this keyword, global variables/methods, and why methods are essential🚀