Skip to main content
  1. Resources/
  2. Study Materials/
  3. Information & Communication Technology Engineering/
  4. ICT Semester 4/
  5. Java Programming (4343203)/
  6. Java Programming Slidev Presentations/

Java Environment Setup & First Program - From Zero to Hero

·
Milav Dabgar
Author
Milav Dabgar
Experienced lecturer in the electrical and electronic manufacturing industry. Skilled in Embedded Systems, Image Processing, Data Science, MATLAB, Python, STM32. Strong education professional with a Master’s degree in Communication Systems Engineering from L.D. College of Engineering - Ahmedabad.
Table of Contents

Java Environment and Program Structure
#

Lecture 2
#

Java Programming (4343203)
Diploma in ICT - Semester IV
Gujarat Technological University

Press Space for next page

layout: default
#

Learning Objectives
#

By the end of this lecture, you will be able to:

  • 🔧 Understand the difference between JVM, JRE, and JDK
  • ⚙️ Explain the bytecode concept and its importance
  • 🗑️ Describe garbage collection in Java
  • 💻 Install and configure Java development environment
  • Write your first “Hello World” Java program
  • 🔄 Compile and execute Java programs

Let's set up our Java development environment! 🛠️

layout: center
#

Java Platform Components
#

graph TD
    A[Java Development Kit - JDK] --> B[Java Runtime Environment - JRE]
    A --> C[Development Tools<br/>javac, javadoc, jar, etc.]
    B --> D[Java Virtual Machine - JVM]
    B --> E[Java Libraries<br/>API Classes]
    D --> F[Class Loader]
    D --> G[Bytecode Verifier]
    D --> H[Just-In-Time Compiler]
    
    style A fill:#e3f2fd
    style B fill:#f3e5f5
    style D fill:#fff3e0
    style C fill:#e8f5e8
    style E fill:#e8f5e8
Remember: JDK ⊃ JRE ⊃ JVM

layout: two-cols
#

Java Virtual Machine (JVM)
#

🎯 What is JVM?
#

  • Runtime environment for Java bytecode
  • Platform-specific (Windows, Linux, macOS)
  • Converts bytecode to machine code
  • Manages memory automatically

🔧 Key Components
#

  • Class Loader - Loads .class files
  • Bytecode Verifier - Security checks
  • Interpreter - Executes bytecode
  • JIT Compiler - Optimizes performance

::right::

📊 JVM Architecture
#

graph TD
    A[.class files] --> B[Class Loader]
    B --> C[Method Area]
    B --> D[Heap Memory]
    C --> E[JIT Compiler]
    D --> F[Garbage Collector]
    E --> G[Native Method Interface]
    F --> H[Operating System]
    G --> H
    
    style A fill:#e1f5fe
    style C fill:#f3e5f5
    style D fill:#e8f5e8
    style F fill:#fff3e0
💡 Key Point: JVM makes Java platform independent!

layout: default
#

Java Runtime Environment (JRE)
#

🎯 What is JRE?
#

  • Runtime environment for Java applications
  • Includes JVM + Java libraries
  • Required to run Java programs
  • Cannot compile Java source code

📦 JRE Components
#

  • JVM - Virtual machine
  • Core Libraries - java.lang, java.util, etc.
  • Supporting Files - Property files, resources
  • Browser Plugins - For applets (deprecated)

🔍 Real-World Analogy

JRE is like a media player - it can play video files (.mp4) but cannot create them. Similarly, JRE can run Java programs (.class) but cannot compile them.


layout: default
#

Java Development Kit (JDK)
#

🛠️ What is JDK?
#

  • Complete development platform
  • Includes JRE + development tools
  • Required for development
  • Free and open source

📋 JDK Versions
#

  • Java 8 - LTS (Long Term Support)
  • Java 11 - LTS
  • Java 17 - LTS (Current)
  • Java 21 - Latest LTS

