Thursday, 28 August 2025

Java Development Kit (JDK) and Java Runtime Environment (JRE)

                 Java Development Kit (JDK) and Java Runtime Environment (JRE) 


To download and install the Java Development Kit ( JDK) and Java Runtime Environment (JRE), follow these step-by-step instructions for Windows, macOS, and Linux.The overall process is similar across all platforms, with minor differences in installation steps and setting up environment variables.

✅What is JDK in Java?

The Java Development Kit (JDK) is a complete software development kit used to build Java applications. It includes:

  • Java Runtime Environment (JRE) – provides the libraries and tools to run Java programs.
  • Java Virtual Machine (JVM) – executes the compiled Java bytecode.
  • Development tools – such as the Java compiler (javac), debugger, and packaging utilities.

In short, the JDK is more than just a runtime environment—it provides everything needed to develop, compile, and run Java programs.

✅Why Do We Need JDK Instead of Just JRE?

A common question developers ask is:
๐Ÿ‘‰ “To run Java programs, isn’t the JRE enough? Why do we need the complete JDK?”

The answer:

  • The JRE is enough to run Java applications.
  • But to develop Java applications, you need tools like the compiler (javac), debugger, and other utilities that are only included in the JDK.

That’s why programmers use the JDK for development and the JRE for execution.

✅The Architecture of JDK in Java

The architecture of JDK consists of three essential components:

  1. JVM (Java Virtual Machine)
    • Provides a runtime environment for Java programs.
    • Converts compiled Java bytecode into machine code.
    • Powers Java’s famous feature: “Write once, run anywhere.”
  2. JRE (Java Runtime Environment)
    • Provides the core librariesJava ClassLoader, and other components required to run applications.
    • It does not include development tools like the compiler.
  3. Development Tools (inside JDK)
    • Includes javac (Java compiler), jdb (debugger), jar (archiver), and other utilities required for building Java applications.

✅Downloading Java JDK and JRE

1. Visit the Official Website
Go to the Oracle Java Downloads page or the OpenJDK official site. The current stable Java versions are JDK 21 (LTS) and JDK 23 (latest release).

2. Choose Your Operating System
Download the installer that matches your operating system:

  • Windows (.exe)
  • macOS (.dmg or .pkg)
  • Linux (.tar.gz or Debian package)

3. Accept the License Agreement
For Oracle JDK downloads, review and accept the license agreement before proceeding with the download.

✅ Installing Java JDK on Windows

1. Run the Installer
Double-click the downloaded .exe file to start the installation.

2. Follow Installation Prompts
Proceed with the setup wizard, selecting the default options unless you prefer a custom location. By default, Java is installed in:

C:\Program Files\Java\jdk-xx

3. Set the JAVA_HOME Environment Variable

  • Right-click This PC → Properties → Advanced system settings → Environment Variables.
  • Add a new variable:
    • Name: JAVA_HOME
    • Value: path of your JDK installation (e.g., C:\Program Files\Java\jdk-21).
  • Edit the existing Path variable and add: %JAVA_HOME%\bin

๐Ÿ‘‰Follow this detailed guide on how to set up the Java PATH environment variable

4. Verify Installation
Open Command Prompt and run:

java --version
javac --version

๐Ÿ“ŒIf both commands show the installed version, your Java JDK setup on Windows is complete.

✅ Installing Java JDK on macOS

1. Run the Installer
Open the downloaded .dmg or .pkg installer and follow the on-screen instructions to complete the installation.

2. Configure Environment Variables
To set up JAVA_HOME and update the PATH:

  • If using bash, open ~/.bash_profile
  • If using zsh (default on newer macOS), open ~/.zshrc

Add:

export JAVA_HOME=$(/usr/libexec/java_home)
export PATH=$JAVA_HOME/bin:$PATH

Save the file and reload it:

source ~/.zshrc   # or source ~/.bash_profile

✅ Installing Java JDK on Linux

