Skip to main content

Java Program to count number of employees working in a company (Completed With Garbage Collection)


    // Java Program to count number of employees working in a company (Completed With Garbage Collection)

    class Employee {
        private String name;
        private int age;
        private int ID;
        private static int nextId = 1;
       
       
        public Employee (String name, int age) {
            this.name = name;
            this.age = age;
            this.ID = nextId++;
        }
       
        public void show()
        {
            System.out.println( "\nID=" + ID +  "\nName=" + name + "\nAge=" + age);
        }
       
        public void showNextId()
        {
            System.out.println("Next employee id will be=" + nextId);
        }
       
        protected void finalize()
        {
            --nextId;
            // In this case,
            // gc will call finalize()
            // for 2 times for 2 objects.
        }
    }

    class HelloWorld {
        public static void main(String[] args) {
            Employee E = new Employee("Ayush", 28);
            Employee F = new Employee("Abhinav", 24);
            E.show();
            F.show();
           
            //Sub block
            {
                Employee X = new Employee("GFG4", 23);
                Employee Y = new Employee("GFG5", 21);
                X.show();
                Y.show();
               
                X = Y = F = null;
                System.gc();
                System.runFinalization();
            }
           
            E.showNextId();
        }
    }
   

This Java program defines two classes: Employee and HelloWorld. It demonstrates the use of garbage collection in Java to manage object destruction and resource reclamation.

Here's a breakdown of the code:

1. Employee Class:

  • Employee is a class representing employees in a company.
  • It has private instance variables name, age, and ID, representing the employee's name, age, and a unique identifier.
  • nextId is a static variable that keeps track of the next available ID for a new employee.
  • The constructor initializes the name and age of the employee and assigns a unique ID to the ID variable using the nextId static variable.
  • The show method prints the details of the employee (ID, name, and age).
  • The showNextId method prints the next available employee ID.
  • The finalize method is called by the garbage collector before an object is reclaimed. In this case, it decrements the nextId variable.
  1. 2. HelloWorld Class:

    • • HelloWorld is the main class with the main method.
    • • Inside the main method:
      • • Two Employee objects, E and F, are created with specific names and ages. Their details are then displayed using the show method.
      • • A sub-block is created, where two additional Employee objects, X and Y, are created and displayed.
      • • The references X, Y, and F are set to null, indicating that there are no more references to those objects.
      • • The System.gc() method is called, suggesting to the JVM that it's an appropriate time to run the garbage collector.
      • • System.runFinalization() is called to ensure that the finalize method is executed for objects pending finalization.
      • • The showNextId method of the original Employee object E is called to display the next available employee ID.

Note: The use of System.gc() and System.runFinalization() is generally discouraged, and it's usually up to the JVM to decide when to run the garbage collector. Explicitly invoking these methods is not a recommended practice in most cases. The finalize method is also not guaranteed to be called promptly by the garbage collector, and it's generally advised to use other resource management techniques.

Comments

Popular posts from this blog

Mastering Python Decorators: A Comprehensive Guide

Welcome to our comprehensive guide on mastering Python decorators! Whether you're a seasoned Python developer or just starting your coding journey, understanding decorators is a key step toward writing more elegant and efficient code. What are Decorators? Decorators are a powerful feature in Python that allows you to modify the behavior of functions or methods. They provide a clean and concise way to enhance the functionality of your code without cluttering it with repetitive patterns. Basics of Decorators Let's start with the basics. In Python, decorators are denoted by the @decorator syntax . Consider the following example:          def my_decorator ( func ):         def wrapper ():             print ( "Something is happening before the function is called." )             func()             print ( "Something is happening after the function is called." )         return wrapper     @my_decorator     def say_hello ():         print ( "Hello!" )

How to Create and Use Custom Filters in Django HTML Templates?

To add custom filters in a Django HTML template, you can follow these steps: Create a Custom Filter Function: You need to create a Python function that defines your custom filter logic. This function should accept one or more arguments and return the filtered output. Register the Filter Function: You'll need to register your custom filter function with Django's template system. This is typically done in a Django app's templatetags directory. Use the Custom Filter in Your HTML Template: After registering the custom filter, you can use it in your HTML templates by loading the filter library and applying the filter to a variable or expression. Here's a step-by-step guide: Step 1: Create a Custom Filter Function  Let's say you want to create a custom filter to capitalize the first letter of each word in a string. You can define your custom filter function like this:         # myapp/templatetags/custom_filters.py     from django import template     register = templ

How to perform CRUD operations using Node.js and MongoDB?

CRUD with Node.js and MongoDB To perform CRUD (Create, Read, Update, and Delete) operations using Node.js and MongoDB, we can follow these steps: 1. Install Node.js To install Node.js, visit https://nodejs.org/en/ . The node version used in this code is v16.15.0. 2. Install the MongoDB driver First, create a project directory. We will name our project "CrudApp" . Then, to install the MongoDB driver, use npm by running the following command: npm install mongodb For the database view, you can download MongoDB Compass, or MongoDB Atlas can also be used. 3. It's time to CODE          // Node.js has a built-in module called HTTP. This helps     // Node.js to send information using the     // Hyper Text Transfer Protocol (HTTP).     const http = require ( 'http' );     // url module provides utilities for URL resolution and parsing.     // We are using variable as nodeUrl because we have already     // defined url variable below     const nodeUrl = require ( 'ur