🔧 Development Tools
#

  • javac - Java compiler
  • java - Java interpreter
  • javadoc - Documentation generator
  • jar - Archive tool
  • jdb - Debugger
  • javap - Class file disassembler
💼 For Developers: Always install JDK, not just JRE, for development work!

layout: center
#

Bytecode Concept
#

sequenceDiagram
    participant SC as Source Code<br/>(.java)
    participant JC as Java Compiler<br/>(javac)
    participant BC as Bytecode<br/>(.class)
    participant JVM as Java Virtual Machine
    participant MC as Machine Code

    SC->>JC: HelloWorld.java
    JC->>BC: HelloWorld.class
    Note over BC: Platform Independent<br/>Intermediate Code
    BC->>JVM: Load bytecode
    JVM->>MC: Convert to native code
    Note over MC: Platform Specific<br/>Executable Code

✅ Advantages

  • • Platform independence
  • • Security verification
  • • Optimized execution
  • • Compact representation

⚠️ Characteristics

  • • Not human-readable
  • • Machine-independent
  • • JVM-specific format
  • • .class file extension

layout: default
#

Garbage Collection
#

🗑️ What is Garbage Collection?
#

  • Automatic memory management
  • Removes unused objects
  • Prevents memory leaks
  • Runs in background

🔄 GC Process
#

  1. Mark - Identify unused objects
  2. Sweep - Remove unused objects
  3. Compact - Defragment memory

💾 Memory Areas
#

graph TD
    A[JVM Memory] --> B[Heap Memory]
    A --> C[Non-Heap Memory]
    B --> D[Young Generation]
    B --> E[Old Generation]
    D --> F[Eden Space]
    D --> G[Survivor Spaces]
    C --> H[Method Area]
    C --> I[PC Registers]
    C --> J[Native Method Stack]
    
    style B fill:#e8f5e8
    style C fill:#fff3e0
    style D fill:#e1f5fe
    style E fill:#f3e5f5
🎯 Benefit: Java developers don't need to manually manage memory like in C/C++!

layout: default
#

Installing Java JDK
#

🔽 Download Sources
#

🏢 Oracle JDK

  • • Commercial license
  • • oracle.com/java
  • • Production support
  • • Latest features

🆓 OpenJDK

  • • Open source
  • • openjdk.java.net
  • • Community support
  • • Free for all use

⚙️ Installation Steps
#

  1. Download JDK installer for your OS
  2. Run installer with admin privileges
  3. Set JAVA_HOME environment variable
  4. Add Java bin directory to PATH
  5. Verify installation with java -version

layout: default
#

Setting Environment Variables
#

🪟 Windows Setup
#

# Set JAVA_HOME
JAVA_HOME = C:\Program Files\Java\jdk-17

# Add to PATH
PATH = %JAVA_HOME%\bin;%PATH%

# Verify installation
java -version
javac -version

🐧 Linux/macOS Setup
#

# Add to ~/.bashrc or ~/.zshrc
export JAVA_HOME=/usr/lib/jvm/java-17-openjdk
export PATH=$JAVA_HOME/bin:$PATH

# Reload configuration
source ~/.bashrc

# Verify installation
java -version
javac -version
⚠️ Important: Make sure JAVA_HOME points to JDK, not JRE!

layout: default
#

Your First Java Program - Professional Deep Dive
#

🎯 The Professional Hello World
#

// HelloWorld.java - Professional Version
public class HelloWorld {
    
    public static void main(String[] args) {
        
        System.out.println("Hello, World!");
        System.out.println("Welcome to Java Programming!");
        
        // Professional additions
        displayProgramInfo();
        
        // Command line arguments demo
        if (args.length > 0) {
            System.out.println("Arguments received: " + 
                             String.join(", ", args));
        }
    }
    