1. Download the Package
Choose the installer based on your Linux distribution:

  • Debian/Ubuntu: .deb package
  • RedHat/CentOS/Fedora: .rpm package
  • Generic: .tar.gz tarball

2. Install via Terminal

For Debian/Ubuntu:

sudo dpkg -i jdk-xx_linux-x64_bin.deb

For tar.gz (generic installation):

tar -xvzf jdk-xx_linux-x64_bin.tar.gz
sudo mv jdk-xx /opt/

3. Configure Environment Variables
Add the following lines to ~/.bashrc or ~/.zshrc:

export JAVA_HOME=/opt/jdk-xx
export PATH=$JAVA_HOME/bin:$PATH

Reload the file:

source ~/.bashrc   # or source ~/.zshrc

4. Verify Installation
Run the following commands to confirm Java is installed correctly:

java --version
javac --version

✅ Installing Java JRE

On Windows

Download the Java Runtime Environment (JRE) installer from the official Oracle Java Downloads page. Run the installer, follow the setup prompts, and configure the JRE path in System Environment Variables, similar to the JDK setup process.

On macOS/Linux

In most modern setups, the JRE is already bundled with the JDK. If you still need a standalone JRE, the process is similar: download the installer for your OS, complete the installation, set the JAVA_HOME environment variable, and verify the installation.


๐Ÿ“Œ Important Notes

  • Most modern JDK packages include JRE by default, so a separate JRE installation is usually unnecessary.
  • Always download Java from official sources (Oracle or OpenJDK) to ensure security and long-term support.
  • Correct installation and environment variable setup ensure Java is ready for both development (JDK) and runtime (JRE) tasks on your system.

Sunday, 24 August 2025

Exception Handling

Data Types

Java isEnum() Method

Java isEnum() Method 

The isEnum() method in Java, available in the java.lang.Class class, is used to check whether a given Class object represents an enumeration type.

If the class represents an enum, the method returns true; otherwise, it returns false.

This method is particularly useful in reflection-based programming, where enums need to be verified or processed dynamically (for example, in frameworks, libraries, or configuration systems).

Syntax :

public boolean isEnum()

Parameters

  • This method takes no parameters.

Returns

  • true → if the class object represents an enum type.
  • false → if the class object is not an enum type.

Understanding of isEnum() :

The method allows developers to check at runtime whether a class is an enum.This can be very useful when you want to dynamically handle enums (for example, iterating through their constants, generating dropdown options, or validating user inputs).

Example 1: Basic Usage

public class IsEnumExample {
    public static void main(String[] args) {
        Class<PaymentStatus> clazz = PaymentStatus.class;
        boolean result = clazz.isEnum();

        System.out.println("Is PaymentStatus an enum? " + result);
    }

    public enum PaymentStatus {
        PENDING, PROCESSING, SUCCESS, FAILED
    }
}

Output :

Is PaymentStatus an enum? true

✅ Here, PaymentStatus is an enum, so isEnum() returns true.

Example 2: Checking a Non-Enum Class

public class NonEnumExample {
    public static void main(String[] args) {
        Class<Integer> clazz = Integer.class;
        boolean result = clazz.isEnum();

        System.out.println("Is Integer an enum? " + result);
    }
}

Output:

Is Integer an enum? false

Note :๐Ÿ‘‰  Since Integer is not an enum, the result is false.

Key Ponts:

The Class.isEnum() method provides a reliable way to identify enums at runtime.

  • It returns true for enums and false otherwise.
  • It’s often used in reflection-based frameworks to dynamically handle enums for configuration, validation, or UI generation.
  • This makes it an important tool when building generic and reusable libraries.

ENUM

Enum

Enums were introduced in Java 5 (JDK 1.5) as a way to define a collection of named constants in a type-safe manner. Unlike enums in older languages (like C or C++), Java enums are far more powerful since they are implemented using class concepts and can contain constructors, methods, and variables.

What is an Enum?

  • Enum is a special data type used to define a group of named constants.
  • Each enum constant is implicitly:

    • public, static, and final.
  • Enums make the code readable, maintainable, and less error-prone compared to using int or String constants.
