Java Projects - Peter Verhas - E-Book

Java Projects E-Book

Peter Verhas

0,0
34,79 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

Java is one of the most commonly used software languages by programmers and developers. In this book, you’ll learn the new features of Java 11 quickly and experience a simple and powerful approach to software development. You’ll see how to use the Java runtime tools, understand the Java environment, and create a simple namesorting Java application. Further on, you'll learn about advanced technologies that Java delivers, such as web programming and parallel computing, and will develop a mastermind game. Moving on, we provide more simple examples, to build a foundation before diving into some complex data structure problems that will solidify your Java 11 skills. With a special focus on the features of new projects: Project Valhalla, Project Panama, Project Amber, and Project Loom, this book will help you get employed as a top-notch Java developer. By the end of the book, you’ll have a firm foundation to continue your journey toward becoming a professional Java developer.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB
MOBI

Seitenzahl: 814

Veröffentlichungsjahr: 2018

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Java ProjectsSecond Edition
Learn the fundamentals of Java 11 programming by building industry grade practical projects
Peter Verhas
BIRMINGHAM - MUMBAI

Java Projects Second Edition

Copyright © 2018 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.

Commissioning Editor: Richa TripathiAcquisition Editor: Denim PintoContent Development Editor: Nikhil BorkarTechnical Editor: Mehul SinghCopy Editor:Safis EditingProject Coordinator: Ulhas KambaliProofreader: Safis EditingIndexer: Rekha NairGraphics: Tom ScariaProduction Coordinator: Nilesh Mohite

First published: April 2017 Second edition: August 2018

Production reference: 1300818

Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK.

ISBN 978-1-78913-189-5

www.packtpub.com

mapt.io

Mapt is an online digital library that gives you full access to over 5,000 books and videos, as well as industry leading tools to help you plan your personal development and advance your career. For more information, please visit our website.

Why subscribe?

Spend less time learning and more time coding with practical eBooks and videos from over 4,000 industry professionals

Improve your learning with Skill Plans built especially for you

Get a free eBook or video every month

Mapt is fully searchable

Copy and paste, print, and bookmark content

PacktPub.com

Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.

At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters, and receive exclusive discounts and offers on Packt books and eBooks.

Contributors

About the author

Peter Verhas is a senior software engineer and software architect with an electrical engineering and economics background from TU Budapest (MsC) and PTE Hungary (MBA), and he also studied at TU Delft and TU Vienna. He created his first programs in 1979, and since then he has authored several open source programs. He has worked in several positions in the telecommunications and finance industries.

Peter works for EPAM Systems in Switzerland, participating in software development projects at various customer sites, and he supports talent acquisition by interviewing candidates, running training programs for developers, and internal mentoring programs. He regularly talks at various international conferences.

About the reviewer

Aristides Villarreal Bravo is a Java developer, a member of the NetBeans Dream Team, and a Java User Groups leader. He lives in Panama. He has organized and participated in various conferences and seminars related to Java, JavaEE, NetBeans, the NetBeans platform, free software, and mobile devices. He is the author of jmoordb and tutorials and blogs about Java, NetBeans, and web development. Aristides has participated in several interviews on sites about topics such as NetBeans, NetBeans DZone, and JavaHispano. He is a developer of plugins for NetBeans.

I would like to thank my mother, father, and all my family and friends.

Packt is searching for authors like you

If you're interested in becoming an author for Packt, please visit authors.packtpub.com and apply today. We have worked with thousands of developers and tech professionals, just like you, to help them share their insight with the global tech community. You can make a general application, apply for a specific hot topic that we are recruiting an author for, or submit your own idea.

Acknowledgments

Acknowledgment is the section of a book that everybody ignores by turning the pages. This time, this section is a bit different. I will mention a few people and their roles in the making of this book but, at the same time, I will explain why and how it is important to rely on people, being a software developer.

Doing professional work is not possible without having a life. It is quite obvious if you take that literally, but it is just as true figuratively. If you do not find the balance between your personal and professional life, you will burn out and will not operate professionally. This is the place to mention my family, my parents whom I am lucky to still have around, my brother who introduced me Java itself the first place, my wife, and my already adult kids who never stopped believing in me being able to do this work, who know more than well what a hypocrite I am, advocating personal-professional life balance, and who continually pushed me closer to this equilibrium point in life so that I could keep performing professionally.

