Top Stories

Ankaj Gupta
December 27, 2020

how to create enum in java

What is Enum in Java?

An enum is a special "data type" that is used to create our own data type like classes. It represents a group of constants (a variable that does not change).

The enum is short for "enumerations", which means "specifically listed" and the Enum data is also known as Enumerated Data Type.

Defining Java Enum

Instead of C/C++, in Java programming language enum types are more powerful. Here, we can define an enum both inside and outside the class, but not inside a method.

Rules to Define Enum in Java:

  • 1. To create an enum in Java, use the enum keyword (instead of class or interface), and separate the constants with a comma
  • 2. The enum can be defined within or outside the class because it is similar to a class. The semicolon (;) at the end of the enum constants are optional
  • 3. Because enums are constants, the names of an enum type's fields are in uppercase letters

Syntax:

enum Directions { EAST, WEST, NORTH, SOUTH; }

// OR (semicolon is optional)

enum Directions { EAST, WEST, NORTH, SOUTH }

Accessing Java Enum

You can access enum constants with the help of dot operator:

Directions myVar = Directions.NORTH;

Examples of Java Enum

Example 1: Enum Defined Inside Class

class EnumExample {
    //Defining the enum inside the class
    enum Directions {
        EAST, WEST, NORTH, SOUTH
    } //semicolon(;) is optional here
    
    public static void main(String args[]) {
        Directions myvar = Directions.NORTH;
        System.out.println(myvar);
    }
}

Output:

NORTH

Example 2: Enum Defined Outside Class

//Defining the enum outside the class
enum Directions {
    EAST, WEST, NORTH, SOUTH
}

class EnumExample {
    public static void main(String args[]) {
        Directions direction = Directions.EAST;
        System.out.println("Direction: " + direction);
    }
}

Output:

Direction: EAST

Example 3: Using Enum in Switch Statement

enum Day {
    MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}

class EnumSwitchExample {
    public static void main(String[] args) {
        Day today = Day.WEDNESDAY;
        
        switch(today) {
            case MONDAY:
                System.out.println("Start of work week");
                break;
            case FRIDAY:
                System.out.println("TGIF!");
                break;
            case SATURDAY:
            case SUNDAY:
                System.out.println("Weekend!");
                break;
            default:
                System.out.println("Midweek day");
                break;
        }
    }
}

Output:

Midweek day

Built-in Enum Methods

Java enums have several useful built-in methods:

Method Description
values() Returns all enum constants as an array
valueOf(String) Returns enum constant with the specified name
ordinal() Returns the position of enum constant (starts at 0)
name() Returns the name of enum constant

Example: Using Enum Methods

enum Colors {
    RED, GREEN, BLUE, YELLOW
}

class EnumMethodsExample {
    public static void main(String[] args) {
        // Get all enum values
        for (Colors color : Colors.values()) {
            System.out.print(color + " ");
        }
        System.out.println();
        
        // Get ordinal value
        System.out.println("GREEN position: " + Colors.GREEN.ordinal());
        
        // Get enum by name
        Colors myColor = Colors.valueOf("BLUE");
        System.out.println("Color name: " + myColor.name());
    }
}

Output:

RED GREEN BLUE YELLOW
GREEN position: 1
Color name: BLUE

Enum vs. Traditional Constants

❌ Traditional Constants

public class Directions {
    public static final int EAST = 0;
    public static final int WEST = 1;
    public static final int NORTH = 2;
    public static final int SOUTH = 3;
}
  • • No type safety
  • • Can pass any integer
  • • No namespace
  • • Hard to debug

✅ Java Enum

public enum Directions {
    EAST, WEST, NORTH, SOUTH
}
  • • Type safe
  • • Only valid values allowed
  • • Has its own namespace
  • • Built-in methods available

Key Benefits of Using Enums

Type Safety

Compile-time checking ensures only valid enum values are used

Better Code Readability

Enum names are more descriptive than magic numbers or strings

Built-in Methods

Access to values(), valueOf(), ordinal(), and name() methods

Can Add Custom Methods

Enums can have constructors, methods, and fields

Best Practices

✅ Do's

  • • Use uppercase letters for enum constants
  • • Use enums for fixed sets of constants
  • • Use enums in switch statements
  • • Prefer enums over magic numbers/strings