Example :

enum Month {
    JAN, FEB, MAR, DEC;
}

Internal Implementation of Enum

  • Internally, an enum is implemented as a class.
  • Every enum constant is a reference variable that points to its own enum object.
  • You can think of enums as a fixed set of static final objects.

Enum Declaration and Usage :

enum Month{
    JAN, FEB, MAR, DEC; // semicolon at the end is optional if no extra members
}

class Test {
    public static void main(String[] args) {
        Month mon = Month.FEB;
        System.out.println(mon);
    }
}
Output:

FEB
๐Ÿ‘‰ Note: Since enum constants are implicitly static, we can access them using EnumName.CONSTANT.

Enum with Switch Statement :

Before Java 5, switch allowed only byte, short, char, int (and their wrappers). From Java 5 onwards, enum types can also be used in a switch.

Example:

enum PaymentStatus {
    PENDING, PROCESSING, SUCCESS, FAILED;
}

class Test {
    public static void main(String[] args) {
        PaymentStatus status = PaymentStatus.PROCESSING;

        switch (status) {
            case PENDING:
                System.out.println("Payment is pending. Please wait...");
                break;
            case PROCESSING:
                System.out.println("Payment is being processed. Do not refresh the page.");
                break;
            case SUCCESS:
                System.out.println("Payment successful! Thank you for your purchase.");
                break;
            case FAILED:
                System.out.println("Payment failed. Please try again.");
                break;
            default:
                System.out.println("Unknown payment status.");
        }
    }
}
Output :

Payment is being processed. Do not refresh the page.
๐Ÿ‘‰ Every case label must be a valid enum constant, otherwise you’ll get a compile-time error.

Enum and Inheritance

  • Every enum in Java is implicitly a child of java.lang.Enum.
  • Hence, enums cannot extend other classes.
  • Enums are implicitly final, so they cannot be extended.
  • But enums can implement interfaces.

Useful Enum Methods

  1. values() returns all constants as an array.
  2. ordinal() returns the index (zero-based position) of the constant.
  3. valueOf(String name) returns the enum constant with the specified name 

values():

  • Returns an array containing all the constants of the enum, in the order they were declared.
  • Automatically added by the compiler for every enum type.
  • Return type: EnumType[]
๐Ÿ“Œ Syntax :
    
  public static EnumType[] values()

ordinal():

  • Returns the position (zero-based index) of the enum constant in its declaration.
  • Return type: int
  • Use case: Helpful when you need the position/order of the enum constant (e.g., for iteration or sorting).

valueOf(String name)

  • Returns the enum constant with the specified name.
  • The name must exactly match the declared constant (case-sensitive).
  • Return type: EnumType
  • Use case: Useful for converting a string into the corresponding enum constant.
๐Ÿ“Œ Syntax :
    
  public static EnumType valueOf(String name)

๐Ÿ“ŒEample :

  enum Day {
    MONDAY, TUESDAY, WEDNESDAY;
}

class Test {
    public static void main(String[] args) {
        // Using the compiler-generated method
        Day d1 = Day.valueOf("MONDAY");

        // Using Enum.valueOf (generic)
        Day d2 = Enum.valueOf(Day.class, "TUESDAY");

        System.out.println(d1); 
        System.out.println(d2); 
    }
}

Output :

MONDAY
TUESDAY

⚠️ Important Note:

  • If the string doesn’t match exactly, it throws IllegalArgumentException.
  • "monday" (lowercase) would fail because enum names are case-sensitive.

๐Ÿ“Œ Important Notes

  • The name must match the enum constant exactly (case-sensitive).
  • If the string doesn’t match any constant, it throws IllegalArgumentException.
  • null input throws NullPointerException.

✅ So yes, valueOf(String name) is always available for enums in Java, either via the compiler-generated method or the generic Enum.valueOf() method.

