Chapter 11: Comprehensive Guide to JVM Data Areas and Object-Oriented Programming (OOP)


Today's Topic of Discussion

In this chapter, we will explore:

  1. Introduction to Object-Oriented Programming (OOP)

  2. Types of Variables in Java:

    • Primitive and Reference Variables

    • Instance, Local, and Static Variables

  3. JVM Data Areas:

    • Method Area

    • Heap Area

    • Stack Area

    • Program Counter (PC) Register

    • Native Method Area


Introduction to Object-Oriented Programming (OOP)

Object-Oriented Programming (OOP) is a theoretical concept that serves as the foundation for many modern programming languages like C++, Java, and Python. OOP simplifies the design and development of software by modeling real-world entities as objects. By following OOP principles, complex problems can be broken down into smaller, more manageable components, making it easier to develop robust and flexible solutions.

  • Class: A class is a blueprint or template for creating objects. It defines the properties (fields) and actions (methods) that the objects of the class will have.

  • Object: An object is an instance of a class. It is created based on the class definition and contains real values for the properties.

When we consider BookMyShow as a software application, it operates within the principles of Object-Oriented Programming (OOP) to solve real-world problems like booking tickets, managing cinema halls, and handling user interactions. Let’s break this down:

Objects in BookMyShow

BookMyShow consists of several objects that represent real-world entities. Some of these include:

  1. Person/User: Represents individuals using the app.

  2. Ticket: Represents the tickets being booked.

  3. Cinema Hall: Represents the location where the movie is being shown.

  4. Chair: Represents individual seats within a cinema hall.

  5. 3D Glasses: Represents accessories required for certain movies.

  6. Screen: Represents the display unit in the cinema hall.

These objects, while physically existing in the real world, are virtually represented in the application as part of the software's design.


Problem Solving in OOP

When solving a problem using OOP, we follow these steps:

  1. Identify the Objects:

    • The first step is to identify the key entities involved in the problem. For BookMyShow, objects include the user, ticket, cinema hall, etc.
  2. Break Each Object into Two Parts:
    Every object consists of:

    • HAS-Part: Represents the information or attributes of the object. This part is stored as variables or fields.

    • DOES-Part: Represents the actions or behaviors of the object. This part is implemented as methods.


HAS-Part and DOES-Part in OOP

  1. HAS-Part:

    • Indicates what the object can hold or its properties.

    • Example for a Student:

      • Attributes: name, age, gender, address.

      • These are represented using variables or identifiers.

  2. DOES-Part:

    • Indicates what the object can do or its behaviors.

    • Example for a Student:

      • Behaviors: play, study, sleep, drink.

      • These are represented using methods.


Example Breakdown

For BookMyShow Objects:

  1. User (Person):

    • HAS-Part:

      • name (e.g., "Rohit"), email, phoneNumber, userID.
    • DOES-Part:

      • login(), searchMovie(), bookTicket().
  2. Ticket:

    • HAS-Part:

      • movieName, seatNumber, time, price.
    • DOES-Part:

      • generateQRCode(), cancel().
  3. Cinema Hall:

    • HAS-Part:

      • hallName, capacity, location.
    • DOES-Part:

      • allocateSeat(), displayMovie().
  4. Chair:

    • HAS-Part:

      • seatNumber, isOccupied, type (recliner/regular).
    • DOES-Part:

      • reserveSeat(), releaseSeat().

OOP Representation

To represent these HAS-Part and DOES-Part in code, we use variables for attributes and methods for behaviors. For example:

class Student {
    // HAS-Part
    String name;
    int age;
    char gender;
    String address;

    // DOES-Part
    void play() {
        System.out.println(name + " is playing.");
    }
    void study() {
        System.out.println(name + " is studying.");
    }
    void sleep() {
        System.out.println(name + " is sleeping.");
    }
    void drink() {
        System.out.println(name + " is drinking.");
    }
}

// Creating an object
Student student = new Student();
student.name = "Rohit";
student.play();

Example:

To represent a student:

  • Attributes: ID, name, age, gender, address.

  • Behaviors: Play, study, drink, sleep.

class Student {
    int id;
    String name;
    int age;
    char gender;
    String address;

    void play() {}
    void study() {}
    void drink() {}
    void sleep() {}
}

// Creating an object
Student student = new Student();

Java Naming Conventions

  1. Class Names:

    • Java developers follow the Pascal Case convention (also called UpperCamelCase) for class names. In Pascal Case, the first letter of each word is capitalized, and there are no spaces or underscores.

    • Example: BufferedReader, FileReader, OutputStream, String.

  2. Method and Variable Names:

    • Java uses Camel Case convention for method and variable names. In Camel Case, the first letter of the first word is lowercase, and the first letter of each subsequent word is capitalized.

    • Example: firstName, toUpperCase(), toLowerCase(), calculateTotalCost(), myVariable.

  3. Variables:

    • Variables (fields) should be written in camel case starting with a lowercase letter.

    • Example: firstName, age, totalAmount.

  4. Constant Names:

    • Constants are written in UPPER_SNAKE_CASE, with all letters uppercase and words separated by underscores.

    • Example: MAX_VALUE, PI.