❌ Don'ts

  • • Don't use enums for large sets of values
  • • Don't define enums inside methods
  • • Don't use lowercase for enum constants
  • • Don't forget to use semicolon with custom methods

Summary

Java enums are powerful and type-safe alternatives to traditional constants. They provide better code organization, compile-time checking, and built-in methods for working with a fixed set of related constants.

Enums can be defined inside or outside classes, used in switch statements, and can even have custom constructors, methods, and fields. Always use uppercase letters for enum constants and prefer enums over magic numbers or strings for better code maintainability.

Java program Java programming
Read
Ankaj Gupta
October 02, 2020

Polymorphism in php with example

PHP Fundamentals

Understanding Polymorphism in PHP

Polymorphism lets you interact with different objects through a common interface and still get behavior tailored to the object you are working with. In PHP, polymorphism sits at the heart of writing testable, extensible, and reusable object-oriented code.

Definition: Polymorphism describes the ability of different classes to respond to the same method call in different, class-specific ways.

The term comes from the Greek words poly (many) and morph (form). A single message—such as render() or process()—can trigger different logic depending on the object that receives it.

Why it matters

Keeps code flexible, reduces duplicate branching logic, and makes maintenance easier.

Where you use it

Framework controllers, service layers, strategy patterns, payment gateways, and more.

Polymorphism Techniques in PHP

Modern PHP uses polymorphism primarily through interfaces, inheritance, and magic methods. The table below highlights the main approaches.

Technique Best for Key Benefit
Method overriding Extending base classes Replace or refine default behavior
Interfaces & abstract classes Formal contracts for implementations Guarantees consistent API surface
Magic methods (__call, __callStatic) Dynamic or proxy objects Intercept unknown method calls

Method Overriding (Runtime Polymorphism)

In PHP, overriding happens when a child class redefines a method inherited from a parent class. When you invoke the method on the child, PHP executes the child’s version.

<?php

abstract class Notification
{
    abstract public function send(string $message): void;
}

class EmailNotification extends Notification
{
    public function send(string $message): void
    {
        echo "๐Ÿ“ง Sending email: {$message}\n";
    }
}

class SmsNotification extends Notification
{
    public function send(string $message): void
    {
        echo "๐Ÿ“ฑ Sending SMS: {$message}\n";
    }
}

function notifyUser(Notification $channel): void
{
    $channel->send('Your order has shipped!');
}

notifyUser(new EmailNotification());
notifyUser(new SmsNotification());

What happens: The notifyUser() function does not care which concrete class it receives. Each object answers the send() call with behavior of its own.

Interfaces and Polymorphism

Interfaces in PHP define a contract. Any class that implements the interface guarantees it will provide the required methods, making them interchangeable at runtime.

interface PaymentGateway
{
    public function charge(int $amount): bool;
}

class StripeGateway implements PaymentGateway
{
    public function charge(int $amount): bool
    {
        // call Stripe API...
        return true;
    }
}

class OfflineGateway implements PaymentGateway
{
    public function charge(int $amount): bool
    {
        // record cash payment...
        return true;
    }
}

function checkout(PaymentGateway $gateway): void
{
    if ($gateway->charge(1999)) {
        echo "Payment complete";
    }
}

checkout(new StripeGateway()); // easily swap with OfflineGateway

Tip: Depend on interfaces rather than concrete classes. This keeps code loosely coupled and easy to extend.

Dynamic Polymorphism with Magic Methods

PHP’s __call() and __callStatic() intercept method calls that do not exist. This is useful for proxy objects, adapters, or builders.

class LazyConfig
{
    private array $data = [];

    public function __call(string $name, array $arguments)
    {
        if (str_starts_with($name, 'set')) {
            $key = lcfirst(substr($name, 3));
            $this->data[$key] = $arguments[0] ?? null;
            return $this;
        }

        if (str_starts_with($name, 'get')) {
            $key = lcfirst(substr($name, 3));
            return $this->data[$key] ?? null;
        }

        throw new BadMethodCallException("Unknown method {$name}");
    }
}

$config = (new LazyConfig())
    ->setHost('localhost')
    ->setPort(3306);

echo $config->getHost(); // localhost

Caution: Magic methods are powerful but can hide bugs. Always validate method names and keep good tests.

