Skip to content

Latest commit

 

History

History
591 lines (381 loc) · 17.5 KB

README.md

File metadata and controls

591 lines (381 loc) · 17.5 KB

1. Introduction to Java Programming ☕

Navigation: Main Tutorial Index | Next: Java Installation

Examples: Hello.java

1.1 What is Java?

Java is a high-level, object-oriented, platform-independent programming language used to develop different types of applications, such as desktop applications, web applications, Android applications, enterprise software, and backend systems.

Java was developed by James Gosling and his team at Sun Microsystems and was officially released in 1995. Today, Java is maintained by Oracle and the Java community through OpenJDK.

Java is one of the most popular programming languages because it is reliable, secure, portable, and widely used in the software development industry.

Simple Example

Think about a mobile application like a banking app. When you check your bank balance, transfer money, or view transactions, the application communicates with backend systems. Java can be used to build those backend systems and handle business logic.

In simple words:

Java allows developers to write instructions that tell computers what to do.

1.2 Why Learn Java?

Java is a great programming language for beginners as well as experienced developers.

Some important reasons to learn Java are:

  1. Easy to Learn: Java has a structured syntax that is relatively easy to understand, especially if you already know programming fundamentals.
  2. Object-Oriented: Java uses classes and objects to organize code and make applications easier to maintain.
  3. Platform Independent: Java programs can run on different operating systems without rewriting the original source code, provided a compatible Java runtime is available.
  4. Secure: Java provides features such as bytecode verification, access control, and runtime security mechanisms.
  5. Robust: Java provides exception handling, type checking, and automatic memory management.
  6. Multithreading: Java supports running multiple tasks concurrently.
  7. Large Community: Java has a huge developer community, documentation, libraries, and frameworks.
  8. Career Opportunities: Java is widely used in enterprise software, backend development, banking systems, and many other industries.

1.3 Where is Java Used?

Java is used in many areas of software development.

Area Example
Web Development Backend applications and APIs
Android Development Android applications
Enterprise Applications Banking and business software
Financial Systems Payment and transaction processing
Desktop Applications Management software
Cloud Computing Backend and distributed systems
Big Data Data processing tools
E-commerce Shopping and order management systems

1.4 Features of Java

Java provides several important features that make it powerful and popular.

1. Simple

Java syntax is similar to C and C++, but it removes some complex features such as explicit pointer manipulation and manual memory management.

2. Object-Oriented

Java follows object-oriented programming principles:

  • Encapsulation
  • Inheritance
  • Polymorphism
  • Abstraction

These concepts help developers write reusable and organized code.

3. Platform Independent

Java follows the principle:

Write Once, Run Anywhere (WORA).

It means you can compile a Java program on one operating system and run the generated bytecode on another operating system with a compatible JVM.

4. Secure

Java provides a runtime environment with bytecode verification, class loading controls, and other security features.

5. Robust

Java helps developers create reliable applications through exception handling, strong type checking, and automatic memory management.

6. Multithreaded

Java allows multiple threads to execute concurrently. For example, an application can download a file while displaying other information.

7. Portable

Java bytecode is designed to work across different platforms that support a compatible JVM.

8. High Performance

Java uses Just-In-Time (JIT) compilation to optimize frequently executed code, improving application performance.

9. Distributed

Java provides networking APIs that help developers build applications communicating across different computers.

10. Dynamic

Java supports dynamic class loading, allowing classes to be loaded when they are needed during program execution.


2. How Does Java Work?

Before understanding JVM, JRE, and JDK, let's understand how a Java program runs.

Unlike some programming languages that directly execute compiled machine code, Java follows a two-step process:

  1. Java source code is compiled into bytecode.
  2. The JVM executes that bytecode on the target operating system.

Java Execution Process

       Java Source Code
          Hello.java
              |
              |
              v
       Java Compiler
           javac
              |
              |
              v
        Bytecode File
          Hello.class
              |
              |
              v
      Java Virtual Machine
             JVM
              |
              |
              v
       Machine Execution
              |
              |
              v
        Program Output

Step-by-Step Explanation

Step 1: Write Java Code

A developer writes a Java program and saves it with the .java extension.

Example: Hello.java

Step 2: Compile the Program

The Java compiler (javac) converts the source code into bytecode.

Command:

javac Hello.java

After successful compilation, a Hello.class file is generated.

Step 3: Execute the Program

The JVM loads and executes the generated bytecode.

Command:

java Hello

Step 4: Get the Output

The JVM executes the program and displays the result.


3. What is JVM (Java Virtual Machine)?

JVM stands for Java Virtual Machine.

JVM is a virtual machine that provides an environment to execute Java bytecode.

In simple language, JVM acts as a bridge between Java bytecode and the operating system.