For professional work, coworkers are almost as important as family support. It is important that you support your colleagues as much as you ask them for their support. You learn a lot from books and from experience, but you learn the most from other people. Pay attention to senior developers. You can, however, learn just as much from juniors. No matter how ace you are, from time to time, a rookie may shed light on a topic. During the years, I learned a lot from juniors who brought a fresh view to the table, asking shocking questions that were absolutely valid. I cannot name each and every junior who aided my work with fresh out-of-the-box thinking.

I can, and should, however, name some peer professionals who actively participated in the creation of this book with their advice, discussions, and suggestions.

I should certainly mention Károly Oláh who was very enthusiastic about my project, and he represented, supported, and encouraged the idea inside EPAM systems. He actively discussed with the upper management that the support for writing a book well fits the innovation line and development of the company and the people who work together. Without the official support from the company providing extra time for the task, I would not have been able to create this book.

A good company attracts good people who are clever and also good to work with. I had many discussions about the book, topics, and how to explain certain aspects with my fellow EPAMers: Krisztián Sallai, Peter Fodor, Sándor Szilágyi, Mantas Aleknavicius, Gábor Lénard, and many others.

I will separately mention István Attila Kovács from our Budapest office with whom I discussed Chapter 5 in detail, and who gave me very valuable feedback about the topic. If he does not know something about Java parallel computing, then that something does not exist.

As a summary and takeaway for the patient reader who read this section till the end, technology, knowledge, skills, and experience are extremely important for being a professional Java developer, but it is the people who really matter.

Table of Contents

Title Page

Copyright and Credits

Java Projects Second Edition

Packt Upsell

Why subscribe?

PacktPub.com

Contributors

About the author

About the reviewer

Packt is searching for authors like you

Acknowledgments

Preface

Who this book is for

What this book covers

To get the most out of this book

Download the example code files

Download the color images

Conventions used

Get in touch

Reviews

Getting Started with Java 11

Getting started with Java

Version numbers

Installing Java

Installation on Windows

Installation on macOS

Installation on Linux

Setting JAVA_HOME

Executing jshell

Looking at the bytecode

Packaging classes into a JAR file

Managing the running Java application

Using an IDE

NetBeans

Eclipse

IntelliJ

IDE services

IDE screen structure

Editing files

Managing projects

Building the code and running it

Debugging Java

Summary

The First Real Java Program - Sorting Names

Getting started with sorting

Bubble sort

Getting started with project structure and build tools

Make

Ant

Installing Ant

Using Ant

Maven

Installing Maven

Using Maven

Gradle

Installing Gradle

Setting up the project with Maven

Coding the sort

Understanding the algorithm and language constructs

Blocks

Variables

Types

Arrays

Expressions

Loops

Conditional execution

Final variables

Classes

Inner, nested, local, and anonymous classes

Packages

Methods

Interfaces

Argument passing

Fields

Modifiers

Object initializers and constructors

Compiling and running the program

Summary

Optimizing the Sort - Making Code Professional

The general sorting program

A brief overview of various sorting algorithms

Quicksort

Project structure and build tools

Maven dependency management

Coding the sort

Creating the interfaces

Creating BubbleSort

Architectural considerations

Creating unit tests

Adding JUnit as a dependency

Writing the BubbleSortTest class

Good unit tests

A good unit test is readable

Unit tests are fast

Unit tests are deterministic

Assertions should be as simple as possible

Unit tests are isolated

Unit tests cover the code

Refactoring the test

Collections with wrong elements

Handling exceptions

Generics

Test-Driven Development

Implementing QuickSort

The partitioning class

Recursive sorting

Non-recursive sorting

Implementing the API class

Creating modules

Why modules are needed

What is a Java module?

Summary

Mastermind - Creating a Game

The game

The model of the game

Java collections

Interface collection

Set

Hash functions

The equals method

The hashCode method

Implementing equals and hashCode

HashSet

EnumSet

LinkedHashSet

SortedSet

NavigableSet

TreeSet

List

LinkedList

ArrayList

Queue

Deque

Map

HashMap

IdentityHashMap

Dependency injection

Implementing the game

ColorManager

The class color

JavaDoc and code comments

Row

Table

Guesser

UniqueGuesser

GeneralGuesser

The Game class

Creating an integration test

Summary

Extending the Game - Run Parallel, Run Faster

How to make Mastermind parallel

Refactoring

Processes

Threads

Fibers

java.lang.Thread

Pitfalls

Deadlocks

Race conditions

Overused locks

Starving

ExecutorService

Completable future

ForkJoinPool

Variable access

The CPU heartbeat

Volatile variables

Synchronized block

Wait and notify

Lock

Condition

ReentrantLock

ReentrantReadWriteLock

Atomic variables

BlockingQueue

LinkedBlockingQueue