Best Practices for Polymorphic PHP Code

Do

  • Design around interfaces and dependency injection
  • Keep method signatures consistent when overriding
  • Document expectations using PHPDoc and type hints
  • Test behavior through the shared interface

Avoid

  • Mixing business logic with type checks (instanceof)
  • Overusing magic methods for basic domain logic
  • Breaking Liskov Substitution Principle when overriding
  • Returning different types than the interface promises

Common Pitfalls

Duplicate method names: PHP does not support compile-time overloading like Java. Declaring two methods with the same name in a class causes a fatal error.

Missing return types: If a parent declares a return type, child classes must honor it or use compatible covariant types (PHP 7.4+).

Leaky abstractions: When subclasses expose details not promised by the interface, polymorphism breaks down.

Key Takeaways

  • Polymorphism enables a single interface to represent multiple concrete behaviors.
  • Use inheritance, interfaces, and magic methods to achieve polymorphism in PHP.
  • Favor interface-driven design and keep method contracts consistent to maintain substitutability.
  • Reserve magic methods for advanced use cases, and pair them with error handling and tests.
oops php programming
Read
Ankaj Gupta
September 29, 2020

Java program for student mark list using inheritance - java code examples with output

Java OOP Tutorial

Build a Student Mark List in Java Using Inheritance

This guide walks through designing a console-based Java application that captures marks for multiple students, calculates their totals, and prints a formatted report. You will apply single inheritance, encapsulation, and clean code practices to keep the workflow easy to extend.

Objective: Build a reusable base class for shared behaviours (input/output) and extend it with a student-specific subclass that stores marks and totals.

Key Concepts

  • Single inheritance
  • Array storage
  • Formatted console output

Prerequisites

  • Java 8 or newer
  • Basic OOP knowledge
  • Terminal/command prompt access

Deliverables

A `StudentReport` program that collects marks for n students, calculates totals, and prints a tabular mark list.

Designing the Class Hierarchy

Base Class: `MarkSheet`

Handles common tasks such as reading input, storing student data, and printing formatted headers. Methods include `captureStudent()` and `printTable()`.

Derived Class: `StudentReport`

Extends `MarkSheet` to add application flow—collecting the number of students, looping through entries, calculating totals, and triggering the final print.

Complete Java Implementation

The following code uses `Scanner` for input and keeps responsibilities separated across classes. Use it as a starting point for experimenting with grading rules or exporting data.

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

class MarkSheet {
    static class Student {
        String name;
        int[] marks;
        int total;

        Student(String name, int subjectCount) {
            this.name = name;
            this.marks = new int[subjectCount];
        }
    }

    protected final Scanner scanner = new Scanner(System.in);
    protected final List<Student> students = new ArrayList<>();
    protected final int subjectCount;

    MarkSheet(int subjectCount) {
        this.subjectCount = subjectCount;
    }

    protected void captureStudent() {
        System.out.print("Student name: ");
        String name = scanner.nextLine().trim();
        Student student = new Student(name, subjectCount);

        for (int i = 0; i < subjectCount; i++) {
            System.out.printf("Subject %d mark: ", i + 1);
            student.marks[i] = Integer.parseInt(scanner.nextLine().trim());
            student.total += student.marks[i];
        }

        students.add(student);
    }

    protected void printTable() {
        System.out.println("============================================================");
        System.out.printf("%-4s %-18s", "No", "Student Name");
        for (int i = 0; i < subjectCount; i++) {
            System.out.printf(" Sub%-2d", i + 1);
        }
        System.out.printf("  Total%n");
        System.out.println("============================================================");

        int index = 1;
        for (Student student : students) {
            System.out.printf("%-4d %-18s", index++, student.name);
            for (int mark : student.marks) {
                System.out.printf(" %-6d", mark);
            }
            System.out.printf(" %-6d%n", student.total);
        }

        System.out.println("============================================================");
    }
}

public class StudentReport extends MarkSheet {

    public StudentReport(int subjectCount) {
        super(subjectCount);
    }

    public void run() {
        System.out.print("How many students? ");
        int numberOfStudents = Integer.parseInt(scanner.nextLine().trim());

        for (int i = 0; i < numberOfStudents; i++) {
            System.out.printf("%nEnter details for student %d%n", i + 1);
            captureStudent();
        }

        System.out.println();
        printTable();
    }