    /**
     * Displays program metadata - professional practice
     */
    private static void displayProgramInfo() {
        System.out.println("\n=== Program Information ===");
        System.out.println("Java Version: " + 
                         System.getProperty("java.version"));
        System.out.println("Operating System: " + 
                         System.getProperty("os.name"));
        System.out.println("User: " + 
                         System.getProperty("user.name"));
    }
}

🔍 Professional Code Analysis
#

🏗️ Structure Elements:
• **Package declaration** (implicit default)
• **Class declaration** with public modifier
• **Main method** - application entry point
• **Helper methods** for code organization
💡 Best Practices Applied:
• **Javadoc comments** for documentation
• **Method extraction** for reusability
• **System properties** for environment info
• **Command-line arguments** handling
🎯 Learning Goals:
• Understanding method signatures
• Exploring the Java runtime environment
• Professional code organization
• Real-world programming patterns
⚠️ Critical Rules:
• **Filename = Class name** (case sensitive)
• **One public class per file**
• **main method signature** must be exact
• **Case sensitivity** throughout Java

🚀 From Beginner to Professional in One Program

This isn't just "Hello World" - it's your first step toward writing enterprise-grade Java applications that real companies deploy to serve millions of users!


layout: default
#

Compilation and Execution
#

⚙️ Step-by-Step Process
#

1️⃣ Write Source Code

HelloWorld.java - Contains human-readable Java code

2️⃣ Compile with javac

javac HelloWorld.java - Creates HelloWorld.class

3️⃣ Execute with java

java HelloWorld - Runs the bytecode

🖥️ Command Line Demo
#

# Navigate to source directory
cd /path/to/your/java/files

# Compile the program
javac HelloWorld.java

# Run the program
java HelloWorld

layout: default
#

Complete Development Workflow
#

flowchart TD
    A[Write Java Code<br/>HelloWorld.java] --> B[Compile with javac<br/>javac HelloWorld.java]
    B --> C{Compilation<br/>Successful?}
    C -->|No| D[Fix Syntax Errors]
    D --> A
    C -->|Yes| E[Bytecode Generated<br/>HelloWorld.class]
    E --> F[Execute with java<br/>java HelloWorld]
    F --> G{Runtime<br/>Errors?}
    G -->|Yes| H[Debug & Fix Code]
    H --> A
    G -->|No| I[Program Output<br/>Hello, World!]
    
    style A fill:#e1f5fe
    style E fill:#fff3e0
    style I fill:#e8f5e8
    style D fill:#ffebee
    style H fill:#ffebee

layout: default
#

Common Compilation Errors
#

❌ Syntax Errors
#

// Missing semicolon
System.out.println("Hello World")