LinkedBlockingDeque

ArrayBlockingQueue

LinkedTransferQueue

IntervalGuesser

ParallelGamePlayer

Microbenchmarking

Summary

Making Our Game Professional - Do it as a Web App

Web and network

IP

TCP/IP

DNS

The HTTP protocol

HTTP methods

Status codes

HTTP/2

Cookies

Client server and web architecture

Writing a servlet

Hello world servlet

JavaServer Pages

HTML, CSS, and JavaScript

Mastermind servlet

Storing state

HTTP session

Storing state on the client

Dependency injection with Guice

The MastermindHandler class

Storing state on the server

The GameSessionSaver class

Running the Jetty web servlet

Logging

Configurability

Performance

Log frameworks

Java logging

Logging practice

Other technologies

Summary

Building a Commercial Web Application Using REST

The MyBusiness web shop

Sample business architecture

Microservices

Service interface design

JSON

REST

Model View Controller

Spring framework

Architecture of Spring

Spring core

Service classes

Compiling and running the application

Testing the application

Integration tests

Application tests

Servlet filters

Audit logging and AOP

Dynamic proxy-based AOP

Summary

Extending Our E-Commerce Application

The MyBusiness ordering

Setting up the project

Order controller and DTOs

Consistency checker

Annotations

Annotation retention

Annotation target

Annotation parameters

Repeatable annotations

Annotation inheritance

@Documented annotation

JDK annotations

Using reflection

Getting annotations

Invoking methods

Setting fields

Functional programming in Java

Lambda

Streams

Functional interfaces

Method references

Scripting in Java

Summary

Building an Accounting Application Using Reactive Programming

Reactive... what?

Reactive programming in a nutshell

Reactive systems

Responsive

Resilient

Elastic

Message-driven

Back-pressure

Reactive streams

Reactive programming in Java

Implementing the inventory

Summary

Finalizing Java Knowledge to a Professional Level

Java deep technologies

Java agent

Polyglot programming

Polyglot configuration

Polyglot scripting

Business DSL

Problems with polyglot

Annotation processing

Programming in the enterprise

Static code analysis

Source code version-control

Software versioning

Code review

Knowledge base

Issue tracking

Testing

Types of tests

Test automation

Black box versus white box

Selecting libraries

Fit for the purpose

License

Documentation

An alive project

Maturity

Number of users

The "I like it" factor

Continuous integration and deployment

Release management

The code repository

Walking up the ladder

Summary

Other Books You May Enjoy

Leave a review - let other readers know what you think

Preface

Java drastically changed with the introduction of Java 8, and this change has been elevated to a whole new level with the new version, Java 9 and then further with Java 10 and 11. Java has a well-established past, being more than 20 years old, but at the same time, it is new, functional, reactive, and sexy. This is a language that developers love, and at the same time, it is the number one choice of developer language for many enterprise projects.

It is probably more lucrative to learn Java now than ever before, starting with Java 11. We encourage you to start your professional developer career by learning Java, and we have done our best in this book to help you along this road. We assembled the topics of the book so that it is easy to start, and you can feel the things working and moving very quickly. At the same time, we have tried to reach very far, signaling the road ahead for a professional developer.

The sands of time kept moving, and I discovered functional programming.

I could very well see why writing side-effect-free code worked! I was hooked and started playing with Scala, Clojure, and Erlang. Immutability was the norm here. However, I wondered how traditional algorithms would look in a functional setting and started learning about it.

A data structure is never mutated in place. Instead, a new version of the data structure is created. The strategy of copy and write with maximized sharing was an intriguing one! All that careful synchronization is simply not needed! The languages come equipped with garbage collection. So, if a version is not needed anymore, the runtime would take care of reclaiming the memory. All in good time, though! Reading this book will help you see that we need not sacrifice algorithmic performance while avoiding in-place mutation!

Who this book is for

This book is for anyone who wants to learn the Java programming language. No programming experience is required. If you have prior experience, it will help you get through the book more easily.

What this book covers

Chapter 1, Getting Started with Java 11, gives you a jump start in Java, helping you install it on your computer and run your first interactive programs using the new Jshell.

Chapter 2, The First Real Java Program - Sorting Names, teaches you how to create a development project. We will create program files and compile the code.

Chapter 3, Optimizing the Sort - Making Code Professional, it develops the code further so that the code is reusable and not only a toy.

Chapter 4, Mastermind - Creating a Game, is when the fun starts. We develop a game application that is interesting and not as trivial as it first seems, but we will do it.