    public static void main(String[] args) {
        int subjectCount = 5; // Adjust as needed
        StudentReport report = new StudentReport(subjectCount);
        report.run();
    }
}
Tip: Replace `Scanner` with `java.nio` file reading APIs if you prefer to read student data from CSVs or external feeds.

Sample Console Output

How many students? 2

Enter details for student 1
Student name: Ankaj
Subject 1 mark: 8
Subject 2 mark: 9
Subject 3 mark: 6
Subject 4 mark: 7
Subject 5 mark: 9

Enter details for student 2
Student name: Anmol
Subject 1 mark: 9
Subject 2 mark: 6
Subject 3 mark: 7
Subject 4 mark: 8
Subject 5 mark: 9

============================================================
No   Student Name       Sub1   Sub2   Sub3   Sub4   Sub5   Total
============================================================
1    Ankaj              8      9      6      7      9      39
2    Anmol              9      6      7      8      9      39
============================================================

Suggested Enhancements

Feature Ideas

  • Calculate averages and grades
  • Export reports to CSV or PDF
  • Add validation for mark ranges

Common Pitfalls

  • Mixing `Scanner.nextInt()` and `nextLine()` without consuming newline characters
  • Hard-coding subject counts across multiple methods
  • Ignoring encapsulation—keep student details private

Key Takeaways

  • Inheritance lets you share input/output logic while keeping student-specific behaviour separate.
  • Use collections (`List`) to store dynamic numbers of students instead of fixed-size arrays.
  • Plan for extensibility—separate formatting, data capture, and calculation so new features are easy to add.
Java program
Read
Ankaj Gupta
September 29, 2020

Java program for student mark list using class and object - java code examples with output

Program to print student mark list using class and object

In this section, You will learn how to calculate and print student total marks lists of n number of student in java, with the help of InputStreamReader and BufferedReader class.

Let's try to create a simple example :

Example : student.java;

import java.io.*;

class MList {
    static public StudentsInfo theStudents = new StudentsInfo();

    public static void ViewRecords() {
        System.out.println("_______________________________________________________________");
        System.out.println("SNo Student Name       Sub1   Sub2   Sub3   Sub4   Sub5   Total");
        System.out.println("_______________________________________________________________");

        for(int i = 0; i < theStudents.m_nMaxStudents; i++){
            System.out.format("%1$-5d", i+1);

            System.out.format("%1$-19s", theStudents.m_studList[i].name);
            System.out.format("%1$-7d", theStudents.m_studList[i].marks[0]);
            System.out.format("%1$-7d", theStudents.m_studList[i].marks[1]);
            System.out.format("%1$-7d", theStudents.m_studList[i].marks[2]);
            System.out.format("%1$-7d", theStudents.m_studList[i].marks[3]);
            System.out.format("%1$-7d", theStudents.m_studList[i].marks[4]);
            System.out.format("%1$-7d", theStudents.m_studList[i].total);
            System.out.println();
        }
        System.out.println("_______________________________________________________________");
    }   

    public static void InputRecords() {
        try{
            InputStreamReader input = new InputStreamReader(System.in);  
            BufferedReader reader = new BufferedReader(input);  

            System.out.print("Student Name : ");
            String name;

            int[] marks = new int[5];
            name = reader.readLine(); 

            for(int i = 1; i <= 5; i++){
                System.out.print("Sub "+i+" Mark : ");
                marks[i-1] = Integer.parseInt(reader.readLine()); 
            }
            theStudents.AddRecord(name, marks);
        }
        catch(Exception e){
            e.printStackTrace();
        }
    }

    public static void main(String args[]) {
        String stdNumber = "";
        InputStreamReader input = new InputStreamReader(System.in);  
        BufferedReader reader = new BufferedReader(input); 

        try{
            System.out.print("Enter the number of students: ");
            stdNumber = reader.readLine(); 
            int numStudents = Integer.parseInt(stdNumber); 

            for(int i = 1; i <= numStudents; i++){
                System.out.println("\nEnter "+i+" Student Information \n");
                InputRecords();
            }

            ViewRecords();

        }
        catch(Exception e){
            e.printStackTrace();

        }

    }

}

class Student {
  public String name;
  public int[] marks = new int[5];
  public int total;

}

