Java Programming Fundamentals: Constructors, Recursion, Access Specifiers, and More

Java Programming Fundamentals

Constructors

Constructors are special methods used to initialize objects of a class when created using the new keyword. They share the class name and have no return type.

Example:

class Student {
Student(int a, String n, double d) {
usn = a; name = n; score = d;
}}

Types of Constructors:

Default Constructor:

Automatically provided by Java if no constructor is explicitly defined. Initializes objects with default values.

Parameterized Constructor:

Allows object initialization with specific values passed as arguments during creation.

Recursion

Recursion is a technique where a method calls itself to solve a problem, like calculating Fibonacci numbers.

Example:

public class Fibonacci {
public static int fibonacci(int n) {
if (n <= 1) {
return n; // Base case
} else {
return fibonacci(n - 1) + fibonacci(n - 2); // Recursive case
}}
}

Access Specifiers

Keywords that define the accessibility of classes, variables, methods, and constructors.

  • public: Accessible from any class.
  • private: Accessible only within the same class.
  • protected: Accessible within the same package and by subclasses.
  • default: Accessible only within the same package.

Accessibility order: public > protected > default > private

Call by Value and Call by Reference

Call by Value: A copy of the actual parameter’s value is passed to the method. Changes inside the method do not affect the original variable.

Call by Reference: A reference to the memory location of the actual parameter is passed. Changes inside the method affect the original variable.

this Keyword

Refers to the current instance of the class. Used within instance methods and constructors.

Uses:

  • Referencing instance variables
  • Calling another constructor
  • Passing the current object as a parameter
  • Returning the current object

Memory Allocation and Garbage Collection

Java objects are allocated memory on the heap. Garbage collection automatically reclaims memory from unused objects.

Static Variables and Methods

Static Variable: Belongs to the class, not to any specific instance. Only one copy exists per class.

Static Method: Belongs to the class. Can be called directly using the class name.