Chapter 5, Extending the Game - Run Parallel, Run Faster, shows you how to utilize the multi-processor capabilities of modern architecture. This is a very important chapter that details technologies that only a few developers truly understand.

Chapter 6, Making Our Game Professional - Do it as a Web App, transforms the user interface from command-line to web browser-based, delivering a better user experience.

Chapter 7, Building a Commercial Web Application Using REST, takes you through the development of an application that has the characteristics of many commercial applications. We will use the standard REST protocol, which has gained ground in enterprise computing.

Chapter 8, Extending Our E-Commerce Application, helps you develop the application further, utilizing modern language features such as scripting and lambda expressions.

Chapter 9, Building an Accounting Application Using Reactive Programming, teaches you how to approach some problems using reactive programming.

Chapter 10, Finalizing Java Knowledge to a Professional Level, gives a bird's-eye view of developer topics that play an important role in the life of a Java developer, and that will guide you further in working as a professional developer.

To get the most out of this book

To immerse yourself into the content of this book and to soak up the skills and knowledge, we assume that you already have some experience of programming. We do not assume too much but hope that you already know what a variable is, that computers have memory, disk, network interfaces, and what they generally are.In addition to these basic skills, there are some technical requirements you need to try out the code and the examples in the book. You need a computer—something that is available today and can run Windows, Linux, or OS X. You need an operating system and, probably, that is all you need to pay for. All other tools and services that you will need are available as open source and free of charge. Some of them are also available as commercial products with an extended feature set, but for the scope of this book, starting to learn Java 9 programming, those features are not needed. Java, a development environment, build tools, and all other software components we use are open source.

Download the example code files

You can download the example code files for this book from your account at www.packtpub.com. If you purchased this book elsewhere, you can visit www.packtpub.com/support and register to have the files emailed directly to you.

You can download the code files by following these steps:

Log in or register at

www.packtpub.com

.

Select the

SUPPORT

tab.

Click on

Code Downloads & Errata

.

Enter the name of the book in the

Search

box and follow the onscreen instructions.

Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

WinRAR/7-Zip for Windows

Zipeg/iZip/UnRarX for Mac

7-Zip/PeaZip for Linux

The code bundle for the book is also hosted on GitHub athttps://github.com/PacktPublishing/Java-Projects. In case there's an update to the code, it will be updated on the existing GitHub repository.

We also have other code bundles from our rich catalog of books and videos available athttps://github.com/PacktPublishing/. Check them out!

Download the color images

We also provide a PDF file that has color images of the screenshots/diagrams used in this book. You can download it here: https://www.packtpub.com/sites/default/files/downloads/JavaProjects_ColorImages.pdf.

Get in touch

Feedback from our readers is always welcome.

General feedback: Email [email protected] and mention the book title in the subject of your message. If you have questions about any aspect of this book, please email us at [email protected].

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/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.

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.

Reviews

Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you!

For more information about Packt, please visit packtpub.com.

Getting Started with Java 11

You want to learn Java and you have a good reason for it. Java is a modern and well-established application programming language, which is widely used in many industries, such as telecommunication, finance, and much more. Java developer positions are the most numerous and, probably, the best paid. This, among other things, makes the language lucrative for young professionals to learn.

On the other hand, this is not without reason. The Java language, the tools, and the whole infrastructure around it is complex and sophisticated. Becoming a Java professional does not happen in a day or a week; it is a work of many years. To be a Java expert, you need to know not only about the programming language but also about object-oriented programming principles, open source libraries, application servers, network, databases, and many other things. Nevertheless, learning the language is an absolute minimum. All other practices build on it. Throughout this book, you will learn Java version 18.9, also known as Java 11, and other things. You will learn not only the language but also the most important tools like maven, gradle, spring, Guice, SoapUI; protocols like http/2, SOAP, REST; how to work in an agile professional team; and what tools the team should use to cooperate. In the last chapter, you will even learn how you can plan your career that you intend to start as a Java developer.

In this chapter, you will be introduced to the Java environment, and you will be given step-by-step instructions on how to install it, edit the sample code, compile, and run Java. You will get acquainted with the basic tools that help in development, whether a part of Java or provided by other vendors. We will cover the following topics in this chapter:

Introduction to Java

Installing on Windows, Linux, and macOS

Executing

jshell

Using other Java tools

Using an integrated development environment

Getting started with Java