class StudentsInfo {
    public Student[] m_studList = new Student[100];
    public int m_nMaxStudents;

    public int AddRecord(String name, int[] marks) {
        Student stud = new Student();
        stud.name = name; 
        stud.marks = marks; 
        stud.total = 0; 

        for(int i = 0; i < 5; i++){
            stud.total += stud.marks[i]; 
        }

        m_studList[m_nMaxStudents++] = stud; 
        return 1;
    }
}
Output :
  • Enter the number of students:2
  • Enter 1 Student Information
  • Student Name: Ankaj
  • Sub 1 Mark : 90
  • Sub 1 Mark : 80
  • Sub 1 Mark : 85
  • Sub 1 Mark : 82
  • Sub 1 Mark : 70
  •  
  • Enter 1 Student Information
  •  
  • Student Name: Anmol
  • Sub 1 Mark : 88
  • Sub 1 Mark : 75
  • Sub 1 Mark : 80
  • Sub 1 Mark : 92
  • Sub 1 Mark : 70
  • ---------------------------------------------------------------------
  • SNO Student Name Sub1 Sub2 Sub3 Sub4 Sub5 Total
  • ---------------------------------------------------------------------
  • 1 Ankaj 90 80 85 82 70 407
  • 2 Anmol 88 75 80 92 70 405
  • ---------------------------------------------------------------------
Recommended Posts:
import java.io.*;

class MList {
    static public StudentsInfo theStudents = new StudentsInfo();

    public static void ViewRecords() {
        System.out.println("_______________________________________________________________");
        System.out.println("SNo Student Name       Sub1   Sub2   Sub3   Sub4   Sub5   Total");
        System.out.println("_______________________________________________________________");

        for(int i = 0; i < theStudents.m_nMaxStudents; i++){
            System.out.format("%1$-5d", i+1);

            System.out.format("%1$-19s", theStudents.m_studList[i].name);
            System.out.format("%1$-7d", theStudents.m_studList[i].marks[0]);
            System.out.format("%1$-7d", theStudents.m_studList[i].marks[1]);
            System.out.format("%1$-7d", theStudents.m_studList[i].marks[2]);
            System.out.format("%1$-7d", theStudents.m_studList[i].marks[3]);
            System.out.format("%1$-7d", theStudents.m_studList[i].marks[4]);
            System.out.format("%1$-7d", theStudents.m_studList[i].total);
            System.out.println();
        }
        System.out.println("_______________________________________________________________");
    }   

    public static void InputRecords() {
        try{
            InputStreamReader input = new InputStreamReader(System.in);  
            BufferedReader reader = new BufferedReader(input);  

            System.out.print("Student Name : ");
            String name;

            int[] marks = new int[5];
            name = reader.readLine(); 

            for(int i = 1; i <= 5; i++){
                System.out.print("Sub "+i+" Mark : ");
                marks[i-1] = Integer.parseInt(reader.readLine()); 
            }
            theStudents.AddRecord(name, marks);
        }
        catch(Exception e){
            e.printStackTrace();
        }
    }

    public static void main(String args[]) {
        String stdNumber = "";
        InputStreamReader input = new InputStreamReader(System.in);  
        BufferedReader reader = new BufferedReader(input); 

        try{
            System.out.print("Enter the number of students: ");
            stdNumber = reader.readLine(); 
            int numStudents = Integer.parseInt(stdNumber); 

            for(int i = 1; i <= numStudents; i++){
                System.out.println("\nEnter "+i+" Student Information \n");
                InputRecords();
            }

            ViewRecords();

        }
        catch(Exception e){
            e.printStackTrace();

        }

    }

}

class Student {
  public String name;
  public int[] marks = new int[5];
  public int total;

}

class StudentsInfo {
    public Student[] m_studList = new Student[100];
    public int m_nMaxStudents;

    public int AddRecord(String name, int[] marks) {
        Student stud = new Student();
        stud.name = name; 
        stud.marks = marks; 
        stud.total = 0; 

        for(int i = 0; i < 5; i++){
            stud.total += stud.marks[i]; 
        }

        m_studList[m_nMaxStudents++] = stud; 
        return 1;
    }
}
Java program
Read
Ankaj Gupta
September 03, 2020

java program for student details using inheritance