It is responsible for loading, verifying, and executing Java bytecode.

Why Do We Need JVM?

Imagine that you develop a Java application on Windows, but your friend wants to run the same application on macOS.

Without platform-independent execution support, you might need to create different versions for different operating systems.

Java solves this problem using JVM.

The Java compiler generates bytecode, and different operating systems have their own compatible JVM implementations.

Therefore, the same bytecode can run on different platforms.

JVM Architecture

The JVM has several important components.

              JVM ARCHITECTURE
                     |
       +-------------+-------------+
       |                           |
       v                           v
  Class Loader Subsystem     Runtime Data Areas
       |                           |
       |                    +------+------+
       |                    |             |
       v                    v             v
   Loading              Method Area    Heap
   Linking              Java Stack     PC Register
   Initialization       Native Method Stack
                              |
                              v
                     Execution Engine
                              |
                    +---------+---------+
                    |         |         |
                    v         v         v
                   JIT     Interpreter  GC
                  Compiler
                    |
                    v
               Native Machine Code

Main Components of JVM

1. Class Loader Subsystem

The Class Loader loads .class files into JVM memory when they are needed.

It performs three main activities:

  • Loading: Finds and loads the required class files.
  • Linking: Verifies bytecode, prepares memory for static variables, and resolves symbolic references.
  • Initialization: Executes static initializers and assigns explicit values to static variables.

2. Runtime Data Areas

Runtime Data Areas are memory areas used by JVM while executing a Java program.

They include:

a. Method Area

Stores class-level information such as class metadata, method information, and runtime constant pools.

b. Heap Area

Stores objects and arrays created during program execution.

Example:

Student student = new Student();

The Student object is generally allocated on the heap.

c. Java Stack

Each thread has its own Java stack. It stores stack frames containing local variables, intermediate calculations, and method execution information.

d. PC Register (Program Counter Register)

Each JVM thread has its own PC register. It keeps track of the current JVM instruction being executed.

e. Native Method Stack

Supports execution of native methods written in languages such as C or C++.

3. Execution Engine

The Execution Engine executes the bytecode loaded into JVM.

It mainly contains:

  • Interpreter: Executes bytecode instructions one by one.
  • JIT Compiler: Compiles frequently executed bytecode into native machine code to improve performance.
  • Garbage Collector (GC): Automatically manages memory by reclaiming memory occupied by objects that are no longer reachable.

4. Java Native Interface (JNI)

JNI allows Java code to interact with native applications and libraries written in languages such as C and C++.

5. Native Libraries

These are platform-specific libraries that can be accessed through JNI when required.

Important Responsibilities of JVM

  • Loads Java class files.
  • Verifies bytecode.
  • Manages memory.
  • Executes Java bytecode.
  • Performs garbage collection.
  • Supports multithreading.
  • Helps provide platform independence.

4. What is JRE (Java Runtime Environment)?

JRE stands for Java Runtime Environment.

JRE provides the environment and libraries required to run Java applications.

In simple language:

JRE is used to run Java programs, not to develop or compile them.

It traditionally consists of:

  • JVM
  • Java class libraries
  • Supporting runtime files and components

Example

Suppose you have already developed and compiled a Java application.

Now, another person wants to run that application on their computer.

They need a compatible Java runtime environment.

The runtime provides the JVM and libraries required for execution.

Main Components of JRE

  1. JVM: Executes Java bytecode.
  2. Java Class Libraries: Provide ready-made functionality for strings, collections, input/output, networking, and more.
  3. Supporting Runtime Components: Help Java applications run correctly.

Note: In modern Java releases, Oracle and OpenJDK distributions commonly provide a modular runtime rather than a separate JRE download. The term JRE is still useful for understanding Java architecture.


5. What is JDK (Java Development Kit)?

JDK stands for Java Development Kit.

JDK is a software development kit that provides the tools required to develop, compile, debug, and run Java applications.

In simple language:

JDK is used by Java developers to write, compile, debug, and execute Java programs.

Main Components of JDK

1. JRE / Runtime Components

Provides the runtime environment needed to execute Java applications.

2. Java Compiler (javac)

Converts Java source code (.java) into bytecode (.class).

3. Java Launcher (java)

Starts the JVM and launches Java applications.

4. Java Debugger (jdb)

Helps developers debug Java applications.

5. Documentation Tool (javadoc)

Generates HTML documentation from Java source code and documentation comments.

6. Archive Tool (jar)

Creates and manages Java archive files (.jar).

Example

Suppose you want to create a Java application.

You need to:

  1. Write the Java source code.
  2. Compile it using javac.
  3. Run it using java.
  4. Debug it if an error occurs.

The JDK provides these development tools.


