Java Environment and Program Structure#
Lecture 2#
Java Programming (4343203)
Diploma in ICT - Semester IV
Gujarat Technological University
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
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:#e8f5e8layout: 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:#fff3e0layout: 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
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#
- Mark - Identify unused objects
- Sweep - Remove unused objects
- 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:#f3e5f5layout: 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#
- Download JDK installer for your OS
- Run installer with admin privileges
- Set JAVA_HOME environment variable
- Add Java bin directory to PATH
- 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 -versionlayout: 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#
• **Class declaration** with public modifier
• **Main method** - application entry point
• **Helper methods** for code organization
• **Method extraction** for reusability
• **System properties** for environment info
• **Command-line arguments** handling
• Exploring the Java runtime environment
• Professional code organization
• Real-world programming patterns
• **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 code2️⃣ Compile with javac
javac HelloWorld.java - Creates HelloWorld.class3️⃣ 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 HelloWorldlayout: 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:#ffebeelayout: 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.printlnSystem ≠ systemlayout: 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
layout: default#
Comprehensive Hands-On Lab - Professional Java Setup#
🚀 Lab Exercises - Progressive Complexity#
• Configure JAVA_HOME and PATH variables
• Verify installation: `java --version` & `javac --version`
• Document any issues encountered
• Include: name, enrollment, college, branch
• Add system information display
• Handle command-line arguments
• Execute with arguments: `java StudentInfo arg1 arg2`
• Debug common errors (syntax, runtime)
• Organize files in proper directory structure
• Create new Java project with proper structure
• Configure JDK in IDE settings
• Run and debug using IDE tools
📋 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#
🎓 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
layout: center class: text-center#
Questions & Discussion#
layout: default#
Java Development Environment Setup#
🔧 Step-by-Step Installation Guide#
Windows Installation#
- Download JDK - Oracle JDK or OpenJDK
- Run Installer - Follow installation wizard
- Set JAVA_HOME - System environment variable
- Update PATH - Add JDK bin directory
- Verify Installation -
java -version
Linux/macOS Installation#
- Package Manager -
sudo apt install openjdk-17-jdk - Homebrew (macOS) -
brew install openjdk@17 - Manual Download - Extract to /usr/local/
- Update Profile - .bashrc or .zshrc
- Verify Setup -
javac -version
layout: default#
IDE Selection and Setup#
🌟 IntelliJ IDEA
- • Intelligent code completion
- • Powerful debugging tools
- • Built-in version control
- • Spring Boot integration
🔮 Eclipse
- • Free and open source
- • Extensive plugin ecosystem
- • Good for beginners
- • Strong community support
🚀 VS Code
- • Lightweight and fast
- • Java Extension Pack
- • Git integration
- • Cross-platform
📝 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#
| Feature | Maven | Gradle | Ant |
|---|---|---|---|
| Configuration | XML-based | Groovy/Kotlin DSL | XML-based |
| Performance | Good | Excellent | Good |
| Learning Curve | Moderate | Steep | Easy |
| Ecosystem | Mature | Growing | Legacy |
layout: default#
Java Memory Management Deep Dive#
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:+HeapDumpOnOutOfMemoryErrorlayout: 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-openjdkPATH#
export PATH=$JAVA_HOME/bin:$PATHCLASSPATH#
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:$PATHIDE 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
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
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