Java program to print student details using "single-level" inheritance

In this section, you will learn how to print student details using single inheritance in Java, with Scanner and without Scanner class.

1

With Scanner class

Interactive input using Scanner for user data entry

Note: This method uses the Scanner class to get input from the user at runtime. The program prompts for student details and displays them.

Example Code:

File: student.java

import java.util.Scanner;
class StudentDetails {
    int roll_no;
    String name, cl;
    //creating a function to take student details
    void input() {
        Scanner sc = new Scanner(System.in);
        
        System.out.print("Enter Roll Number: ");
        roll_no = sc.nextInt();  //=> 22\n == buffer
        
        sc.nextLine(); // => \n
        
        System.out.print("Enter Name: ");
        name = sc.nextLine();
        
        System.out.print("Enter class: ");
        cl = sc.nextLine();
    }
}
class Student extends StudentDetails {
    //method to display student details
    void display() {
        System.out.println("/******* Student details printed ********/");
        System.out.println("Roll Number is: "+roll_no);
        System.out.println("Your name is: "+name);
        System.out.println("Your class is: "+cl);
    }
    public static void main(String args[]) {
        Student obj = new Student();
        obj.input();
        obj.display();
    }
}

Output:

Console Output

Enter Roll Number: 22
Enter Name: Coder Website
Enter class: 12th
/******* Student details printed ********/
Roll Number is: 22
Your name is: Coder Website
Your class is: 12th
2

Without Scanner class

Hard-coded values passed directly to methods

Note: This method uses parameters to pass student details directly. Useful when data is already known or when testing multiple students.

Example Code:

File: student.java

class StudentDetails {
    int roll_no;
    String name, cl;
    //creating a function to take student details
    void input(int roll, String nam, String cl_name) {
        roll_no = roll;
        name   = nam;
        cl     = cl_name;
    }
}
class Student extends StudentDetails {
    //method to display student details
    void display() {
        System.out.println("\n/******* Student details printed ********/");
        System.out.println("Roll Number is: "+roll_no);
        System.out.println("Your name is: "+name);
        System.out.println("Your class is: "+cl);
    }
    public static void main(String args[]) {
        Student std1 = new Student();
        std1.input(20, "Ankaj Gupta", "12th");
        std1.display();
        
        Student std2 = new Student();
        std2.input(10, "Anmol kumar", "10th");
        std2.display();
    }
}

Output:

Console Output

/******* Student details printed ********/
Roll Number is: 20
Your name is: Ankaj Gupta
Your class is: 12th
/******* Student details printed ********/
Roll Number is: 10
Your name is: Anmol kumar
Your class is: 10th
Java program
Read
Ankaj Gupta
August 31, 2020

How to calculate content-length python

Python Networking

Calculate Content Length with Python Requests

Need to know how much data a URL returns? The requests package makes it simple to fetch a page and inspect the raw payload size. This walkthrough covers installation, a sample script, and best practices.

Prerequisites

Environment

  • Python 3.8 or higher
  • Terminal access (Command Prompt, PowerShell, or shell)
  • Internet connection to reach target URLs

Install Requests

# Windows
pip install requests

# macOS / Linux
pip3 install requests

Already installed? Run pip show requests to confirm the version.

Step-by-Step Implementation

  1. 1. Import the library.

    Use a simple import requests. If you see no errors, the installation succeeded.

  2. 2. Send a GET request.

    Wrap the call in requests.get(). Consider using timeout to avoid long waits on slow servers.

  3. 3. Inspect the response.

    The content attribute returns the raw bytes. Use Python’s len() to measure the payload size.

Example Script

import requests

def get_content_length(url: str, timeout: int = 10) -> int:
    """Return the size (in bytes) of the response body for a URL."""

    response = requests.get(url, timeout=timeout)
    response.raise_for_status()  # raise an exception for 4xx/5xx errors
    return len(response.content)

if __name__ == "__main__":
    target_url = "https://www.example.com"
    try:
        size_in_bytes = get_content_length(target_url)
        print(f"Content length for {target_url}: {size_in_bytes} bytes")
    except requests.exceptions.RequestException as exc:
        print(f"Request failed: {exc}")

Why handle exceptions? Production scripts should catch network issues (timeouts, DNS errors) and HTTP errors to avoid silent failures or half-fetched data.

