32,36 €
A comprehensive guide to get started with Java and gain insights into major concepts such as object-oriented, functional, and reactive programming
Key Features
Book Description
Java is one of the preferred languages among developers, used in everything right from smartphones, and game consoles to even supercomputers, and its new features simply add to the richness of the language. This book on Java programming begins by helping you learn how to install the Java Development Kit. You will then focus on understanding object-oriented programming (OOP), with exclusive insights into concepts like abstraction, encapsulation, inheritance, and polymorphism, which will help you when programming for real-world apps. Next, you'll cover fundamental programming structures of Java such as data structures and algorithms that will serve as the building blocks for your apps. You will also delve into core programming topics that will assist you with error handling, debugging, and testing your apps. As you progress, you'll move on to advanced topics such as Java libraries, database management, and network programming, which will hone your skills in building professional-grade apps.
Further on, you'll understand how to create a graphic user interface using JavaFX and learn to build scalable apps by taking advantage of reactive and functional programming.
By the end of this book, you'll not only be well versed with Java 10, 11, and 12, but also gain a perspective into the future of this language and software development in general.
What you will learn
Who this book is for
Students, software developers, or anyone looking to learn new skills or even a language will find this book useful. Although this book is for beginners, professional programmers can benefit from it too. Previous knowledge of Java or any programming language is not required.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 818
Veröffentlichungsjahr: 2019
Copyright © 2019 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: Digvijay BagulTechnical Editor: Neha PandeCopy Editor: Safis EditingProject Coordinator: Prajakta NaikProofreader: Safis EditingIndexer:Tejal Daruwale SoniGraphics: Tom ScariaProduction Coordinator: Tom Scaria
First published: April 2019 Production reference: 1300419
Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK.
ISBN 978-1-78995-705-1
www.packtpub.com
To my wife Luda, a software developer too, who was the source of my inspiration and the sound technical advice for this book
– Nick Samoylov
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.
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
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.packt.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.packt.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.
Nick Samoylov graduated from Moscow Institute of Physics and Technology, working as a theoretical physicist and learning to program as a tool for testing his mathematical models. After the demise of the USSR, Nick created and successfully ran a software company, but was forced to close it under the pressure of governmental and criminal rackets. In 1999, with his wife Luda and two daughters, he emigrated to the USA and has been living in Colorado since then, working as a Java programmer. In his free time, Nick likes to write and hike in the Rocky Mountains.
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 writes tutorials and blogs about Java, NetBeans, and web development. He has participated in several interviews on sites about topics such as NetBeans, NetBeans DZone, and JavaHispano. He is a developer of plugins for NetBeans.
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.
Title Page
Copyright and Credits
Learn Java 12 Programming
Dedication
About Packt
Why subscribe?
Packt.com
Contributors
About the author
About the reviewer
Packt is searching for authors like you
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
Section 1: Overview of Java Programming
Getting Started with Java 12
How to install and run Java
What is JDK and why do we need it?
Installing Java SE
Commands, tools, and utilities
How to install and run an IDE
Selecting an IDE
Installing and configuring IntelliJ IDEA
Creating a project
Importing a project
Executing examples from the command line
Java primitive types and operators
Boolean type
Numeric types
Integral types
Floating-point types
Default values of primitive types
Literals of primitive types
New compact number format
Operators
Arithmetic unary (+ and -) and binary operators (+, -, *, /, and %)
Increment and decrement unary operators (++ and --)
Equality operators (== and !=)
Relational operators (<, >, <=, and >=)
Logical operators (!, &, and |)
Conditional operators (&&, ||, and ? :)
Assignment operators (=, +=, -=, *=, /=, and %=)
String type and literals
String literals
String immutability
Identifiers and variables
Identifier
Variable declaration (definition) and initialization
Type holder var
Java statements
Expression statements
Control flow statements
Selection statements
Iteration statements
Exception-handling statements
Branching statements
Summary
Quiz
Java Object-Oriented Programming (OOP)
OOP concepts
Object/Class
Inheritance
Abstraction/Interface
Encapsulation
Polymorphism
Class
Method
Varargs
Constructor
The new operator
Class java.lang.Object
Instance and static properties and methods
Interface
Default methods
Private methods
Static fields and methods
Interface versus abstract class
Overloading, overriding, and hiding
Overloading
Overriding
Hiding
Final variable, method, and classes
Final variable
Final method
Final class
Polymorphism in action
Object factory
Operator instanceof
Summary
Quiz
Java Fundamentals
Packages, importing, and access
Packages
Importing 
Access modifiers
Java reference types
Class and interface
Array
Enum
Default values and literals 
Reference type as a method parameter
Method equals()
Reserved and restricted keywords
Reserved keywords
Restricted keywords
The usage of the this and super keywords
Usage of the this keyword
Usage of the super keyword 
Converting between primitive types
Widening conversion
Narrowing conversion
Methods of conversion
Converting between primitive and reference types
Boxing
Unboxing
Summary
Quiz
Section 2: Building Blocks of Java
Exception Handling
Java exceptions framework
Checked and unchecked exceptions
The try, catch, and finally blocks
The throws statement
The throw statement
The assert statement
Best practices of exceptions handling
Summary
Quiz
Strings, Input/Output, and Files
Strings processing
Methods of the class String
Strings analysis
Strings comparison
Strings transformation
Methods added with Java 11
String utilities
I/O streams
Stream data
Class InputStream and its subclasses
ByteArrayInputStream
FileInputStream
ObjectInputStream
PipedInputStream
SequenceInputStream
FilterInputStream
javax.sound.sampled.AudioInputStream
Class OutputStream and its subclasses
PrintStream 
Classes reader and writer and their subclasses
Reader and its subclasses
Writer and its subclasses
Other classes of java.io package
Console
StreamTokenizer
ObjectStreamClass and ObjectStreamField
Class java.util.Scanner
File management
Creating and deleting files and directories
Listing files and directories
Apache Commons utilities FileUtils and IOUtils
Class FileUtils
Class IOUtils
Summary
Quiz
Data Structures, Generics, and Popular Utilities
List, set, and map interfaces
Generics
How to initialize List and Set
Interface java.lang.Iterable
Interface Collection
Interface List 
Interface Set
Interface Map
Unmodifiable collections
Collections utilities
Class java.util.Collections
Class CollectionUtils of Apache project
Arrays utilities
Class java.util.Arrays
Class ArrayUtils of Apache project
Object utilities
Class java.util.Objects
Class ObjectUtils of Apache project
java.time package
Class LocalDate
Class LocalTime
Class LocalDateTime
Classes Period and Duration
Summary
Quiz
Java Standard and External Libraries
Java Class Library
java.lang
java.util
java.time
java.io and java.nio
java.sql and javax.sql
java.net
java.lang.math and java.math
java.awt, javax.swing, and javafx
External libraries
org.junit
org.mockito
org.apache.log4j and org.slf4j
org.apache.commons
lang and lang3
collections4
codec.binary
Summary
Quiz
Multithreading and Concurrent Processing
Thread vs process
User thread vs daemon
Extending class thread
Implementing interface Runnable
Extending thread vs implementing Runnable
Using pool of threads
Getting results from thread
Parallel vs concurrent processing
Concurrent modification of the same resource
Atomic variable
Synchronized method
Synchronized block
Concurrent collections 
Addressing memory consistency error
Summary
Quiz
JVM Structure and Garbage Collection
Java application execution
Using IDE
Using the command line with classes
Using the command line with JAR files
Using the command line with an executable JAR file
Java processes 
Class loading
Class linking
Class initialization
Class instantiation
Method execution
Garbage collection
Application termination
JVM structure
Runtime data areas
Classloaders
Execution engine
Garbage collection
Responsiveness, throughput, and stop-the-world
Object age and generations
When stop-the-world is unavoidable
Summary
Quiz
Managing Data in a Database
Creating a database
Creating a database structure
Connecting to a database
Releasing the connection
CRUD data
The INSERT statement
The SELECT statement
The UPDATE statement
The DELETE statement
Using statements
The execute(String sql) method
The executeQuery(String sql) method
The executeUpdate(String sql) method
Using PreparedStatement
Using CallableStatement
Summary
Quiz
Network Programming
Network protocols
UDP-based communication
TCP-based communication
The java.net.ServerSocket class
The java.net.Socket class
Running the examples
UDP versus TCP protocols
URL-based communication
The URL syntax
The java.net.URL class
Using the HTTP 2 Client API
Blocking HTTP requests
Non-blocking (asynchronous) HTTP requests
Server push functionality
WebSocket support
Summary
Quiz
Java GUI Programming
Java GUI technologies
JavaFX fundamentals
Hello with JavaFX
Control elements
Charts
Applying CSS
Using FXML
Embedding HTML
Playing media
Adding effects
Summary
Quiz
Section 3: Advanced Java
Functional Programming
What is functional programming?
What is a functional interface?
What is a lambda expression?
Local-variable syntax for lambda parameters
Standard functional interfaces
Consumer<T>
Predicate<T>
Supplier<T>
Function<T, R>
Other standard functional interfaces
Lambda expression limitations
Method references
Summary
Quiz
Java Standard Streams
Stream as a source of data and operations
Stream initialization
Stream interface
empty()
of(T... values)
ofNullable(T t)
iterate(Object, UnaryOperator)
concat (Stream a, Stream b)
generate (Supplier)
Stream.Builder interface
Other classes and interfaces
Operations (methods)
Intermediate operations
Filtering
Mapping
Sorting
Peeking
Terminal operations
Processing each element
Counting all elements
Match all, any, none
Find any or first
Class Optional
Min and max
To array
Reduce
Collect
Collectors
Numeric stream interfaces
Creating a stream
range(), rangeClosed()
Intermediate operations
boxed(), mapToObj()
mapToInt(), mapToLong(), mapToDouble()
flatMapToInt(), flatMapToLong(), flatMapToDouble()
Terminal operations
sum(), average()
Parallel streams
Stateless and stateful operations
Sequential or parallel processing?
Summary
Quiz
Reactive Programming
Asynchronous processing
Sequential and parallel streams
Using the CompletableFuture object
Non-blocking API
java.io package versus java.nio package
Event/run loop
Reactive
Responsive
Resilient
Elastic
Message-driven
Reactive streams 
RxJava
Observable types
Blocking versus non-blocking
Cold versus hot
Disposable
Creating an observable
Operators
Transforming
Filtering 
Combining
Converting from XXX
Exceptions handling
Life cycle events handling
Utilities
Conditional and boolean
Backpressure
Connectable 
Multithreading (scheduler)
Summary
Quiz
Microservices
What is a microservice?
The size of a microservice
How microservices talk to each other
The reactive system of microservices
The HTTP server
The EventBus message receiver 
The EventBus message senders 
The reactive system demonstration
Summary
Quiz
Java Microbenchmark Harness
What is JMH?
Creating a JMH benchmark
Running the benchmark
Using an IDE plugin
JMH benchmark parameters
Mode
Output time unit
Iterations
Forking
JMH usage examples
Using the @State annotation
Using the Blackhole object
Using the @CompilerControl annotation
Using the @Param annotation
A word of caution
Summary
Quiz
Best Practices for Writing High-Quality Code
Java idioms, their implementation, and their usage
The equals() and hashCode() methods
The compareTo() method
The clone() method
The StringBuffer and StringBuilder classes
Try, catch, and finally clauses
Best design practices
Identifying loosely coupled functional areas
Breaking the functional area into traditional tiers
Coding to an interface
Using factories
Preferring composition over inheritance
Using libraries
Code is written for people
Testing is the shortest path to quality code
Summary
Quiz
Java Getting New Features
Java continues to evolve
Panama project
Valhalla project
Amber project
Data class
Pattern match
Raw string literals
Concise method bodies
Lambda leftovers
Using an underscore instead of a parameter name 
Shadowing a local variable
Better disambiguation of functional expressions
Loom project
Skara project
Summary
Assessments
Chapter 1 – Getting Started with Java 12
Chapter 2 – Java Object-Oriented Programming (OOP)
Chapter 3 – Java Fundamentals
Chapter 4 – Exception Handling
Chapter 5 – Strings, Input/Output, and Files
Chapter 6 – Data Structures, Generics, and Popular Utilities
Chapter 7 – Java Standard and External Libraries
Chapter 8 – Multithreading and Concurrent Processing
Chapter 9 – JVM Structure and Garbage Collection
Chapter 10 – Managing Data in a Database
Chapter 11 – Network Programming
Chapter 12 – Java GUI Programming
Chapter 13 – Functional Programming
Chapter 14 – Java Standard Streams
Chapter 15 – Reactive Programming
Chapter 16 – Microservices
Chapter 17 – Java Microbenchmark Harness
Chapter 18 – Best Practices for Writing High-Quality Code
Other Books You May Enjoy
Leave a review - let other readers know what you think
The purpose of this book is to equip the readers with a solid understanding of Java fundamentals and to lead them through a series of practical steps from the basics to the actual real programming. The discussion and examples aim to stimulate the growth of the reader's professional intuition by using proven programming principles and practices. The book starts with the basics and brings the readers up to the latest programming technologies, considered on a professional level.
After finishing this book, you will be able to do the following:
Install and configure your Java development environment
Install and configure your
Integrated Development Environment
(
IDE
)—essentially, your editor
Write, compile, and execute Java programs and tests
Understand and use Java language fundamentals
Understand and apply object-oriented design principles
Master the most frequently used Java constructs
Learn how to access and manage data in the database from Java application
Enhance your understanding of network programming
Learn how to add graphical user interface for better interaction with your application
Become familiar with the functional programming
Understand the most advanced data processing technologies—streams, including parallel and reactive streams
Learn and practice creating microservices and building a reactive system
Learn the best design and programming practices
Envision Java's future and learn how you can become part of it
This book is for those who would like to start a new career in the modern Java programming profession, as well as those who do it professionally already and would like to refresh their knowledge of the latest Java and related technologies and ideas.
Chapter 1, Getting Started with Java 12, begins with the basics, first explaining what "Java" is and defining its main terms, then going on to how to install the necessary tools to write and run (execute) a program. This chapter also describes the basic Java language constructs, illustrating them with examples that can be executed immediately.
Chapter2, Object-Oriented Programming (OOP), presents the concepts of object-oriented programming and how they are implemented in Java. Each concept is demonstrated with specific code examples. The Java language constructs of class and interface are discussed in detail, as well as overloading, overriding, hiding, and use of the final keyword. The last section of the chapter is dedicated to presenting the power of polymorphism.
Chapter 3, Java Fundamentals, presents to the reader a more detailed view of Java as a language. It starts with the code organization in packages and a description of the accessibility levels of classes (interfaces) and their methodsand properties (fields). The reference types as the main types of Java's object-oriented nature are presented in much detail, followed by a list of reserved and restricted keywords and a discussion of their usage. The chapter ends with the methods of conversion between primitive types, and from a primitive type to the corresponding reference type and back.
Chapter 4, Exception Handling, tells the reader about the syntax of the Java constructs related to exception handling and the best practices to address (handle) exceptions. The chapter ends with the related topic of the assertion statement that can be used to debug the application code in production.
Chapter 5, Strings, Input/Output, and Files, discusses the String class methods, as well as popular string utilities from standard libraries and the Apache Commons project. An overview of Java input/output streams and related classes of the java.io package follow along with some classes of the org.apache.commons.io package. The file-managing classes and their methods are described in a dedicated section.
Chapter 6, Data Structures, Generics, and Popular Utilities, presents the Java collections framework and its three main interfaces List, Set, and Map, including discussion and demonstration of generics. The equals() and hashCode() methods are also discussed in the context of Java collections. Utility classes for managing arrays, objects, and time/date values have corresponding dedicated sections, too.
Chapter 7, Java Standard and External Libraries, provides an overview of the functionality of the most popular packages of Java Class Library (JCL): java.lang, java.util, java.time, java.io and java.nio, java.sql and javax.sql, java.net, java.lang.math, java.math, java.awt, javax.swing, and javafx. The most popular external libraries are represented by the org.junit, org.mockito, org.apache.log4j, org.slf4j, and org.apache.commons packages. This chapter helps the reader to avoid writing custom code in cases where such functionality already exists and can be just imported and used out of the box.
Chapter 8, Multithreading and Concurrent Processing, presents the ways to increase Java application performance by using workers (threads) that process data concurrently. It explains the concept of Java threads and demonstrates their usage. It also talks about the difference between parallel and concurrent processing, and how to avoid unpredictable results caused by the concurrent modification of a shared resource.
Chapter 9, JVM Structure and Garbage Collection, provides the readers with an overview of JVM's structure and behavior, which are more complex than we usually expect. One of the service threads, called garbage collection, performs an important mission of releasing the memory from unused objects. After reading this chapter, the readers will understand better what constitutes Java application execution, Java processes inside JVM, garbage collection, and how JVM works in general.
Chapter 10, Managing Data in a Database, explains and demonstrates how to manage—that is, insert, read, update, and delete—data in a database from a Java application. It also provides a short introduction to the SQL language and basic database operations: how to connect to a database, how to create a database structure, how to write a database expression using SQL, and how to execute them.
Chapter 11, Network Programming, describes and discusses the most popular network protocols, User Datagram Protocol (UDP), Transmission Control Protocol (TCP), HyperText Transfer Protocol (HTTP), and WebSocket, and their support for JCL. It demonstrates how to use these protocols and how to implement client-server communication in Java code. The APIs reviewed include URL-based communication and the latest Java HTTP Client API.
Chapter 12, Java GUI Programming, provides an overview of Java GUI technologies and demonstrates how the JavaFX kit can be used to create a GUI application. The latest versions of JavaFX not only provide many helpful features, but also allow preserving and embedding legacy implementations and styles.
Chapter 13, Functional Programming, explains what a functional interface is, provides an overview of functional interfaces that come with JDK, and defines and demonstrates lambda expressions and how to use them with functional interfaces, including using method reference.
Chapter 14, Java Standard Streams, talks about the processing of data streams, which are different from the I/O streams reviewed in Chapter 5, Strings, Input/Output, and Files. It defines what data streams are, how to process their elements using methods (operations) of the java.util.stream.Stream object, and how to chain (connect) stream operations in a pipeline. It also discusses the stream's initialization and how to process the stream in parallel.
Chapter 15, Reactive Programming, introduces the Reactive Manifesto and the world of reactive programming. It starts with defining and discussing the main related concepts – "asynchronous", "non-blocking", "responsive", and so on. Using them, it then defines and discusses reactive programming, the main reactive frameworks, and talks about RxJava in more details.
Chapter 16, Microservices, explains how to build microservices – the foundational component for creating a reactive system. It discusses what a microservice is, how big or small they can be, and how existing microservices frameworks support message-driven architecture. The discussion is illustrated with a detailed code demonstration of a small reactive system built using the Vert.x toolkit.
Chapter 17, Java Microbenchmark Harness, presents the Java Microbenchmark Harness (JMH) project that allows us to measure various code performance characteristics. It defines what JMH is, how to create and run a benchmark, what the benchmark parameters are, and outlines supported IDE plugins. The chapter ends with some practical demo examples and recommendations.
Chapter 18, Best Practices for Writing High-Quality Code, introduces Java idioms and the most popular and useful practices for designing and writing application code.
Chapter 19, Java Gets New Features, talks about current the most significant projects that will add new features to Java and enhance it in other aspects. After reading this chapter, the reader will understand how to follow Java development and will be able to envision the roadmap of future Java releases. If so desired, the reader can become the JDK source contributor too.
Read the chapters systematically and answer the quiz questions at the end of each chapter. Clone or just download the source code repository (see the following sections) and run all the code samples that demonstrate the discussed topics. For getting up to speed in programming, there is nothing better than executing the provided examples, modifying them, and trying your own ideas. Code is truth.
You can download the example code files for this book from your account at www.packt.com. If you purchased this book elsewhere, you can visit www.packt.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.packt.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 at https://github.com/PacktPublishing/Learn-Java-12-Programming. 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 at https://github.com/PacktPublishing/. Check them out!
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/9781789957051_ColorImages.pdf.
Feedback from our readers is always welcome.
General feedback: If you have questions about any aspect of this book, mention the book title in the subject of your message and 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.packt.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.
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 packt.com.
The first part of the book brings the reader into the world of Java programming. It starts with basic Java-related definitions and the main terms, walks the reader through the installation of the necessary tools and Java itself, and explains how to run (execute) a Java program and the examples of the code provided with this book.
With the basics in place, we then explain and discuss Object-Oriented Programming (OOP) principles, how Java implements them, and how a programmer can take advantage of them to write high-quality code that is easy to maintain.
The book proceeds by presenting a more detailed view of Java as a language. It explains how the code is organized in packages, defines all the main types, and the list of reserved and restricted keywords. All the discussions are illustrated with specific code examples.
This section contains the following chapters:
Chapter 1, Getting Started with Java 12
Chapter 2, Java Object-Oriented Programming (OOP)
Chapter 3, Java Fundamentals
This chapter is about how to start learning Java 12 and Java in general. We will begin with the basics, first explaining what Java is and its main terms, followed by how to install the necessary tools to write and run (execute) a program. In this respect, Java 12 is not much different from the previous Java versions, so this chapter's content is applicable to the older versions too.
We will describe and demonstrate all the necessary steps for building and configuring a Java programming environment. This is the bare minimum that you have to have on the computer in order to start programming. We also describe the basic Java language constructs and illustrate them with examples that can be executed immediately.
The best way to learn a programming language or any language for that matter is to use it, and this chapter guides the reader on how they can do this with Java. The topics covered in this chapter include the following:
How to install and run Java
How to install and run
an
Integrated Development Environment
(
IDE
)
Java primitive types and operators
String type and literals
Identifiers and variables
Java statements
When somebody says "Java," they may mean quite different things:
Java programming language
: A high-level programming language that allows an intent (a program) to be expressed in a human-readable format that can be translated into the binary code executable by a computer
Java compiler
: A program that can read a text written in the Java programming language and translate it into a bytecode that can be interpreted by
Java Virtual Machine
(
JVM
)
into the binary code executable by a computer
Java Virtual Machine
(
JVM
): A program that reads a compiled Java program and interprets it into the binary code that is executable by a computer
Java Development Kit
(
JDK
): The collection of programs (tools and utilities), including Java compiler, JVM, and supporting libraries, which allow the compilation and execution of a program written in the Java language
The following section walks the reader through the installation of JDK of Java 12 and the basic related terms and commands.
As we have mentioned already, JDK includes a Java compiler and JVM. The task of the compiler is to read a .java file that contains the text of the program written in Java (called source code) and transform (compile) it into a bytecode stored in a .class file. The JVM then can read the .class file, interpret the bytecode into a binary code, and send it to the operating system for execution. Both the compiler and JVM have to be invoked explicitly from the command line.
To support the .java file compilation and its bytecode execution, JDK installation also includes standard Java libraries called Java Class Library (JCL). If the program uses a third-party library, it has to be present during the compilation and execution. It has to be referred from the same command line that invokes the compiler and later when the bytecode is executed by JVM. JCL, on the other hand, does not need to be referred to explicitly. It is assumed that the standard Java libraries reside in the default location of the JDK installation, so the compiler and JVM know where to find them.
If you do not need to compile a Java program and would like to run only the already-compiled .class files, you can download and install Java Runtime Environment (JRE). For example, it consists of a subset of the JDK and does not include a compiler.
Sometimes, JDK is referred to as a Software Development Kit (SDK), which is a general name for a collection of software tools and supporting libraries that allow the creation of an executable version of a source code written using a certain programming language. So, JDK is an SDK for Java. This means it is possible to call JDK an SDK.
You may also hear the terms Java platform and Java edition in relation to a JDK. A typical platform is an operating system that allows a software program to be developed and executed. Since JDK provides its own operating environment, it is called a platform too. An edition is a variation of a Java platform (JDK) assembled for a specific purpose. There are five Java platform editions, as listed here:
Java Platform Standard Edition
(
Java SE
): This includes JVM, JCL, and other tools and utilities.
Java Platform Enterprise Edition
(
Java EE
):
This
includes Java SE, servers (computer programs that provide services to the applications), JCL and other libraries, code samples, tutorials, and other documentation for developing and deploying large-scale, multi-tiered, and secure network applications.
Java Platform Micro Edition
(
Java ME
):
This i
s a subset of Java SE with some specialized libraries for developing and deploying Java applications for embedded and mobile devices such as phones, personal digital assistants, TV set-top boxes, printers, sensors, and similar. A variation of Java ME (with its own JVM implementation) is called
Android SDK
. It was developed by Google
for Android programming
.
Java Card
: It's the smallest of the Java editions and is intended for developing and deploying Java applications on to small embedded devices such as smart cards. It has two editions:
Java Card Classic Edition
, for smart cards, based on ISO7816 and ISO14443 communication, and
Java Card Connected Edition
, which supports a web application model and TCP/IP as basic protocol and runs on high-end secure microcontrollers.
So, to install Java means to install JDK, which also means to install Java platform on one of the listed editions. In this book, we are going to talk about and use only Java SE.
All the recently released JDKs are listed on the official Oracle page: www.oracle.com/technetwork/java/javase/overview/index.html (we will call it an Installation Home Page for the further references).
Here are the steps that need to be followed to install Java SE:
Find the link to the Java SE version you are looking for (
Java SE 12
in this case) and click on it.
You will be presented with the various links, one of which is
Installation Instructions
. Alternatively, you could get to this page by clicking the
Downloads
tab.
Click the
DOWNLOAD
link
under the title
Oracle JDK
.
A new screen will give you the option to accept or decline a
License Agreement
using a radio button and
a list of links to various JDK installers
.
Read the
License Agreement
and make your decision. If you do not accept it, you cannot download the JDK. If you accept the
License Agreement
, you can select the JDK installer from the available list.
You need to choose the installer that fits your operating system and the format (extension) you are familiar with.
If in doubt, go back to the
Installation
Home Page
, select the
Downloads
tab,
and click the
Installation Instructions
link.
F
ollow the steps that correspond to your operating system.
The JDK is installed successfully when the
java -version
command on your computer displays the correct Java version, as demonstrated in the following screenshot:
If you follow the installation instructions, you may have noticed a link (Installed Directory Structure of JDK) given under the Table of Contents. It brings you to a page that describes the location of the installed JDK on your computer and the content of each directory of the JDK root directory. The bin directory contains all the executables that constitute the Java commands, tools, and utilities. If the directory bin is not added to the environment variable PATH automatically, consider doing it manually so that you can launch a Java executable from any directory.
In the previous section, we have already demonstrated the Java command, java -version. A list of the other available Java executables (commands, tools, and utilities) can be found in the Java SE documentation (https://www.oracle.com/technetwork/java/javase/documentation/index.html) by clicking the link Java Platform Standard Edition Technical Documentation site, then the link Tools Reference on the next page. You can learn more about each executable tool by clicking its link.
You can also run each of the listed executables on your computer using one of the following options: -?, -h, --help, or -help. It will display a brief description of the executable and all its options.
The most important Java commands are the following:
javac
: This reads a
.java
file, compiles it, and creates one or more
corresponding
.class
files, depending on how many Java classes are defined in the
.java
file.
java
: This executes a
.class
file.
These are the commands that make programming possible. Each Java programmer must have a good understanding of their structure and capabilities. But if you are new to Java programming and use an IDE (see the How to install and run IDE section), you do not need to master these commands immediately. A good IDE hides them from you by compiling a .java file automatically every time you make a change to it. It also provides a graphical element that runs the program every time you click it.
Another very useful Java tool is jcmd. It facilitates communication with, and diagnosis of, any of the currently running Java processes (JVM) and has many options. But in its simplest form, without any option, it lists all the currently running Java processes and their Process IDs (PIDs). You can use it to see whether you have run-away Java processes. If you have, you can then kill such a process using the provided PID.
What used to be just a specialized editor that allowed checking the syntax of the written program the same way a Word editor checks the syntax of an English sentence gradually evolved into an Integrated Development Environment (IDE). It bears its main function in the name. It integrates all the tools necessary for writing, compiling, and then executing a program under one Graphical User Interface (GUI). Using the power of Java Compiler, IDE identifies syntax errors immediately and then helps to improve code quality by providing context-dependent help and suggestions.
There are several IDEs available for a Java programmer such as NetBeans, Eclipse, IntelliJ IDEA, BlueJ, DrJava, JDeveloper, JCreator, jEdit, JSource, jCRASP, and jEdit, to name a few. The most popular ones are NetBeans, Eclipse, and IntelliJ IDEA.
NetBeans development started in 1996 as a Java IDE student project at Charles University in Prague. In 1999, the project and the company created around the project were acquired by Sun Microsystems. After Oracle acquired Sun Microsystems, NetBeans became open source, and many Java developers have contributed to the project. It was bundled with JDK 8 and became an official IDE for Java development. In 2016, Oracle donated it to the Apache Software Foundation.
There is a NetBeans IDE for Windows, Linux, Mac, and Oracle Solaris. It supports multiple programming languages and can be extended with plugins. NetBeans is bundled only with JDK 8, but NetBeans 8.2 can work with JDK 9 too and uses features introduced with JDK 9, such as Jigsaw, for example. On netbeans.apache.org, you can read more about NetBeans IDE and download the latest version, which is 11.0 as of the time of this writing.
Eclipse is the most widely used Java IDE. The list of plugins that add new features to the IDE is constantly growing, so it is not possible to enumerate all the IDE's capabilities. The Eclipse IDE project has been developed since 2001 as open source software. A non-profit, member-supported corporation Eclipse foundation was created in 2004 with the goal of providing the infrastructure (version-control systems, code review systems, build servers, the download sites, and so on) and a structured process. None of the thirty-something employees of the Foundation is working on any of 150 Eclipse-supported projects.
The sheer number and variety of the Eclipse IDE plugins create a certain challenge for a beginner because you have to find your way around different implementations of the same, or similar features, that can, on occasion, be incompatible and may require deep investigation as well as a clear understanding of all the dependencies. Nevertheless, Eclipse IDE is very popular and has solid community support. You can read about the Eclipse IDE and download the latest release from www.eclipse.org/ide.
The IntelliJ IDEA has two versions: a paid one and a free Community Edition. The paid version is consistently ranked as the best Java IDE, but the Community Edition is listed among the three leading Java IDEs too. The JetBrains software company that develops the IDE has offices in Prague, Saint Petersburg, Moscow, Munich, Boston, and Novosibirsk. The IDE is known for its deep Intelligence that is "giving relevant suggestions in every context: instant and clever code completion, on-the-fly code analysis, and reliable refactoring tools," as stated by the authors while describing the product on their website (www.jetbrains.com/idea). In the Installing and configuring IntelliJ IDEA section, we will walk you through the installation and configuration of IntelliJ IDEA Community Edition.
These are the steps you need to follow in order to download and install IntelliJ IDEA:
Download an installer of IntelliJ Community Edition from
www.jetbrains.com/idea/download
.
Launch the installer and accept all the default values.
Select
.java
on the
Installation Options
screen. We assume you have installed JDK already, so you do not check the
Download and install JRE
option.
The last installation screen has a checkbox
Run IntelliJ IDEA
that you can check to start the IDE automatically. Alternatively, you can leave the checkbox unchecked and launch the IDE manually once the installation is complete.
When the IDE starts the first time, it asks whether you would like to
Import IntelliJ IDEA settings
. Check the
Do not import settings
checkbox if you have not used the IntelliJ IDEA before and would like to reuse the settings.
The following screen or two asks whether you accept the
JetBrains Privacy Policy
and whether you would like to pay for the license or prefer to continue to use the free community edition or free trial (this depends on the particular download you get).
Answer the questions whichever way you prefer, and if you accept the privacy policy, the
Customize IntelliJ IDEA
screen asks you to choose a theme, white (
IntelliJ
) or dark (
Darcula
).
When offered the buttons
Skip All and Set Defaults
and
Next: Default plugins
, select the
Next: Default plugins
, as it will give you the option to configure the IDE beforehand.
When presented with the
Tune IDEA to your tasks
screen, select the
Customize...
link for the following three, one at a time:
Build Tools
: Select
Maven
and click the button
Save Changes and Go Back
.
Version Controls
: Select the version-control system you prefer (optional) and click
Save Changes and Go Back
.
Test Tools
: Select
JUnit
or any other test framework you prefer (optional) and click
Save Changes and Go Back
.
If you decide to change the set values, you can do this later by selecting
from the topmost menu
File
,
Settings
on Windows or
Preferences
on Linux and macOS.
Before you start writing your program, you need to create a project. There are several ways to create a project in IntelliJ IDEA, which is the same for any IDE, as follows:
Create New Project
: This creates a new project from scratch.
Import Project
:
This allows reading the existing source code from the filesystem.
Open
:
This allows reading the existing project from the filesystem.
Check out from Version Control
:
This allows reading the existing project from the version control system.
In this book, we will walk you through the first option only—using the sequence of guided steps provided by the IDE. The other two options are much simpler and do not require additional explanations. Once you have learned how to create a new project from scratch, the other ways to bring up a project in the IDE will be very easy for you.
Start by clicking the Create New Project link and proceed further as follows:
Select a value for
Project SDK
(Java Version 12, if you have installed JDK 12 already) and click
Next
.
Do not check
Create project from template
(if checked, the IDE generates a canned program
Hello world
and similar, which we do not need)
and click
Next
.
Select the desired project location in the
Project location
field (this is where your new code will reside).
Enter anything you like in the
Project name
field (for example, the project for the code in this book is called
learnjava
) and click the
Finish
button.
You will see the following project structure:
Right-click on the project name (
learnjava
) and select
Add Framework Support
from the drop-down menu. On the following pop-up window, select
Maven
:
Maven
is a project configuration tool. Its primary function is to manage project dependencies. We will talk about it shortly. For now, we will use its other responsibility, to define and hold the project code identity using three properties:
groupId
: To identify a group of projects within an organization or an open-source community
artifactId
: To identify a particular project within the group
version
: To identify the version of the project
The main goal is to make the identity of a project unique among all the projects of the world. To help avoid a groupId clash, the convention requires that you start building it from the organization domain name in reverse. For example, if a company has the domain name company.com, the group IDs of its projects should start with com.company. That is why for the code in this book, we use the groupId value com.packt.learnjava.
Let's set it. Click OK on the pop-up window Add Framework Support and you will a newly generated pom.xml file as follows:
At the same time, in the lower-right corner of the screen, another small window will pop-up:
Click the Enable Auto-Import link. This will make writing code easier: all the new classes you will start using will be imported automatically. We will talk about class importing in due time.
Now let's enter groupId, artifactId, and version values:
Now, if somebody would like to use the code of your project in their application, they would refer to it by the three values shown and Maven (if they use it) will bring it in (if you upload your project in the publicly shared Maven repository, of course). Read more about Maven at https://maven.apache.org/guides.
Another function of the groupId value is to define the root directory of the folders tree that holds your project code. Let's open the src folder; you will see the following directory structure beneath it:
The java folder under main will hold the application code, while the java folder under test will hold the test code.
Let's create our first program using the following steps:
Right-click on
java
, select
New
and then click
Package
:
In the provided
New Package
window, type
com.packt.learnjava.ch01_start
as follows:
Click
OK
and you should see in the left panel, the set of new folders, the last of them being
com.packt.learnjava.ch01_start
:
Right-click on it
, select
New
and then click
Java Class
:
In the provided input window, type
PrimitiveTypes
:
Click
OK
and you will see the first Java class,
PrimitiveTypes
, created in the package
com.packt.learnjava.ch01_start
package:
The package reflects the Java class location in the filesystem. We will talk about it in Chapter 2, Java Object-Oriented Programming (OOP). Now, in order to run a program, we create a main() method. If present, this method can be executed and serve as an entry point into the application. It has a certain format, as follows:
It has to have the following attributes:
public
: Freely accessible from outside the package
static
: Should be able to be called without creating an object of the class it belongs to
It should also be the following:
Return
void
(nothing).
Accept a
String
array as an input or
varargs
as we have done. We will talk about
varargs
in
Chapter 2
,
Java Object-Oriented Programming (OOP)
. For now, suffice to say that
String[] args
and
String... args
define essentially the same input format.
We explained how to run the main class using a command line in the Executing examples from the command line section. You can read more about Java command-line arguments in the official Oracle documentation: https://docs.oracle.com/javase/tutorial/essential/environment/cmdLineArgs.html. It is also possible to run the examples from IntelliJ IDEA.
Notice the two green triangles to the left in the following screenshot. By clicking any of them, you can execute the main() method. For example, let's display Hello, world!.
In order to do it, type the following line inside the main() method:
System.out.println("Hello, world!");
Then, click one of the green triangles:
You should get the following output in the terminal area as follows:
From now on, every time we are going to discuss code examples, we will run them the same way, by using the main() method. While doing this, we will not capture a screenshot but put the result in comments, because such a style is easier to follow. For example, the following code displays how the previous code demonstration would look in this style:
System.out.println("Hello, world!"); //prints: Hello, world!
It is possible to add a comment (any text) to the right of the code line separated by the double slash //. The compiler does not read this text and just keeps it as it is. The presence of a comment does not affect performance and is used to explain the programmer's intent to humans.
In this section, we are going to demonstrate the process of importing the existing code into IntelliJ IDEA by using the source code for this book. We assume that you have Maven installed (https://maven.apache.org/install.html) on your computer and that you have Git (https://gist.github.com/derhuerst/1b15ff4652a867391f03) installed too, and can use it. We also assume that you have installed JDK 12, as was described in the Installation of Java SE section.
To import the project with the code examples for this book, follow these steps:
Go to the source repository (
https://github.com/PacktPublishing/Learn-Java-12-Programming
) and click the
Clone or download
link, as shown in the following screenshot:
Click the
Clone or download
link and then copy the provided URL:
Select a directory on your computer where you would like the source code to be placed and then run the following Git command:
A new
Learn-Java-12-Programming
folder is created, as shown in the following screenshot:
Alternatively, instead of cloning, you can download the source as a .zip file using the link Download ZIP shown on the preceding screenshot. Unarchive the downloaded source in a directory on your computer where you would like the source code to be placed, and then rename the newly created folder by removing the suffix "-master" from its name, making sure that the folder's name is Learn-Java-12-Programming.
The new
Learn-Java-12-Programming
folder contains the
Maven
project with all the source code from this book. Now run the IntelliJ IDEA and click
File
in the topmost menu, then
New
and
Project from Existing Sources...
:
Select the
Learn-Java-12-Programming
folder created in step 4 and click the
Open
button:
Accept the default settings and click the
Next
button on each of the following screens until you reach a screen that shows a list of the JDKs installed and the
Finish
button:
Select
12
and click
Finish
. You will see the project imported into your IntelliJ IDEA:
Wait until the following small window shows up in the bottom-right corner:
You may not want to wait and continue with step 12. Just do steps 10 and 11 when the window pops up later. If you miss this window, you may click the Event Log link any time later, and you will be presented with the same options.
Click on it; then click the
Add as Maven Project
link:
Any time the following window shows up, click
Enable Auto-Import
:
You may not want to wait and continue with step 12. Just do step 11 when the window pops-up later. If you miss this window, you may click the Event Log link any time later, and you will be presented with the same options.
Select the Project structure symbol, which is the third from the right on the following screenshot:
If you have the
main
and
test
modules listed, remove them by highlighting them and clicking the minus symbol (
-
) as shown on the following screen:
Here’s how the final list of modules should look:
Click
OK
in the bottom-right corner and get back to your project. Click
Learn-Java-12-Programming
in the left pane and continue going down in the source tree until you see the following list of classes:
Click on the green arrow in the right pane and execute any class you want. The result you will be able to see in the
Run
window is similar to the following:
To execute the examples from the command line, follow these steps:
Go to the
Learn-Java-12-Programming
folder created in
step 4
in the
Importing a project
section, where the
pom.xml
file is located, and run the
mvn clean package
command:
Select the example you would like to run. For example, assuming you would like to run
ControlFlow.java
, run the following command:
java -cp target/learnjava-1.0-SNAPSHOT.jar:target/libs/* \com.packt.learnjava.ch01_start.ControlFlow
You will see the following results:
If you would like to run example files from the
ch05_stringsIoStreams
package, run the same command with a different package and class name:
java -cp target/learnjava-1.0-SNAPSHOT.jar:target/libs/* \com.packt.learnjava.ch05_stringsIoStreams.Files
If your computer has a Windows system, use the following command as one line:
java -cp target\learnjava-1.0-SNAPSHOT.jar;target\libs\* com.packt.learnjava.ch05_stringsIoStreams.Files
Note that a Windows command has a different slash and semicolon (;) as the classpath separator.
The results will be as follows:
This way you can run any class that has the
main()
method in it. The content of the
main()
method will be executed.
With all the main programming tools in place, we can start talking about Java as a language. The language syntax is defined by Java Language Specification, which you can findon https://docs.oracle.com/javase/specs. Don't hesitate to refer to it every time you need some clarification. It is not as daunting as many people assume.
All the values in Java are divided into two categories: reference types and primitive types. We start with primitive types and operators as the natural entry point to any programming language. In this chapter, we will also discuss one reference type called String (see the String type and literalssection).
All primitive types can be divided into two groups: the boolean type and the numeric types.
Javanumeric types form two groups: integral types (byte, char, short, int, long) and floating-point types (float and double).
The integral types consume the following amount of memory:
byte
: 8 bit
char
: 16 bit
short
: 16 bit
int
: 32 bit
long
: 64 bit
The char type is an unsigned integer that can hold a value (called a code point) from 0 to 65,535 inclusive. It represents a Unicode character, which means there are 65,536 Unicode characters. Here are three records form the Basic Latin list of Unicode characters:
Code point
Unicode escape
Printable symbol
Description
33
\u0021
!
Exclamation mark
50
\u0032
2
Digit two
65
\u0041
A
Latin Capital letter A