// Mismatched braces
public class Test {
    public static void main(String[] args) {
        System.out.println("Hello");
    // Missing closing brace

❌ Common Mistakes
#

// Wrong class name
public class hello {  // Should be Hello
    // ...
}

// Wrong main method signature
public void main(String[] args) {
    // Should be: public static void main
}

// Case sensitivity
system.out.println("Hello");
// Should be: System.out.println
⚠️ Remember: Java is case-sensitive! Systemsystem

layout: default
#

IDE vs Command Line
#

🖥️ Command Line Development
#

Advantages:

  • Direct control over compilation
  • Better understanding of process
  • Lightweight and fast
  • Good for learning

Disadvantages:

  • Manual error checking
  • No syntax highlighting
  • No auto-completion
  • More typing required

💻 IDE Development
#

Popular IDEs:

  • IntelliJ IDEA (Most popular)
  • Eclipse (Free and powerful)
  • NetBeans (Oracle supported)
  • VS Code (Lightweight)

Benefits:

  • Syntax highlighting
  • Auto-completion
  • Error detection
  • Debugging tools
  • Project management
🎯 Recommendation: Start with command line to understand basics, then move to IDE for productivity!

layout: default
#

Comprehensive Hands-On Lab - Professional Java Setup
#

🚀 Lab Exercises - Progressive Complexity
#

🎯 **Level 1: Environment Mastery**
• Install JDK 21 LTS on your system
• Configure JAVA_HOME and PATH variables
• Verify installation: `java --version` & `javac --version`
• Document any issues encountered
Success Criteria: Both commands return version 21.x.x
🎯 **Level 2: First Professional Program**
• Create StudentInfo.java with proper structure
• Include: name, enrollment, college, branch
• Add system information display
• Handle command-line arguments
Challenge: Make it interactive with Scanner input
🎯 **Level 3: Development Workflow**
• Master compilation: `javac *.java`
• Execute with arguments: `java StudentInfo arg1 arg2`
• Debug common errors (syntax, runtime)
• Organize files in proper directory structure
Pro Tip: Use package structure: com.gtu.ict.studentname
🎯 **Level 4: IDE Integration**
• Install IntelliJ IDEA Community or VS Code
• Create new Java project with proper structure
• Configure JDK in IDE settings
• Run and debug using IDE tools
Bonus: Set up code formatting and style checking

📋 Expected Professional Output
#

// Expected when running: java StudentInfo "GTU" "ICT"
=== Student Information System ===
Name: Raj Patel
Enrollment: 21ICT001
College: Government Polytechnic
Branch: Information & Communication Technology

=== System Information ===
Java Version: 21.0.1
Operating System: Windows 11
User: raj.patel
Working Directory: C:\JavaProjects\GTU

=== Command Line Arguments ===
Arguments received: GTU, ICT
Argument count: 2

=== Professional Features ===
 Proper error handling implemented
 Input validation completed
 Professional code structure
 Documentation standards followed

Thank you for using Student Info System!
Program executed successfully in 0.045 seconds.

🏆 Mastery Checklist
#

JDK installed and configured correctly
Environment variables set properly
Compilation and execution mastered
Professional code structure implemented
IDE setup and configuration completed
Error handling and debugging practiced

🎓 Congratulations! You're Now a Java Developer!

You've successfully set up a professional Java development environment and created your first application.
You're ready to tackle more complex programming challenges and build real-world software solutions!


layout: default
#

Troubleshooting Common Issues
#

❌ 'javac' is not recognized

Solution: Check JAVA_HOME and PATH environment variables

❌ Could not find or load main class

Solution: Ensure class name matches filename exactly

❌ Public class must be in file named

Solution: Rename file to match public class name

❌ Cannot find symbol

Solution: Check spelling and case sensitivity


layout: center class: text-center
#

Summary
#

📖 What We Learned

  • • JVM, JRE, and JDK concepts
  • • Bytecode and its importance
  • • Garbage collection basics
  • • Java environment setup
  • • First Java program creation

🎯 Next Steps

  • • Java program structure details
  • • Types of comments in Java
  • • Coding conventions
  • • More complex programs
  • • Debugging techniques
You've written your first Java program! 🎉

layout: center class: text-center
#

Questions & Discussion
#

Any questions about Java environment setup or your first program?
Next lecture: **Java Program Structure & Comments**

layout: default
#

Java Development Environment Setup
#

🔧 Step-by-Step Installation Guide
#

Windows Installation
#

  1. Download JDK - Oracle JDK or OpenJDK
  2. Run Installer - Follow installation wizard
  3. Set JAVA_HOME - System environment variable
  4. Update PATH - Add JDK bin directory
  5. Verify Installation - java -version

Linux/macOS Installation
#

  1. Package Manager - sudo apt install openjdk-17-jdk
  2. Homebrew (macOS) - brew install openjdk@17
  3. Manual Download - Extract to /usr/local/
  4. Update Profile - .bashrc or .zshrc
  5. Verify Setup - javac -version
💡 Tip: Use OpenJDK for free, production-ready Java development!

layout: default
#

IDE Selection and Setup
#

🌟 IntelliJ IDEA

  • • Intelligent code completion
  • • Powerful debugging tools
  • • Built-in version control
  • • Spring Boot integration
Best for professionals

🔮 Eclipse

  • • Free and open source
  • • Extensive plugin ecosystem
  • • Good for beginners
  • • Strong community support
Best for learning

🚀 VS Code

  • • Lightweight and fast
  • • Java Extension Pack
  • • Git integration
  • • Cross-platform
Best for simplicity

📝 Alternative Text Editors
#

  • Notepad++ (Windows) - Simple syntax highlighting
  • Sublime Text - Fast with Java packages
  • Atom - GitHub’s hackable editor
  • Vim/Emacs - For terminal enthusiasts

layout: default
#

Java Build Tools Overview
#

🔨 Maven
#

<project>
  <groupId>com.example</groupId>
  <artifactId>my-app</artifactId>
  <version>1.0</version>
  
  <properties>
    <maven.compiler.source>17</maven.compiler.source>
    <maven.compiler.target>17</maven.compiler.target>
  </properties>
  
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.13.2</version>
    </dependency>
  </dependencies>
</project>

⚡ Gradle
#

plugins {
    id 'java'
    id 'application'
}

java {
    toolchain {
        languageVersion = JavaLanguageVersion.of(17)
    }
}

dependencies {
    testImplementation 'junit:junit:4.13.2'
}

application {
    mainClass = 'com.example.Main'
}

🏗️ Build Tool Comparison
#

FeatureMavenGradleAnt
ConfigurationXML-basedGroovy/Kotlin DSLXML-based
PerformanceGoodExcellentGood
Learning CurveModerateSteepEasy
EcosystemMatureGrowingLegacy

layout: default
#

Java Memory Management Deep Dive
#

🧠 Memory Areas
#

Heap Memory
#

  • Young Generation - New objects
  • Old Generation - Long-lived objects
  • Metaspace - Class metadata (Java 8+)

Non-Heap Memory
#

  • Method Area - Class-level data
  • Code Cache - Compiled native code
  • Direct Memory - NIO buffers

🗑️ Garbage Collection Types
#

Serial GC
#

  • Single-threaded
  • Good for small applications

Parallel GC
#

  • Multi-threaded
  • Default for server applications

G1GC
#

  • Low-latency collector
  • Good for large heap sizes

ZGC/Shenandoah
#

  • Ultra-low latency
  • Concurrent collection
⚡ Performance Tip: Monitor heap usage with `jconsole` or `jvisualvm` tools!

layout: default
#

Advanced JVM Features
#

🚀 Just-In-Time (JIT) Compilation
#

  • Interpretation - Initial execution
  • C1 Compiler - Client compiler (fast compilation)
  • C2 Compiler - Server compiler (aggressive optimization)
  • Tiered Compilation - Best of both worlds
  • Profile-Guided Optimization - Runtime feedback
  • Method Inlining - Eliminate method call overhead

🔧 JVM Tuning Parameters
#

# Heap size configuration
-Xms512m -Xmx2g

# Garbage collection
-XX:+UseG1GC
-XX:MaxGCPauseMillis=200

# JIT compilation
-XX:+TieredCompilation
-XX:CompileThreshold=10000

# Monitoring and debugging
-XX:+PrintGC
-XX:+HeapDumpOnOutOfMemoryError
🎯 Production Tip: Always profile before tuning JVM parameters!

layout: default
#

Java Development Best Practices
#

📋 Project Structure Best Practices
#

my-java-project/
├── src/
│   ├── main/
│   │   ├── java/
│   │   │   └── com/company/project/
│   │   │       ├── Main.java
│   │   │       ├── model/
│   │   │       ├── service/
│   │   │       └── util/
│   │   └── resources/
│   │       ├── application.properties
│   │       └── log4j2.xml
│   └── test/
│       └── java/
│           └── com/company/project/
├── target/ (Maven) or build/ (Gradle)
├── pom.xml (Maven) or build.gradle
└── README.md

✅ Do's

  • • Follow package naming conventions
  • • Use meaningful class and method names
  • • Keep classes focused and small
  • • Write unit tests for all methods
  • • Use version control (Git)

❌ Don'ts

  • • Don't use default package
  • • Avoid magic numbers and strings
  • • Don't ignore compiler warnings
  • • Avoid deep inheritance hierarchies
  • • Don't commit compiled .class files

layout: default
#

Environment Variables and Configuration
#

🌍 Essential Environment Variables
#

JAVA_HOME
#

export JAVA_HOME=/usr/lib/jvm/java-17-openjdk

PATH
#

export PATH=$JAVA_HOME/bin:$PATH

CLASSPATH
#

export CLASSPATH=.:$JAVA_HOME/lib/*

JVM Options
#

export JAVA_OPTS="-Xms512m -Xmx1g"

⚙️ Configuration Files
#

Windows (System Variables)
#

  • Control Panel → System → Advanced
  • Environment Variables button
  • Add or modify system variables

Linux/macOS (~/.bashrc)
#

# Java configuration
export JAVA_HOME=/usr/lib/jvm/java-17
export PATH=$JAVA_HOME/bin:$PATH
export MAVEN_HOME=/opt/maven
export PATH=$MAVEN_HOME/bin:$PATH

IDE Configuration
#

  • Project JDK settings
  • Compiler compliance level
  • Build path configuration

layout: default
#

Troubleshooting Common Issues
#

🚨 Installation Problems
#

“java command not found”
#

  • Check JAVA_HOME setting
  • Verify PATH configuration
  • Restart terminal/IDE

“javac not recognized”
#

  • Install JDK (not just JRE)
  • Add JDK/bin to PATH
  • Check system vs user variables

Version conflicts
#

  • Use update-alternatives (Linux)
  • Check multiple Java installations
  • Set correct JAVA_HOME

🔧 Runtime Issues
#

OutOfMemoryError
#

  • Increase heap size (-Xmx)
  • Check for memory leaks
  • Profile application memory

ClassNotFoundException
#

  • Check CLASSPATH setting
  • Verify JAR file locations
  • Check package declarations

UnsupportedClassVersionError
#

  • Compile with correct JDK version
  • Match runtime Java version
  • Check bytecode compatibility
🔍 Debugging Tip: Use `java -version` and `javac -version` to verify your installation!

layout: default
#

Performance Monitoring Tools
#

🔍 JConsole

  • • Built-in JVM monitoring
  • • Memory usage tracking
  • • Thread analysis
  • • MBean inspection
jconsole

📊 VisualVM

  • • Profiling capabilities
  • • Heap dump analysis
  • • CPU profiling
  • • Plugin ecosystem
jvisualvm

⚡ JProfiler

  • • Commercial profiler
  • • Advanced analysis
  • • Database profiling
  • • Memory leak detection
jprofiler

📈 Key Metrics to Monitor
#

  • Heap utilization - Memory usage patterns
  • GC frequency - Collection overhead
  • Thread states - Concurrency issues
  • CPU usage - Performance bottlenecks
  • Class loading - Startup optimization
📊 Best Practice: Establish baseline metrics before optimizing performance!

layout: center class: text-center
#

Summary & Next Steps
#

📖 What We Covered

  • • JVM, JRE, JDK architecture
  • • Bytecode and platform independence
  • • Development environment setup
  • • IDE selection and configuration
  • • Build tools and project structure
  • • Memory management concepts
  • • Performance monitoring tools

🎯 Ready for Next Lecture

  • • Java development environment working
  • • Understanding of compilation process
  • • Knowledge of memory management
  • • Familiarity with development tools
  • • Project structure best practices
  • • Basic troubleshooting skills
  • • Performance monitoring awareness
Next: Java Program Structure and Comments! 📝
Great job setting up Java! 👏