Object Creation

To create an object of a class in Java, we use the new keyword, which allocates memory for the object in the heap. Here's how it works:

  • Syntax:

      ClassName variableName = new ClassName();
    
  • Explanation:

    • ClassName: The class you're creating an object from (e.g., String, BufferedReader).

    • variableName: The variable name that will hold the reference to the object.

    • new: The keyword that tells the Java Virtual Machine (JVM) to allocate memory for the object in the heap.

Example:

    String myString = new String("Hello, World!");
    BufferedReader reader = new BufferedReader(new FileReader("file.txt"));

JVM and Memory Allocation

  • When you use the new keyword, the JVM dynamically allocates memory for the object in the heap. This is where all objects are stored in Java. The heap is managed by the garbage collector, which frees up memory once objects are no longer in use.

Summary of Conventions and Object Creation

  • Class Names: PascalCase (e.g., BufferedReader, FileReader).

  • Method and Variable Names: camelCase (e.g., firstName, calculateTotal()).

  • Constants: UPPER_SNAKE_CASE (e.g., MAX_VALUE).

  • Object Creation: Use the new keyword to allocate space in the heap for an object.

By following these conventions, Java code becomes more readable and maintainable, allowing developers to quickly understand the purpose and function of different elements in the code.

JVM Architecture

The JVM architecture consists of several memory areas that are used to execute a Java program. Here's a description of each of the major areas:

  1. Method Area:

    • The method area is where class-level data is stored. This includes the class's bytecode, static variables, and metadata. It's shared among all threads and is part of the heap, but it's used to store information about classes, methods, and the constant pool.

    • Key Content:

      • Class metadata (such as runtime representation of the class).

      • Static variables and constants.

      • The bytecode (compiled .class files) of the Java program.

  2. Heap Area:

    • The heap is the area of memory used for dynamic memory allocation. All objects are created in the heap. It is the largest memory area and is used by the garbage collector to manage memory.

    • Key Content:

      • Object instances (e.g., new MyClass() creates an object in the heap).

      • Arrays and other dynamically created objects.

  3. PC Register (Program Counter Register):

    • The PC register holds the address of the next instruction to be executed. Every thread has its own PC register. It keeps track of the program’s execution and ensures that the JVM can jump to the next instruction in the sequence of bytecode.

    • Key Content:

      • The address of the next instruction to execute.
  4. Native Method Area:

    • The Native Method Area contains code that is written in other programming languages (typically C or C++) but needs to be invoked from Java programs. For example, when Java calls native methods using the JNI (Java Native Interface), the native code is stored in this area.

    • Key Content:

      • Native method code (written in languages other than Java, typically for performance reasons).
  5. Stack Area:

    • The stack is used for storing local variables, method calls, and method frames. Each thread has its own stack, which is used to manage the execution of methods, local variables, and the return addresses of method calls.

    • Key Content:

      • Local variables for methods.

      • Method call frames (contains parameters, return address, etc.).

  6. Runtime Constant Pool:

    • The constant pool is part of the method area and contains constants like string literals and other constants that are referenced in the class's bytecode. It allows quick access to values that are constant during execution.

    • Key Content:

      • String literals and other constant data.

JVM Execution Process

When a Java program is executed, the following steps take place:

  1. Class Loading:

    • The Java class file is loaded into the JVM. The JVM first loads the class's bytecode into the Method Area.
  2. Memory Allocation:

    • Objects and arrays are created in the Heap Area. The Stack Area is used for method execution, where local variables are stored.
  3. Execution:

    • The PC Register keeps track of the current instruction being executed. The bytecode is executed in sequence, and the method calls are managed in the Stack Area.
  4. Native Code Execution:

    • If the Java program calls native methods, the code is executed from the Native Method Area.

Summary of JVM Areas

  • Method Area: Stores class-level information like bytecode and static variables.

  • Heap Area: Stores objects and arrays.

  • PC Register: Keeps the address of the next instruction to execute.

  • Native Method Area: Stores native (non-Java) code.

  • Stack Area: Stores local variables and method call information.

  • Runtime Constant Pool: Stores constants such as string literals.

Each of these areas plays a crucial role in the JVM's ability to manage memory and execute Java programs efficiently. The JVM architecture allows Java to be platform-independent by abstracting away the underlying hardware and providing a standardized execution environment.