It is like going through a path in a forest. You can focus on the gravel of the road, but it is pointless. Instead, you can enjoy the view, the trees, the birds, and the environment around you, which is more enjoyable. This book is similar, as I won't be focusing only on the language. From time to time, I will cover topics that are close to the road and will give you some overview and directions on where you can go after you finish this book. I will not only teach you the language but also talk a bit about algorithms, object-oriented programming principles, tools that surround Java development, and how professionals work. This will be mixed with the coding examples that we will follow. Lastly, the final chapter will be fully devoted to the topic, what to learn next, and how to go further to become a professional Java developer.

By the time this book gets into print, Java will have completed 22 years (http://www.oracle.com/technetwork/java/javase/overview/javahistory-index-198355.html). The language has changed a lot during this period and got better. The real question to ask is not how long it has been here, but how long will itstay? Is it still worth learning this language? There are numerous new languages that have been developed since Java was born (http://blog.takipi.com/java-vs-net-vs-python-vs-ruby-vs-node-js-who-reigns-the-job-market/). These languages are more modern and have functional programming features, which, by the way, Java has also had since version 8. Many say that Java is the past—the future is Scala, Swift, Go, Kotlin, JavaScript, and so on. You can add many other languages to this list, and for each, you can find a blog article that celebrates the burial of Java. There are two answers to this concern: one is a pragmatic business approach, and the other is more regarding engineering:

Considering that COBOL is still actively used in the finance industry and COBOL developers are perhaps better paid than Java developers, it is not too risky to say that, as a Java developer, you will find positions in the next 40 years. Personally, I would bet more than 100 years, but considering my age, it will not be fair predicting more than 20 to 40 years ahead.

Java is not only a language, it is also a technology that you will learn a bit about from this book. The technology includes the

Java Virtual Machine

(

JVM

), which is usually referred to as JVM, and gives the runtime environment for many languages; Kotlin and Scala, for example, cannot run without JVM. Even if Java will be adumbrated, JVM will still be a number one player in the enterprise scene.

To understand and learn the basic operation of JVM is almost as important as the language itself. Java is a compiled and interpreted language. It is a special beast that forges the best of both worlds. Before Java, there were interpreted and compiled languages.

Interpreted languages are read from the source code by the interpreter, and then the interpreter executes the code. In each of these languages, there is some preliminary lexical and syntax analysis steps; however, after that, the interpreter, which, as a program itself, is executed by the processor, and the interpreter continuously interprets the program code to know what to do. Compiled languages are different. In such a case, the source code is compiled to binary (.exefile on Windows platforms), which the operating system loads and the processor directly executes. Compiled programs usually run faster, but there is usually a slower compilation phase that may make the development slower, and the execution environment is not so flexible. Java combined the two approaches.

To execute a Java program, the Java source code has to be compiled to the JVM bytecode (.class file), which is loaded by JVM and is interpreted or compiled. Hmm…is it interpreted or compiled? The thing that came with Java is the Just in Time (JIT) compiler. This makes the phase of the compilation that is calculation-intensive and the compilation for compiled languages relatively slow. JVM first starts to interpret the Java bytecode and, while doing that, it keeps track of execution statistics. When it gathers enough statistics about code executions, it compiles to native code (for example, x86 code on an Intel/AMD platform) for direct execution of the parts of the code that are executed frequently and keeps interpreting the code fragments that are rarely used. After all, why waste expensive CPU time to compile some code that is hardly ever used? (For example, code that reads configuration during startup and does not execute again unless the application server is restarted.) Compilation to the bytecode is fast, and code generation is done only for the segments that pay off.

It is also interesting that JIT uses the statistics of the code execution to optimize the code. If, for example, it can see that some conditional branch is executed in 99% of the cases and the other branch is executed only in 1%, it will generate native code that runs fast, thus favoring the frequent branch. If the behavior of that part of the program changes by time and the statistic shows that the ratios changed, the JIT automatically recompiles the bytecode from time to time. This is all automatic and behind the scenes.

In addition to the automatic compilation, there is also an extremely important feature of JVM—it manages the memory for the Java program. The execution environment of modern languages does that, and Java was the first mainstream language that had an automatic garbage collection (GC). Before Java, I was programming in C for 20 years, and it was a great pain to keep track of all memory allocation and not to forget to release the memory when the program no longer needed it. Forget memory allocation at a single point in the code, and the long-running program eats up all memory slowly. Such problems practically ceased to exist in Java. There is a price that we have to pay for it—GC needs processor capacity and some extra memory, but that is something we are not short of in most of the enterprise applications. Some special programs, like real-time embedded systems that control the brakes of a heavy-duty lorry, may not have that luxury.

Those are still programmed in assembly or C. For the rest of us, we have Java, and though it may seem strange for many professionals, even almost-real-time programs, such as high-frequency trading applications, are written in Java.

These applications connect through the network to the stock exchange, and they sell and buy stock responding to market changes in milliseconds. Java is capable of doing that. The runtime environment of Java that you will need to execute a compiled Java code, which also includes the JVM itself, contains code that lets Java programs access the network, files on disks, and other resources. To do this, the runtime contains high-level classes that the code can instantiate, execute, and which do the low-level jobs. You will also do this. It means that the actual Java code does not need to handle IP packets, TCP connections, or even HTTP handling when it wants to use or provide a REST service in some microservices architecture. It is already implemented in the runtime libraries, and all the application programmer has to do is include the classes in the code and use the APIs they provide on an abstraction level that matches the program. When you program in Java, you can focus on the actual problem you want to solve, which is the business code and not the low-level system code. If it is not in the standard library, you will find it in some product in some external library, and it is also very probable that you will find an open source solution for the problem.

This is also a strong point of Java. There are a vast number of open source libraries available for all the different purposes. If you cannot find a library fitting your problem and you start to code some low-level code, then you are probably doing something wrong. There are topics in this book that are important, such as class loaders or reflection, not because you have to use them every day but because they are used by frameworks, and knowing them helps you understand how these frameworks work. If you cannot solve your problem without using reflection or writing your own class loader or program multithread directly, then you probably chose the wrong framework. There is almost certainly a good one; Apache project, Google, and many other important players in the software industry publish their Java libraries as open source.

This is also true for multithread programming. Java is a multithread programming environment from the very beginning. The JVM and the runtime support programs that execute the code. The execution runs parallel on multiple threads. There are runtime language constructs that support the parallel execution of programs. Some of these constructs are very low level, and others are at a high abstraction level. Multithread code utilizes the multicore processors, which are more effective. These processors are more and more common. 20 years ago, only high-end servers had multiple processors and only Digital Alpha processors had 64-bit architecture and CPU clock above 100 MHz. 10 years ago, a multiprocessor structure was common on the server side, and about 5 years ago, multicore processors were on some desktops and on notebooks; today, even mobile phones have them. When Java was started in 1995, the geniuses who created it had seen this future.

They envisioned Java to be a write once, run anywhere language. At that time, the first target for the language was applet running in the browser. Today, many think (and I also share this opinion) that applets were a wrong target, or at least things were not done in the right way. As of now, you will meet applets on the internet less frequently than Flash applications or dinosaurs. What's more, the applet interface was deprecated already in Java 9, creating the opinion that applets are not good officially.

However, at the same time, the Java interpreter was also executing server and client applications without any browser. Furthermore, as the language and the executing environment developed, these application areas became more and more relevant. Today, the main use of Java is enterprise computing and mobile applications mainly for the Android platform. For the future, the use of the environment is growing in embedded systems as the Internet of things (IoT) comes more and more into the picture.

Version numbers

Java versioning is constantly changing. It does not only mean that the version numbers are changing from one release to the other. That is kind of obvious; that is what version numbers are for, after all. In the case of Java, however, the structure of the version numbers is also changing. Java started with version 1.0 (surprise!) and then version 1.1 shortly followed. The next release was 1.2, and it was so much different from the previous versions that people started calling it Java 2. Then, we had Java 1.3 till Java 1.8. This was a stable period as far as we consider the structure of the version number. However, the next Java version was named Java 9 instead of 1.9 last year, in 2017. It makes sense, because after 22 years of development and nine releases, the 1. part of the version number did not really make much sense. Nobody was expecting a "real" Java 2.0 that is so much different from any other releases that it deserved the 2. version prefix. In reality, the Java versions were really 1, 2, 3 and so on; they were just named as 1.1, 1.2, 1.3, and so on.

You could expect that after this huge change in the release number format, the next release of Java would be Java 10. Not at all. Oracle decided to use date-based release numbers. The first part of the release number before the dot will be the two digit year, like 18 for versions released in 2018. The part after the dot is the number of the month, usually 3 for March and 9 for September. Thus, when you look at Java version number 18.3, you immediately know that this version was released March 2018, which is actually Java 10 when following the old nomenclature.

Installing Java

To develop, compile, and execute Java programs, you will need the Java execution environment. As the operating systems that we usually use for software development do not contain the language preinstalled, you will have to download it. Although there are multiple implementations of the language, I recommend that you download the official version of the software from Oracle. The official site for Java is http://java.com, and this is the site from where the latest release of the language can be downloaded. At the time of writing this book, the 11th version of Java has not yet been released. An early pre-release version is accessible via http://jdk.java.net/11/ to download. Later, the release versions will also be available from here:

What you can download from here is a so-called early access version of the code that is available only to experiment with it, and no professionals should use it for commercial purposes.

On the page, you have to click on the radio button to accept, but the license. After that, you can click on the link that directly starts the download of the installation kit. The license is a special early access license version that you, as a professional, should carefully read, understand, and accept only if you are agreeable to the terms.

There is a separate installation kit for Windows 32 and 64 bit systems, macOS, Linux 32, and 64-bit versions, Linux for ARM processor, Solaris for SPARC processor systems, and Solaris x86 versions. As it is not likely that you will use Solaris, I will detail the installation procedure only for Windows, Linux, and macOS. In the later chapters, the samples will always be macOS, but since Java is a write once, run anywhere language, there is no difference after the installation. The directory separator may be slanted differently, the classpath separator character is a semicolon on Windows instead of a colon, and the look and feel of the Terminal or command application is also different. However, where it is important, I will try not to forget to mention it.

To confuse you, the Java download for each of these operating system versions lists a link for the JRE and one for the JDK. JRE stands for Java Runtime Environment, and it contains all the tools and executables that are needed to run Java programs. JDK is the Java Development Kit that contains all the tools and executables needed to develop Java programs, including the execution of the Java program. In other words, JDK contains its own JRE. For now, all you need to do is download the JDK.

There is one important point of the installation that is the same on each of the three operating systems, which you have to be prepared for before the installation—to install Java, you should have administrative privileges.

Installation on Windows

The installation process on Windows starts by double-clicking on the downloaded file. It will start the installer and will present you with a welcome screen. Windows 10 may ask you the admin permission to install Java:

Pressing the Next button gets a window where you can select the parts you want to install, and also, we can change the location where Java will be installed:

Let's leave the default settings here, which means that we install all the downloaded parts of Java and press Next:

We get to a progress screen while Java is installing. This is a fairly fast process, no more than a 10-second process. After Java has been installed, we get a confirmation screen:

We can press Close. It is possible to press the Next Steps button, that opens the browser and brings us to a page that describes the next steps we can do with Java. Using the prerelease version results in an HTTP 404 error. This will hopefully be fixed when you read this book.

The last step is to set the environment variable JAVA_HOME. To do that, in Windows, we have to open the control center and select the Edit environment variables for your account menu:

This will open a new window that we should use to create a new environment variable for the current user:

The name of the new variable has to be JAVA_HOME, and the value should point to the installation directory of the JDK:

This value on most systems is C:\Program Files\Java\jdk-11. This is used by many Java programs and tools to locate the Java runtime.

Installation on macOS

In this section, we will take look at how to install Java step by step on a macOS platform. I will describe the installation process for the released version available at the time of writing this book. As of now, the Java 18.9 early access version is a bit tricky to install. It is probable that the release version of Java 18.9 will have similar or the same installation steps as Java 9.

The macOS version of Java comes in the form of a .dmg file. This is a packaging format of macOS. To open it, simply double-click on the file in the Download folder where the browser saves it, and the operating system will mount the file as a read-only disk image:

There is only one file on this disk—the installation image. Double-click on the filename or icon in the Finder application and the installation process will start:

The first screen is a welcome screen. Click on Continue, and you will see the Summary page that displays what will be installed.

It is not a surprise that you will see a standard Java installation. This time, the button is called Install. Click on it and you will see the following:

This is the time when you have to provide the login parameters for the administrative user—a username and password:

When provided, installation starts and, in a few seconds, you will see a Summary page:

Click on Close and you are ready. You have Java installed on your Mac. Optionally, you can dismount the installation disk and, sometime later, you can also delete the .dmg file. You will not need that, and in case you do, you can download it any time from Oracle.

The last thing is to check whether the installation was okay. The proof of the pudding is in eating it. Start a Terminal window and type java -version at the prompt; Java will tell you the version that's been installed.

In the following screenshot, you can see the output on my workstation and also the macOS commands that are handy to switch between the different versions of Java:

In the preceding screenshot, you can see that I have installed the Java 11 version and, at the same time, I also have a Java 18.9 early release installation, which I will use to test the new features of Java for this book.

Installation on Linux

There are several ways to install Java on Linux, depending on its flavor. Here, I will describe an installation method that works more or less the same way on all flavors. The one I used is Debian.

The first step is the same as in any other operating system—download the installation kit. In the case of Linux, you should select a package that has a tar.gz ending. This is a compressed archive format. You should also carefully select the package that matches the processor in your machine and the 32/64 bit version of the operating system. After the package is downloaded, you have to switch to root mode, issuing the su command. This is the first command you can see in the following screenshot, that shows the installation commands:

The tar command uncompressed the archive into a subfolder. In Debian, this subfolder has to be moved to /opt/jdk, and the mv command is used for this purpose. The two update-alternatives commands are Debian-specific. These tell the operating system to use this newly installed Java in case there is already an older Java installed. The Debian I was using to test and demonstrate the installation process on a virtual machine came with a 7-year-old version of Java.

The final step of the installation is the same as any other operating system—checking whether the installation was successful in issuing the java -version command. In the case of Linux, this is even more important. The installation process does not check that the downloaded version matches the operating system and the processor architecture.

Setting JAVA_HOME

The JAVA_HOME environment variable plays a special role in Java. Even though the JVM executable, java.exe or java, is on the PATH (thus, you can execute it by typing the name java without specifying the directory in the Command Prompt) (Terminal), it is recommended that you use the correct Java installation to set this environment variable. The value of the variable should point to the installed JDK. There are many Java-related programs, Tomcat or Maven for example, that use this variable to locate the installed and currently used Java version. In macOS, setting this variable is unavoidable.

In macOS, the program that starts to execute when you type java, is a wrapper that first looks at JAVA_HOME to decide which Java version to start. If this variable is not set, macOS will decide on its own, selecting from the available installed JDK versions. To see the available versions, you can issue the following command:

~$ /usr/libexec/java_home -V Matching Java Virtual Machines (13): 11, x86_64: "Java SE 11-ea" /Library/Java/JavaVirtualMachines/jdk-11.jdk/Contents/Home 10, x86_64: "Java SE 10" /Library/Java/JavaVirtualMachines/jdk-10.jdk/Contents/Home 9.0.1, x86_64: "Java SE 9.0.1" /Library/Java/JavaVirtualMachines/jdk-9.0.1.jdk/Contents/Home 9, x86_64: "Java SE 9-ea" /Library/Java/JavaVirtualMachines/jdk-9.jdk/Contents/Home 1.8.0_92, x86_64: "Java SE 8" /Library/Java/JavaVirtualMachines/jdk1.8.0_92.jdk/Contents/Home 1.8.0_20, x86_64: "Java SE 8" /Library/Java/JavaVirtualMachines/jdk1.8.0_20.jdk/Contents/Home 1.8.0_05, x86_64: "Java SE 8" /Library/Java/JavaVirtualMachines/jdk1.8.0_05.jdk/Contents/Home 1.8.0, x86_64: "Java SE 8" /Library/Java/JavaVirtualMachines/jdk1.8.0.jdk/Contents/Home 1.7.0_60, x86_64: "Java SE 7" /Library/Java/JavaVirtualMachines/jdk1.7.0_60.jdk/Contents/Home 1.7.0_40, x86_64: "Java SE 7" /Library/Java/JavaVirtualMachines/jdk1.7.0_40.jdk/Contents/Home 1.7.0_21, x86_64: "Java SE 7" /Library/Java/JavaVirtualMachines/jdk1.7.0_21.jdk/Contents/Home 1.7.0_07, x86_64: "Java SE 7" /Library/Java/JavaVirtualMachines/jdk1.7.0_07.jdk/Contents/Home 1.7.0_04, x86_64: "Java SE 7" /Library/Java/JavaVirtualMachines/1.7.0.jdk/Contents/Home /Library/Java/JavaVirtualMachines/jdk-11.jdk/Contents/Home

You will then get the list of installed JDKs. Note that the command is lowercase, but the option is capitalized. If you do not provide any options and argument to the program, it will simply return the JDK it thinks is the newest and most appropriate for the purpose. As I copied the output of the command from my Terminal window, you can see that I have quite a few versions of Java installed on my machine.

The last line of the program response is the home directory of JDK, which is the default. You can use this to set your JAVA_HOME variable using some bash programming:

export JAVA_HOME=$(/usr/libexec/java_home)

You can place this file in your .bashrc file, which is executed each time you start a Terminal application, and thus JAVA_HOME will always be set. If you want to use a different version, you can use -v, with the lowercase option this time, to the same utility, as follows:

export JAVA_HOME=$(/usr/libexec/java_home -v 1.8)

The argument is the version of Java you want to use. Note that this versioning becomes the following:

export JAVA_HOME=$(/usr/libexec/java_home -v 11)

If you want to use the Java JDK Early Access version and not 1.11, there is not an explanation for the same—fact of life.

Note that there is another environment variable that is important for Java—CLASSPATH. We will talk about it later.