Sample Output

Content length for https://www.example.com: 12564 bytes

Troubleshooting

Common Issues

  • Timeouts: Increase the timeout value or verify connectivity.
  • Redirect loops: Check response.history for multiple hops.
  • Compressed responses: Some servers gzip content—length represents compressed bytes.

Tips

  • Inspect response.headers["Content-Length"] if provided.
  • Use streaming (stream=True) for large downloads to avoid memory spikes.
  • Combine with logging to audit request performance.

Where to Go Next

  • Convert byte counts to kilobytes/megabytes for easier reporting.
  • Integrate with schedulers (cron, Windows Task Scheduler) to track changes over time.
  • Benchmark multiple URLs and visualize results in a dashboard (e.g., Grafana, Tableau).
Python programming
Read
Ankaj Gupta
August 20, 2020

Javascript division by 0

JavaScript Basics

What Happens When You Divide by Zero in JavaScript?

Unlike many languages that throw an error, JavaScript returns special numeric values when you divide by zero. Understanding these edge cases prevents confusing console output and logical bugs in your applications.

Safe but Special

Dividing a finite non-zero number by zero never throws an exception in JavaScript. The runtime returns Infinity or -Infinity instead.

Watch for NaN

Zero divided by zero—or an invalid numeric expression—produces NaN. Always guard calculations with sanity checks.

Division by Zero Outcomes

Expression Result Explanation
10 / 0 Infinity Positive numerator divided by zero returns positive infinity.
-10 / 0 -Infinity Sign is preserved—negative numerator produces negative infinity.
0 / 0 NaN Mathematically undefined, so JavaScript returns Not-a-Number.
1 / Infinity 0 When dividing by infinity you approach zero, which is useful for normalization logic.

Console Examples

Positive Numerator

const numerator = 10;
const denominator = 0;

const result = numerator / denominator;
console.log(result); // Infinity
console.log(Number.isFinite(result)); // false

Zero Numerator

const value = 0 / 0;

console.log(value);             // NaN
console.log(Number.isNaN(value)); // true
console.log(value === value);     // false (NaN is never equal to itself)

How to Guard Against Unexpected Results

  • Check denominators first: if (denominator === 0) before performing the division.
  • Use helper utilities: Create a reusable function that returns null or throws when division is invalid.
  • Normalize Infinity: Replace Infinity with a sentinel value when serializing or persisting data.
  • Avoid NaN propagation: NaN contaminates further calculations—use Number.isNaN() to guard intermediate values.

Reusable Safe Division Helper

export function safeDivide(numerator, denominator, fallback = null) {
    if (denominator === 0) {
        return fallback;
    }

    const value = numerator / denominator;
    return Number.isFinite(value) ? value : fallback;
}

// usage
console.log(safeDivide(12, 3)); // 4
console.log(safeDivide(12, 0)); // null

Key Takeaways

  • JavaScript returns Infinity or -Infinity instead of throwing when dividing by zero.
  • 0 / 0 is NaN, which silently poisons later math operations.
  • Always validate denominators and handle special numeric values before rendering or storing results.
Code JavaScript Code
Read
Ankaj Gupta
August 19, 2020

Properties list in JavaScript

JavaScript Fundamentals

Create, Access, and Iterate JavaScript Object Properties

Object literals are the backbone of JavaScript applications. They store configuration, API responses, and UI state in an easy-to-read format. This guide walks through building a nested object, accessing values, and iterating properties safely.

Object Literals

Define key–value data inline using curly braces. Ideal for configuration and mock data.

Property Access

Use dot notation for known keys, bracket notation for dynamic keys.

Iteration Patterns

Loop through objects with for...in, Object.keys(), or Object.entries().

1. Define a Nested Object

Start with a single literal that groups fruit nutrition facts. Each fruit is another object containing macronutrient values.

const fruits = {
    apple: {
        water: "86%",
        protein: "0.3 g",
        fat: "0.2 g",
        sugars: "10.4 g"
    },
    mango: {
        water: "83.5 g",
        protein: "0.8 g",
        fat: "0.4 g",
        sugars: "14.8 g"
    }
};

Tip: Keep numeric units in strings if they include symbols (%, g). Otherwise, store numbers and add units when rendering.