๐Ÿ“ŒNote : 

  • ordinal() is defined in the java.lang.Enum class.
  • valueOf(String) is also defined in the Enum class. 
  • values() is not defined in Enum; instead, it is a synthetic method automatically generated by the compiler for each enum type. That’s why you won’t find it in the JDK source of Enum.


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

class Test {
    public static void main(String[] args) {
        Day[] days = Day.values();
        for (Day d : days) {
            System.out.println(d + " ---> " + d.ordinal());
        }
    }
}
Output :

MONDAY ---> 0
TUESDAY ---> 1
WEDNESDAY ---> 2
THURSDAY ---> 3
FRIDAY ---> 4
SATURDAY ---> 5
SUNDAY ---> 6

✅ Key Differences :

Featureordinal()valueOf(String name)values()
PurposeReturns index (position) of constantReturns enum constant by its nameReturns an array of all enum constants
Return TypeintEnum type itselfEnum array (EnumType[])
InputNo input (called on enum constant)Takes String argumentNo input (called on enum type)
Example UsageDay.MONDAY.ordinal()0Day.valueOf("MONDAY")Day.MONDAYDay.values()[MONDAY, TUESDAY, …]
RiskChanges if enum order is modifiedThrows IllegalArgumentException if not foundNone (safe, but array order depends on enum order)

Enum with Constructors and Fields

Each enum constant is actually an object, and constructors are executed at class loading time.

enum UserRole {
    ADMIN(5), MODERATOR(3), CUSTOMER(1), GUEST;

    private int accessLevel;

    // parameterized constructor
    UserRole(int accessLevel) {
        this.accessLevel = accessLevel;
    }

    // default constructor (for GUEST)
    UserRole() {
        this.accessLevel = 0;
    }

    public int getAccessLevel() {
        return accessLevel;
    }
}

class Test {
    public static void main(String[] args) {
        for (UserRole role : UserRole.values()) {
            System.out.println(role + " has access level " + role.getAccessLevel());
        }
    }
}
Output :

ADMIN has access level 5
MODERATOR has access level 3
CUSTOMER has access level 1
GUEST has access level 0
Note :๐Ÿ‘‰ You cannot create enum objects manually (new UserRole() is not allowed). They are created internally at load time.
         ๐Ÿ‘‰ This way, each UserRole constant represents a real application role with an access level (like permissions in a system).

Enum with Methods

Enums can override methods just like classes.

Example:

enum NotificationType {
    EMAIL {
        @Override
        public void send() {
            System.out.println("Sending Email Notification...");
        }
    },
    SMS {
        @Override
        public void send() {
            System.out.println("Sending SMS Notification...");
        }
    },
    PUSH; // uses default implementation
    // default behavior
    public void send() {
        System.out.println("Sending Push Notification...");
    }
}

class Test {
    public static void main(String[] args) {
        for (NotificationType type : NotificationType.values()) {
            type.send();
        }
    }
}
Output :

Sending Email Notification...
Sending SMS Notification...
Sending Push Notification...

Static Import with Enum

You can use static imports to avoid qualifying enum constants.

package pack1;
public enum Fish {
    STAR, GUPPY;
}
package pack2;
import static pack1.Fish.*;

class A {
    public static void main(String[] args) {
        System.out.println(STAR);
        System.out.println(GUPPY);
    }
}

Valid imports:

  1. import static pack1.Fish.*;

  2. import static pack1.Fish.STAR;

Invalid imports:

  1. import pack1.*;

  2. import pack1.Fish;

๐Ÿ“Key Points (Latest Java Versions ✅)

  • Enums are type-safe constants.
  • They can have fields, methods, and constructors.
  • They cannot extend other classes, but can implement interfaces.
  • Enums are thread-safe since all constants are created at class loading.
  • From Java 5 onwards, enums can be used in switch.
  • Useful methods: values(), ordinal(), name(), compareTo().
  • They work seamlessly with Collections, Generics, and Streams (Java 8+).


Java Development Kit (JDK) and Java Runtime Environment (JRE)

                  Java Development Kit (JDK) and Java Runtime Environment (JRE)  To download and install the Java Development Kit (  JDK ) ...