High Performance with Java: Discover strategies and best practices to develop high performance Java applications
()
Dr. Edward Lavieri Jr.
Dr. Edward Lavieri Jr. is a seasoned software developer and senior member of the Institute of Electrical and Electronic Engineers (IEEE). He has developed software for over 30 years and primarily focused on Java for over 20 years. His experience includes both military information systems and the software design and development industry. Dr. Lavieri currently serves as a university dean for a college of computer science and a school of information technology as well as the chief academic officer of a programming bootcamp organization, all part of a regionally accredited US university. He holds a doctorate degree in computer science and a master's degree in information systems, along with other degrees and certificates.
Related to High Performance with Java
Related ebooks
Java Performance Optimization: From Basics to Expert Proficiency Rating: 0 out of 5 stars0 ratingsMastering Core Java:Advanced Techniques and Tricks Rating: 0 out of 5 stars0 ratingsMastering the Craft of JAVA Programming: Unraveling the Secrets of Expert-Level Programming Rating: 0 out of 5 stars0 ratingsJava Performance Optimization: Expert Strategies for Enhancing JVM Efficiency Rating: 0 out of 5 stars0 ratingsMastering Edge Computing: Scalable Application Development with Azure Rating: 0 out of 5 stars0 ratingsMastering Advanced Object-Oriented Programming in Java: Unlock the Secrets of Expert-Level Skills Rating: 0 out of 5 stars0 ratingsEnhancing Java EE Applications: Strategies for Performance and Scalability Rating: 0 out of 5 stars0 ratingsMastering the Java Virtual Machine: An in-depth guide to JVM internals and performance optimization Rating: 0 out of 5 stars0 ratingsJava: Tips and Tricks to Programming Code with Java Rating: 0 out of 5 stars0 ratingsEssential Techniques for Java Programming with BlueJ: Definitive Reference for Developers and Engineers Rating: 0 out of 5 stars0 ratingsJava Concurrency and Parallelism: Master advanced Java techniques for cloud-based applications through concurrency and parallelism Rating: 0 out of 5 stars0 ratingsJava Concurrency and Multithreading: Unlock the Secrets of Expert-Level Skills Rating: 0 out of 5 stars0 ratingsJava Full Stack Interview Questions: Your Ultimate Preparation Guide Rating: 0 out of 5 stars0 ratingsIntelliJ IDEA Workflow and Productivity Guide: Definitive Reference for Developers and Engineers Rating: 0 out of 5 stars0 ratingsEssential Design Patterns in Java: Mastering Core Concepts and Practical Applications Rating: 0 out of 5 stars0 ratingsOCP Oracle Certified Professional Java SE 11 Programmer I Study Guide: Exam 1Z0-815 Rating: 5 out of 5 stars5/5Mastering Java Concurrency: Threads, Synchronization, and Parallel Processing Rating: 0 out of 5 stars0 ratingsMastering Efficient Memory Management in Java: Unlock the Secrets of Expert-Level Skills Rating: 0 out of 5 stars0 ratingsC++ VS JAVA A PERFORMANCE DEEPDIVE: Unraveling the Performance Characteristics of C++ and Java for High-Performance Computing Rating: 0 out of 5 stars0 ratingsASP.NET Core 1.0 High Performance Rating: 0 out of 5 stars0 ratingsAdvanced Java Rating: 0 out of 5 stars0 ratingsMastering Core Java: From Basics to Expert Proficiency Rating: 0 out of 5 stars0 ratingsJava SE 21 Developer Study Guide Rating: 5 out of 5 stars5/5Core Java Rating: 0 out of 5 stars0 ratingsJava: Tips and Tricks to Programming Code with Java: Java Computer Programming, #2 Rating: 0 out of 5 stars0 ratingsThe Ultimate Guide to Java Frameworks: Building Robust and Scalable Web Applications Rating: 0 out of 5 stars0 ratingsSystems Programming with C# and .NET: Building robust system solutions with C# 12 and .NET 8 Rating: 0 out of 5 stars0 ratingsPerformance Optimization Made Simple: A Practical Guide to Programming Rating: 0 out of 5 stars0 ratingsModern Programming in Java Rating: 0 out of 5 stars0 ratings
Programming For You
Python: For Beginners A Crash Course Guide To Learn Python in 1 Week Rating: 4 out of 5 stars4/5Python: Learn Python in 24 Hours Rating: 4 out of 5 stars4/5Coding All-in-One For Dummies Rating: 4 out of 5 stars4/5JavaScript All-in-One For Dummies Rating: 5 out of 5 stars5/5Excel : The Ultimate Comprehensive Step-By-Step Guide to the Basics of Excel Programming: 1 Rating: 5 out of 5 stars5/5Python Programming : How to Code Python Fast In Just 24 Hours With 7 Simple Steps Rating: 4 out of 5 stars4/5Linux: Learn in 24 Hours Rating: 5 out of 5 stars5/5SQL QuickStart Guide: The Simplified Beginner's Guide to Managing, Analyzing, and Manipulating Data With SQL Rating: 4 out of 5 stars4/5Python Data Structures and Algorithms Rating: 5 out of 5 stars5/5Microsoft Azure For Dummies Rating: 0 out of 5 stars0 ratingsBeginning Programming with Python For Dummies Rating: 3 out of 5 stars3/5Learn SQL in 24 Hours Rating: 5 out of 5 stars5/5Beginning Programming with C++ For Dummies Rating: 4 out of 5 stars4/5Excel 101: A Beginner's & Intermediate's Guide for Mastering the Quintessence of Microsoft Excel (2010-2019 & 365) in no time! Rating: 0 out of 5 stars0 ratingsPYTHON PROGRAMMING Rating: 4 out of 5 stars4/5Learn to Code. Get a Job. The Ultimate Guide to Learning and Getting Hired as a Developer. Rating: 5 out of 5 stars5/5SQL All-in-One For Dummies Rating: 3 out of 5 stars3/5Learn PowerShell in a Month of Lunches, Fourth Edition: Covers Windows, Linux, and macOS Rating: 5 out of 5 stars5/5Coding All-in-One For Dummies Rating: 0 out of 5 stars0 ratingsA Slackers Guide to Coding with Python: Ultimate Beginners Guide to Learning Python Quick Rating: 1 out of 5 stars1/5Linux Basics for Hackers: Getting Started with Networking, Scripting, and Security in Kali Rating: 3 out of 5 stars3/5
Reviews for High Performance with Java
0 ratings0 reviews
Book preview
High Performance with Java - Dr. Edward Lavieri Jr.
High Performance with Java
Copyright © 2024 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
Group Product Manager: Kunal Sawant
Publishing Product Manager: Teny Thomas
Book Project Manager: Manisha Singh
Senior Editor: Kinnari Chohan
Technical Editor: Vidhisha Patidar
Copy Editor: Safis Editing
Proofreader: Kinnari Chohan
Indexer: Subalakshmi Govindhan
Production Designer: Aparna Bhagat
DevRel Marketing Coordinator: Sonia Chauhan
First published: July 2024
Production reference: 1080724
Published by Packt Publishing Ltd.
Grosvenor House
11 St Paul’s Square
Birmingham
B3 1RB, UK
ISBN 978-1-83546-973-6
www.packtpub.com
To Brenda, my wonderful wife, whose unwavering support and patience during countless evenings and weekends made this book possible. And to KuBougie, our beloved Hemmingway cat, who brought joy and comfort to our home, helping to heal the loss of our dear dogs, Muzz and Java.
Thank you both!
Contributors
About the author
Dr. Edward Lavieri Jr. is a seasoned software developer and senior member of the Institute of Electrical and Electronic Engineers (IEEE). He has developed software for over 30 years and primarily focused on Java for over 20 years. His experience includes both military information systems and the software design and development industry. Dr. Lavieri currently serves as a university dean for a college of computer science and a school of information technology as well as the chief academic officer of a programming bootcamp organization, all part of a regionally accredited US university. He holds a doctorate degree in computer science and a master’s degree in information systems, along with other degrees and certificates.
I want to thank my wife, Brenda, for her unwavering support, and the entire Packt team, with special gratitude to Teny, Manisha, Kinnari, and Vidhisha.
About the reviewer
Aristides Villarreal is a Panamanian Java Champion and a member of the Apache Project Management Committee (PMC) for the NetBeans Project. He is also a Jakarta EE Ambassador and a specialist in NoSQL, Jakarta EE, and Eclipse MicroProfile.
Pallavi Sharma is a versatile professional with 18 years of experience, having worked as an individual contributor, project manager, Scrum Master, and coach. She is the Founder of 5 Elements Learning and the author of five books on Selenium. As a recognized committer to the Selenium Project, Pallavi actively participates in international testing conferences as a reviewer, judge, organizer, and speaker. She holds various certifications in her field. Outside of work, Pallavi enjoys writing, traveling, and nature watching. She is dedicated to giving back to society, guided by the principle of #bekind.
Table of Contents
Preface
Part 1: Code Optimization
1
Peeking Inside the Java Virtual Machine
Technical requirements
How the JVM works
More options with javap
Garbage collection
The garbage collection process
Garbage collection algorithms
Garbage collection optimizations
JIT compiler optimizations
Interpretation
AOT compilation
JIT compilation
Summary
2
Data Structures
Technical requirements
Improving performance with lists
Why use lists?
Common list implementations
High performance with lists
Improving performance with arrays
Array characteristics
Implementing arrays
High performance with arrays
Improving performance with trees
Examples of a tree structure
High-performance considerations
Improving performance with stacks and queues
Implementing stacks
Improving the performance of stacks
Implementing queues
Improving the performance of queues
Improving performance with advanced data structures
Hash tables
Graphs
Trie
Heap
Quad trees
Octrees
Bitsets
Ropes
Summary
3
Optimizing Loops
Technical requirements
Types of loops
A loop’s impact on performance
Loop optimization basics
Loop unrolling
Testing loops for performance
Profiling tools and methodology
Benchmarking and testing strategies
Case studies and examples
Nested loops
Introduction to nested loops
Loop fusion in nested loops
Parallelizing nested loops
Nested loop vectorization
Summary
4
Java Object Pooling
Technical requirements
Jumping into the object pool
Database example
Implementing an object pool in Java
Advantages and disadvantages of object pooling
Advantages
Disadvantages
Performance testing
Designing a performance test
Implementing a performance test
Analyzing the results
Summary
5
Algorithm Efficiencies
Technical requirements
Algorithm selection
Selection process
Case study
Evolving trends
Low time complexity
Strategies for reducing time complexity
Common pitfalls
Testing algorithms for efficiency
Importance of testing
Preparing for algorithm efficiency testing
Conducting the tests
Post-test actions
Summary
Part 2: Memory Optimization and I/O Operations
6
Strategic Object Creation and Immutability
Technical requirements
Minimizing object creation
Java object life cycle
Memory
Object pooling
Initialization approaches
Overhead reduction
Object immutability
Immutability overview
Best practices
Performance advantages
Custom classes
String classes
Garbage collection
Garbage collection implications
Object cloning
Design patterns
Singleton pattern
Factory pattern
Summary
7
String Objects
Technical requirements
Proper string pooling
String interning
Best practices
Code examples
String pooling for database queries
Lazy initialization
Code examples
Best practices
Additional string operation strategies
Concatenation
Regular expressions
Large text files
Summary
8
Memory Leaks
Technical requirements
Proper referencing
An introduction to references
Memory leak identification
Memory leak avoidance strategies
Listeners and loaders
Event listeners
Class loaders
Caching and threads
Caching strategies
Thread management
Java concurrency utilities
Summary
Part 3: Concurrency and Networking
9
Concurrency Strategies and Models
Technical requirements
Concurrency models
Thread-based model
The message passing model
The Reactive model
Multithreading
Thread life cycles
Multithreading best practices
Synchronization
Non-blocking algorithms
Summary
10
Connection Pooling
Technical requirements
Connection pooling concepts
Advantages of connection pooling
Challenges of connection pooling
Implementing connection pools
Connection pool libraries
Setting up a connection pool
Integrating connection pools
Monitoring connection pools
Best practices with connection pools
Connection pool sizing
Handling connection leaks
Connection pool security
Advanced topics
Summary
11
Hypertext Transfer Protocols
Technical requirements
Introduction to HTTP
HTTP core components
Java and HTTP
Java web applications
Java web application architecture
Key technologies
Steps for creating a simple Java web application
Using HTTP in Java
API integration
Security considerations
Performance optimization
Summary
Part 4: Frameworks, Libraries, and Profiling
12
Frameworks for Optimization
Technical requirements
Asynchronous input/output
Advantages and best practices
Implementing AIO
Buffered input/output
Advantages and best practices
Implementing buffered input/output
Batch operations
Advantages and best practices
Implementing batch operations
Frameworks for microservices
Advantages and best practices
Implementing microservices frameworks
Frameworks for cloud-native applications
Advantages and best practices
Implementing a cloud-native application
Case studies and performance analysis
Case studies
Performance analysis
Summary
13
Performance-Focused Libraries
Technical requirements
Java Microbenchmark Harness
Key features
Adding JMH libraries to your IDE
Writing benchmarks
Running benchmarks
Analyzing results
Use cases
Netty
Core features
Performance considerations
Implementation
FasterXML Jackson
Core features
Performance considerations
Implementation
Other notable libraries
Agrona
Eclipse Collections
Guava
Summary
14
Profiling Tools
An introduction to profiling tools
The importance of profiling in performance tuning
Types of profiling tools and their uses
Profilers bundled in the JDK
JVisualVM
JMC
IDE-embedded profilers
The IntelliJ IDEA profiler
Eclipse’s Test and Performance Tools Platform
NetBeans Profiler
Additional profilers
YourKit Java Profiler
JProfiler
VisualVM plugins and extensions
A comparative analysis of profiling tools
Performance overhead
Accuracy
Ease of use
Integration
Cost and licensing considerations
The best use cases for each tool
Scoring our profiling tools
Practical profiling strategies
Identifying performance bottlenecks
Profiling in development versus production
Continuous profiling
Case studies
Case study 1 – profiling a large enterprise application
Case study 2 – performance tuning in a microservices architecture
Case study 3 – profiling and optimizing a high-throughput system
Future trends in Java profiling
Advances in profiling tools
Integration with AI and machine learning
Emerging standards and best practices
Summary
Part 5: Advanced Topics
15
Optimizing Your Database and SQL Queries
Database design
Schema principles
Indexing
Partitioning and sharding
Query optimizations
Query execution
Best practices
Advanced SQL techniques
Additional strategies
Fine-tuning
Database performance monitoring
Database maintenance
Case studies
Case study 1
Case study 2
Case study 3
Summary
16
Code Monitoring and Maintenance
APM tools
APM tool overview
APM tool key features
Popular APM tools
APM tool best practices
Code reviews
Best practices
Peer review processes
Common pitfalls
Logging
Best practices
Logging frameworks
Analyzing log data
Monitoring and alerting
Monitoring system setup
Alert configuration
Alert and incident response
Maintenance strategies
Documentation and knowledge management
Refactoring strategies
Legacy code
Summary
17
Unit and Performance Testing
Technical requirements
Unit testing
Frameworks
Writing unit tests
Best practices
Pitfalls
TDD
Performance testing
Types and tools
Overarching strategies
Integrating unit and performance testing
Summary
18
Leveraging Artificial Intelligence (AI) for High-Performance Java Applications
Technical requirements
Introduction to AI in Java
AI’s relevance to high-performance Java applications
Current trends
Future directions
AI for performance optimization
Code optimization and performance tuning
Predicting performance bottlenecks
Abbreviated case study
AI-powered monitoring and maintenance
Anomaly detection
AI-based logging
Maintenance strategies
AI integration
Best practices
Ethical and practical considerations
Summary
Epilogue
Index
Other Books You May Enjoy
Preface
Java remains one of the most popular and powerful programming languages in the world. Since its inception, it has empowered developers to create robust, high-performance applications across various domains. This book, High Performance with Java, delves into the intricate details of optimizing Java applications for peak performance. From understanding the fundamentals of the Java virtual machine (JVM) to leveraging advanced profiling tools, this book is a comprehensive guide for anyone looking to enhance their Java development skills and deliver high-performance solutions.
Who this book is for
This book is intended for Java developers who have a foundational understanding of the language and are looking to deepen their knowledge of performance optimization. Whether you are a seasoned developer or a mid-level programmer, this book can provide valuable insights and practical techniques to improve the performance of your Java applications. A basic familiarity with Java development tools and the Java Development Kit (JDK) is assumed.
What this book covers
Chapter 1
, Peeking Inside the Java Virtual Machine, provides an in-depth look at the JVM, exploring how it works, including garbage collection and just-in-time (JIT) compiler optimizations to maximize application performance.
Chapter 2
, Data Structures, allows you to learn about the impact of different data structures on performance and how to select and implement the most efficient ones for your applications.
Chapter 3
, Optimizing Loops, covers techniques for optimizing loops, a fundamental construct in programming, to avoid bottlenecks and improve runtime performance.
Chapter 4
, Java Object Pooling, dives into the concept of object pooling in Java and how to achieve high performance with them in your Java applications.
Chapter 5
, Algorithm Efficiencies, helps you learn how to choose the right algorithm for any given requirement.
Chapter 6
, Strategic Object Creation and Immutability, presents information and examples on how to make objects immutable and explains why you should consider it.
Chapter 7
, String Objects, focuses on the efficient use of string objects in our Java applications.
Chapter 8
, Memory Leaks, provides techniques, design patterns, coding examples, and best practices to avoid memory leaks.
Chapter 9
, Concurrency Strategies and Models, provides foundational information on concurrency concepts and provides hands-on opportunities to implement concurrency in Java programs.
Chapter 10
, Connection Pooling, covers the concept of connection pooling, providing fundamental principles, implementation approaches, and examples.
Chapter 11
, Hypertext Transfer Protocols, covers the foundational protocol used for information exchange on the web.
Chapter 12
, Frameworks for Optimization, provides a foundational understanding of key frameworks to optimize Java applications.
Chapter 13
, Performance-Focused Libraries, takes an in-depth look at libraries such as JMH, Netty, and Jackson, and how they can be used to enhance the performance of your Java applications.
Chapter 14
, Profiling Tools, explores various profiling tools, both bundled in the JDK and additional ones, to monitor and improve the performance of your Java applications.
Chapter 15
, Optimizing Your Databases with SQL Queries, demonstrates how to optimize SQL queries and manage databases to ensure high performance.
Chapter 16
, Code Monitoring and Maintenance, examines the importance of code monitoring and maintenance, including the use of application performance management (APM) tools, code reviews, and logging.
Chapter 17
, Unit and Performance Testing, covers strategies for effective unit and performance testing to ensure your applications meet performance requirements.
Chapter 18
, Leveraging Artificial Intelligence (AI) for High-Performance Java Applications, explores how AI can be integrated into Java applications for performance enhancements, including predictions, forecasting, and content pre-processing.
To get the most out of this book
To fully benefit from the content in this book, readers should have a solid understanding of Java programming basics and be comfortable with development tools such as integrated development environments (IDEs) and version control systems. Familiarity with performance monitoring and profiling concepts will be advantageous. This book assumes that readers have a desire to delve deeper into the intricacies of Java performance tuning and are willing to experiment with different techniques to achieve the best results.
Libraries and frameworks are included throughout the book and their installation is optional.
If you are using the digital version of this book, we advise you to type the code yourself or access the code from the book’s GitHub repository (a link is available in the next section). Doing so will help you avoid any potential errors related to the copying and pasting of code.
Download the example code files
You can download the example code files for this book from GitHub at https://github.com/PacktPublishing/High-Performance-with-Java
. If there’s an update to the code, it will be updated in the GitHub repository.
We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/
. Check them out!
Conventions used
There are a number of text conventions used throughout this book.
Code in text: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: As you can see in the following, we can use the javap command without any parameters.
A block of code is set as follows:
public class CH1EX1 {
public CH1EX1 {
public static void main(java.lang.String[]);
}
}
When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:
public class Example2 {
public static void main(String[] args) {
List
Any command-line input or output is written as follows:
$ cd src
$ ls
CH1EX1.java
$
Tips or important notes
Appear like this.
Get in touch
Feedback from our readers is always welcome.
General feedback: If you have questions about any aspect of this book, email us at [email protected]
and mention the book title in the subject of your message.
Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/support/errata
and fill in the form.
Piracy: If you come across any illegal copies of our works in any form on the internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected]
with a link to the material.
If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com
.
Share Your Thoughts
Once you’ve read High Performance with Java, we’d love to hear your thoughts! Please click here to go straight to the Amazon review page
for this book and share your feedback.
Your review is important to us and the tech community and will help us make sure we’re delivering excellent quality content.
Download a free PDF copy of this book
Thanks for purchasing this book!
Do you like to read on the go but are unable to carry your print books everywhere?
Is your eBook purchase not compatible with the device of your choice?
Don’t worry, now with every Packt book you get a DRM-free PDF version of that book at no cost.
Read anywhere, any place, on any device. Search, copy, and paste code from your favorite technical books directly into your application.
The perks don’t stop there, you can get exclusive access to discounts, newsletters, and great free content in your inbox daily
Follow these simple steps to get the benefits:
Scan the QR code or visit the link below
https://packt.link/free-ebook/978-1-83546-973-6
Submit your proof of purchase
That’s it! We’ll send your free PDF and other benefits to your email directly
Part 1: Code Optimization
This part delves into the core techniques and strategies to optimize Java code. It starts with an in-depth exploration of the Java Virtual Machine (JVM) and its impact on performance. You will learn about the efficient use of data structures, techniques to optimize loops, the benefits of Java object pooling, and strategies to improve algorithm efficiencies. By mastering these fundamental concepts, you will significantly enhance the performance of your Java applications.
This part has the following chapters:
Chapter 1
, Peeking Inside the Java Virtual Machine (JVM)
Chapter 2
, Data Structures
Chapter 3
, Optimizing Loops
Chapter 4
, Java Object Pooling
Chapter 5
, Algorithm Efficiencies
1
Peeking Inside the Java Virtual Machine
I would like to introduce you to a remarkable piece of technology that helped revolutionize the software industry. Meet the Java Virtual Machine (JVM). Okay, so you are likely already familiar with the JVM, and it is important to understand and appreciate the tremendous value it has as the middleware between compiled Java bytecode and a virtually limitless number of hardware platforms. The ingenious design of Java and the JVM is a testament to its wild popularity and value to users and developers.
Since the first release of Java in the 1990s, the JVM has been the true success factor for the Java programming language. With Java and the JVM, the concept of write once, run anywhere
was born. Java developers can write their programs once and allow the JVM to ensure the code runs on devices the JVM is installed on. The JVM also makes Java a platform-independent language. The primary objective of this chapter is to provide greater insights into the unsung hero of Java, the JVM.
In this chapter, we will take an extensive look at the JVM so that we can learn to get the most out of it in an effort to increase the performance of our Java applications.
In this chapter, we will cover the following topics:
How the JVM works
Garbage collection
Just-in-Time (JIT) compiler optimizations
By the end of this chapter, you should understand how to get the most out of the JVM to improve the performance of your Java applications.
Technical requirements
To follow the instructions in this chapter, you will need the following:
A computer with either Windows, macOS, or Linux installed
The current version of the Java SDK
Preferably, a code editor or integrated development environment (IDE) (such as Visual Studio Code, NetBeans, Eclipse, or IntelliJ IDEA)
The finished code for this chapter can be found here: https://github.com/PacktPublishing/High-Performance-with-Java/tree/main/Chapter01
.
Important note
This book is based on Java 21 and the Java Development Kit (JDK) 21.0.1. It also uses the IntelliJ IDEA Community Edition IDE, running on macOS.
This chapter contains code examples that you can use to follow along with and experiment with. So, you will want to ensure your system is properly prepared.
Start by downloading and installing your IDE of choice. Here are a couple of options:
Visual Studio Code (https://code.visualstudio.com/download
)
NetBeans (https://netbeans.apache.org/download/
)
Eclipse (https://www.eclipse.org/downloads/
)
IntelliJ IDEA Community Edition (https://www.jetbrains.com/idea/download/
)
After your IDE is set up, you need to ensure it is configured for Java development. Most modern IDEs are capable of downloading and installing the Java SDK for you. If this is not the case for you, the Java SDK can be obtained here: https://www.oracle.com/java/technologies/downloads/
.
Ensuring that your IDE is Java-ready is important. Here are some IDE-specific links in case you need some help:
Java in Visual Studio Code (https://code.visualstudio.com/docs/languages/java
)
Java quick start tutorial for NetBeans (https://netbeans.apache.org/tutorial/main/kb/docs/java/quickstart/
)
Preparing Eclipse (https://help.eclipse.org/latest/index.jsp?topic=%2Forg.eclipse.jdt.doc.user%2FgettingStarted%2Fqs-3.htm
)
Creating your first Java application with IntelliJ IDEA Community Edition (https://www.jetbrains.com/help/idea/creating-and-running-your-first-java-application.html
)
Once you have your IDE and the Java SDK installed and configured on your computer, you are ready to move to the next section.
How the JVM works
At the core, the JVM sits between your Java bytecode and your computer. As illustrated next, we develop our Java source code in an IDE, and our work is saved as .java files. We use the Java compiler to convert our Java source code to bytecode; the resulting files are .class files. We then use the JVM to run our bytecode on our computer:
Figure 1.1 – Java application workflow
It is important to realize that Java is different from typical compile-and-execute languages where source code is fed into a compiler, which then produces a .exe file (for Windows), a .app file (for (macOS), or ELF files (for Linux). This impressive process is much more complex than it seems.
Let’s take a closer look at what is going on with regard to the JVM, using a basic example. In the following code, we implement a simple loop that prints to the console. It is presented so that we can see how the JVM handles Java code:
// Chapter1
// Example