2. Access Properties

Dot Notation

const appleProtein = fruits.apple.protein;
console.log(appleProtein); // "0.3 g"

Bracket Notation

const fruitName = "mango";
const nutrient = "sugars";

console.log(fruits[fruitName][nutrient]); // "14.8 g"

3. Iterate Over Properties

Choose an iteration strategy based on the data you need. The examples below log each nutrient for every fruit.

for...in Loop

for (const property in fruits.apple) {
    if (Object.prototype.hasOwnProperty.call(fruits.apple, property)) {
        console.log(`${property}: ${fruits.apple[property]}`);
    }
}

Object.entries()

Object.entries(fruits).forEach(([fruitName, stats]) => {
    console.log(`\n${fruitName.toUpperCase()}`);

    Object.entries(stats).forEach(([nutrient, value]) => {
        console.log(`- ${nutrient}: ${value}`);
    });
});

4. Present Objects as Tables

When displaying object data in the browser, render it in a table to improve readability.

Fruit Water Protein Fat Sugars
Apple 86% 0.3 g 0.2 g 10.4 g
Mango 83.5 g 0.8 g 0.4 g 14.8 g

Best Practices

Recommended

  • Freeze configuration objects with Object.freeze().
  • Namespace related data in nested objects for clarity.
  • Use TypeScript or JSDoc to document expected properties.

Avoid

  • Mutating objects in multiple places without tracking state.
  • Using for...in without hasOwnProperty.
  • Mixing numeric and string keys unless absolutely necessary.

Key Takeaways

  • Object literals let you describe complex data structures with minimal syntax.
  • Choose the right access pattern—dot for known keys, brackets for dynamic ones.
  • Use iteration helpers such as Object.entries() to keep loops concise and readable.
Code JavaScript Code
Read
Ankaj Gupta
August 19, 2020

Access properties in javascript

JavaScript Fundamentals

How to Access JavaScript Object Properties (Dot vs Bracket)

JavaScript offers two primary syntaxes for reading and writing object properties: dot notation and bracket notation. Mastering both patterns ensures your code works with dynamic keys, external data, and reserved words.

Dot Notation

Concise, autocomplete friendly, works with valid identifiers (letters, digits, underscores).

Bracket Notation

Handles dynamic property names, strings with spaces, numbers, and characters disallowed in identifiers.

Dot Notation

const book = {
    id: 2,
    title: "JavaScript Essentials",
    author: "Coder Website"
};

console.log(book.id);    // 2
console.log(book.title); // "JavaScript Essentials"

Remember: Property names must be valid identifiers (no spaces or hyphens) to use dot notation.

Bracket Notation

Bracket notation accepts any string or expression inside the brackets. Use it for keys with spaces, numbers, or when using variables.

const dynamicKey = "title";

console.log(book[dynamicKey]); // "JavaScript Essentials"
console.log(book["author"]);   // "Coder Website"

When You Must Use Bracket Notation

Keys with Spaces or Hyphens

const movie = {
    "release date": "2024-08-01"
};

console.log(movie["release date"]); // works
console.log(movie.release date);     // SyntaxError

Numeric Property Names

const stats = {
    1: "Bronze",
    2: "Silver",
    3: "Gold"
};

console.log(stats[1]); // "Bronze"
console.log(stats.1);  // SyntaxError

Working with Dynamic Keys

External data (e.g., API responses) often requires dynamic property access.

const response = {
    metrics: {
        visits_2024: 12000,
        visits_2023: 9800
    }
};

function getMetric(year) {
    const key = `visits_${year}`;
    return response.metrics[key] ?? 0;
}

console.log(getMetric(2024)); // 12000

Dot vs Bracket at a Glance

Scenario Preferred Syntax Reason
Static, known keys Dot notation Cleaner syntax, IDE autocomplete support
Keys with spaces or symbols Bracket notation Dot notation is invalid syntax
Access via variables Bracket notation Allows expression evaluation inside brackets
Numeric keys Bracket notation Dot notation treats numbers as invalid identifiers

Key Takeaways

  • Use dot notation when property names are static and valid identifiers.
  • Switch to bracket notation for dynamic keys, user-generated data, or properties with special characters.
  • Combine both approaches for readable, resilient code that adapts to different data shapes.
JavaScript
Read