6. Difference Between JVM, JRE, and JDK

This is one of the most frequently asked questions in Java interviews.

Feature JVM JRE JDK
Full Form Java Virtual Machine Java Runtime Environment Java Development Kit
Main Purpose Execute bytecode Run Java applications Develop Java applications
Compiler No No Yes
JVM Included It is the JVM Yes Yes, in traditional JDK architecture
Java Libraries Uses runtime libraries Yes Yes
Development Tools No No Yes
Used By Runtime environment Application users Java developers

Easy Way to Remember

  • JVM: Executes Java bytecode.
  • JRE: Provides everything needed to run Java applications.
  • JDK: Provides everything needed to develop Java applications.

Relationship Between JVM, JRE, and JDK

          +-------------------------+
          |           JDK           |
          |                         |
          |  +-------------------+  |
          |  |        JRE        |  |
          |  |                   |  |
          |  |  +-------------+  |  |
          |  |  |     JVM     |  |  |
          |  |  +-------------+  |  |
          |  |                   |  |
          |  |   Libraries      |  |
          |  +-------------------+  |
          |                         |
          |  Compiler (javac)       |
          |  Debugger (jdb)         |
          |  Documentation (javadoc)|
          |  Other Development Tools|
          +-------------------------+

Note: This is a conceptual representation of the traditional Java architecture. Modern JDK distributions use modular components, so the JRE is not necessarily shipped as a separate directory or installation.


7. First Java Program – Hello World

Now let's write our first Java program.

Code

public class Hello {

    public static void main(String[] args) {

        System.out.println("Hello, World!");

    }
}

Output

Hello, World!

Explanation of the Code

1. public class Hello

  • public is an access modifier.
  • class is a keyword used to define a class.
  • Hello is the class name.

2. public static void main(String[] args)

This is the main method, which acts as the standard entry point for launching a Java application.

  • public: Allows the launcher to access the method.
  • static: Allows the method to be called without creating an object.
  • void: Means the method does not return a value.
  • main: The method name recognized by the Java launcher.
  • String[] args: Accepts command-line arguments.

3. System.out.println()

This statement displays text on the console.

  • System is a predefined Java class.
  • out is the standard output stream.
  • println() prints the given text and moves to the next line.

How to Compile and Run

First, save the program as Hello.java.

Open your terminal and execute:

javac Hello.java

This generates:

Hello.class

Now run the program:

java Hello

Output:

Hello, World!

8. Important Java Interview Questions

Q1. Who developed Java?

Answer: Java was developed by James Gosling and his team at Sun Microsystems. It was officially released in 1995.

Q2. Why is Java called platform independent?

Answer: Java source code is compiled into platform-independent bytecode. A compatible JVM on each operating system executes that bytecode.

Q3. What is JVM?

Answer: JVM stands for Java Virtual Machine. It is responsible for loading, verifying, and executing Java bytecode.

Q4. What is JRE?

Answer: JRE stands for Java Runtime Environment. It provides the runtime components and libraries needed to execute Java applications.

Q5. What is JDK?

Answer: JDK stands for Java Development Kit. It provides development tools such as the Java compiler, debugger, and runtime components.

Q6. What is bytecode?

Answer: Bytecode is the intermediate code generated by the Java compiler. It is stored in .class files and executed by the JVM.

Q7. What is the difference between JDK and JVM?

Answer: JDK provides tools for developing Java applications, while JVM executes Java bytecode.

Q8. Is Java fully object-oriented?

Answer: No. Java is not considered a purely object-oriented language because it supports primitive data types such as int, char, boolean, and double.

Q9. What is JIT Compiler?

Answer: JIT stands for Just-In-Time Compiler. It improves Java execution performance by compiling frequently executed bytecode into native machine code.

Q10. What is Garbage Collection in Java?

Answer: Garbage Collection is an automatic memory management process that reclaims memory occupied by objects that are no longer reachable.


9. Key Takeaways

Let's quickly revise what we learned:

  • Java is a high-level, object-oriented, platform-independent programming language.
  • Java was officially released in 1995.
  • Java source code is compiled into bytecode.
  • JVM executes Java bytecode.
  • JRE provides the environment required to run Java applications.
  • JDK provides tools required to develop Java applications.
  • JIT improves execution performance.
  • Garbage Collection automatically manages memory.

Remember:

JVM = Executes Bytecode

JRE = Runs Java Applications

JDK = Develops Java Applications


🚀 What's Next?

In the next tutorial, we will learn:

Java Installation and Environment Setup

  • How to install JDK 8.
  • How to configure Java environment variables.
  • How to check Java and javac versions.
  • How to write and execute your first Java program.

Keep Learning, Keep Practicing, and Keep Coding! ☕