31,19 €
Get a solid understanding of Java fundamentals to master programming through a series of practical steps
Key Features Enjoy your first step into the world of programming Understand what a language is and use its features to build applications Learn about a wide variety of programming applicationsBook Description
Have you ever thought about making your computer do what you want it to do? Do you want to learn to program, but just don't know where to start? Instead of guiding you in the right direction, have other learning resources got you confused with over-explanations?
Don't worry. Look no further. Introduction to Programming is here to help.
Written by an industry expert who understands the challenges faced by those from a non-programming background, this book takes a gentle, hand-holding approach to introducing you to the world of programming. Beginning with an introduction to what programming is, you'll go on to learn about languages, their syntax, and development environments. With plenty of examples for you to code alongside reading, the book's practical approach will help you to grasp everything it has to offer. More importantly, you'll understand several aspects of application development. As a result, you'll have your very own application running by the end of the book. To help you comprehensively understand Java programming, there are exercises at the end of each chapter to keep things interesting and encourage you to add your own personal touch to the code and, ultimately, your application.
What you will learnUnderstand what Java isInstall Java and learn how to run itWrite and execute a Java programWrite and execute the test for your programInstall components and confgure your development environmentLearn and use Java language fundamentalsLearn object-oriented design principlesMaster the frequently used Java constructsWho this book is for
Introduction to Programming is for anybody who wants to learn programming. All you’ll need is a computer, internet connection, and a cup of coffee.
Nick Samoylov graduated from the Moscow Institute of Physics and Technology, has worked as a theoretical physicist, and learned to program 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 following pressure from the government and criminal elements. In 1999, with his wife Luda and two daughters, he emigrated to the USA and has been living in Colorado ever since, working as a Java programmer. In his free time, Nick likes to write and hike in the Rocky Mountains.
Sie lesen das E-Book in den Legimi-Apps auf:
Seitenzahl: 906
Veröffentlichungsjahr: 2018
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: Aaron LazarAcquisition Editor: Denim PintoContent Development Editor: Nikhil BorkarTechnical Editor: Subhalaxmi NadarCopy Editor: Safis EditingProject Coordinator: Ulhas KambaliProofreader: Safis EditingIndexer: Aishwarya GangawaneGraphics: Tania DuttaProduction Coordinator: Arvindkumar Gupta
First published: June 2018
Production reference: 1140618
Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK.
ISBN 978-1-78883-912-9
www.packtpub.com
Nick Samoylov graduated from the Moscow Institute of Physics and Technology, has worked as a theoretical physicist, and learned to program 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 following pressure from the government and criminal elements. In 1999, with his wife Luda and two daughters, he emigrated to the USA and has been living in Colorado ever since, working as a Java programmer. In his free time, Nick likes to write and hike in the Rocky Mountains.
Dr. Srinivas Padmanabhuni, the past president of ACM India, prior to cofounding Tarah Technologies, was Associate Vice President heading research at Infosys until October 2015. He has over 15 years' experience in IT and has given over 100 expert invited talks in the US, China, Australia, Canada, Singapore, UK, and India, including ivy league universities such as CMU, Purdue, and RUC.
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.
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 insights 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.
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.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.
Title Page
Copyright and Credits
Introduction to Programming
Dedication
Contributors
About the author
About the reviewers
Packt is searching for authors like you
Packt Upsell
Why subscribe?
PacktPub.com
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
Java Virtual Machine (JVM) on Your Computer
What is Java?
Basic terms
History and popularity
Principles
Java platforms, editions, versions, and technologies
Platforms and editions
Versions
Technologies
Java SE Development Kit (JDK) installation and configuration
Where to start
The page with Java installers
How to install
Main Java commands
The JVM execution command
The compilation command
Command jcmd and other commands
Exercise – JDK tools and utilities
Answer
Summary
Java Language Basics
The basic terms of Java programming
Byte code
Defects (bugs) and their severity and priority
Java program dependencies
Statements
Methods
Classes
The Main class and the main method
Classes and objects (instances)
Java classes
Java object (class instance)
Class (static) and object (instance) members
Private and public
Static members
Object (instance) members
Method overloading
Interface, implementation, and inheritance
Interface
Implementation
Inheritance
The java.lang.Object class
The equals() method
The hashCode() method
The getClass() method
The toString() method
The clone() method
The wait() and notify() methods
OOP concepts
Object/class
Encapsulation
Inheritance
Interface (abstraction)
Polymorphism
Exercise – Interface versus abstract class
Answer
Summary
Your Development Environment Setup
What is the development environment?
Java editor is your main tool
Source code compilation
Code sharing
Code and test execution
Setting the classpath
Manual setting
Searching on the classpath
IDE sets the classpath automatically
There are many IDEs out there
NetBeans
Eclipse
IntelliJ IDEA
Installing and configuring IntelliJ IDEA
Downloading and installing
Configuring IntelliJ IDEA
Exercise – Installing NetBeans IDE
Answer
Summary
Your First Java Project
What is a project?
Definition and origin of project
Project-related terms
A project's life cycle
Creating a project
Creating a project using a project wizard
Maven project configuration
Changing IDE settings at any time
Writing an application code
Java package declaration
Creating a package
Creating the MyApplication class
Building the application
Hiding some files and directories
Creating the SimpleMath class
Creating methods
Executing and unit testing an application
Executing the application using the IDE
Creating a unit test
Executing the unit test
How many unit tests are enough?
Exercise – JUnit @Before and @After annotations
Answer
Summary
Java Language Elements and Types
What are the Java language elements?
Input elements
Types
Comments
Identifiers and variables
Identifier
Variable
Variable declaration, definition, and initialization
Final variable (constant)
Reserved and restricted keywords
Reserved keywords
Restricted keywords
Separators
Semicolon ";"
Braces "{}"
Parentheses "()"
Brackets "[]"
Comma ","
Period "."
Ellipsis "..."
Colons "::"
At sign "@"
Primitive types and literals
The Boolean type
Integral types
Floating-point types
Default values of primitive types
Primitive type literals
Reference types and String
Class types
Interface types
Arrays
Default value of a reference type
Reference type literals
String immutability
Enum types
Passing reference type values as method parameters
Exercise – Variable declarations and initializations
Answer
Summary
Interfaces, Classes, and Object Construction
What is an API?
Java APIs
Command line APIs
HTTP-based APIs
Software component API
Interface and object factory as API
Interface
Object factory
Reading configuration file
Using the json-simple library
Using the json-api library
Unit test
Calculator API 
Adding static methods to API
The API is complete
Overloading, overriding, and hiding
Interface method overloading
Interface method overriding
Interface static member hiding
Class member hiding
Instance method overriding
Instance method overloading 
This, super, and constructors
Keyword this and its usage
Keyword super and its usage
Constructors
Final variable, final method, or final class
Final variable
Final method
Final class
Exercise – Restricting a class instantiation to a single shared instance
Answer
Summary
Packages and Accessibility (Visibility)
What is importing?
Structure of the .java file and packages
Single class import
Multiple classes import
Static import
Access modifiers
The accessibility of a top-level class or interface
Access to class or interface members
The constructor's accessibility is the same as any class member
Encapsulation
Data hiding and decoupling
Flexibility, maintainability, and refactoring
Reusability
Testability
Exercise – Shadowing
Answer
Summary
Object-Oriented Design (OOD) Principles
What is the purpose of design?
The project's feasibility
Requirement gathering and prototyping
High-level design
Detailed design
Coding
Testing
A roadmap to a good design
Encapsulating and coding to an interface
Taking advantage of polymorphism
Decoupling as much as you can
Preferring aggregation over inheritance
So many OOD principles and so little time
Exercise – Design patterns
Answer
Summary
Operators, Expressions, and Statements
What are the core elements of Java programming?
Operators
Arithmetic unary (+  -) and binary operators:  +   -   *   /   %
Incrementing and decrementing unary operators:  ++   -- 
Equality operators:  ==   !=
Relational operators:  <  >  <=  >=   
Logical operators:  !  &  |  
Conditional operators:  &&   ||    ? : (ternary)
Assignment operators (most popular):  =   +=   -=   *=   /=   %=
Instance creation operator: new
Type comparison operator:  instanceof
Preferring polymorphism over the instanceof operator
Field access or method invocation operator:  .
Cast operator:  (target type)
Expressions
Statements
Operator precedence and evaluation order of operands
Operator precedence
Evaluation order of operands
Widening and narrowing reference types
Widening
Narrowing
Widening and narrowing conversion of primitive types
Widening
Narrowing
Methods of primitive type conversion 
Boxing and unboxing between primitive and reference types
Boxing
Unboxing
Method equals() of reference types
Using the implementation of the base class Object
Overriding the equals() method
Using the identification implemented in the parent class
The equals() method of the String class
 The equals() method in wrapper classes of primitive types
Exercise – Naming the statements
Answer
Summary
Control Flow Statements
What is a control flow?
Selection statements
Iteration statements
Branching statements
Exception handling statements
Selection statements
if 
if...else 
if...else if-...-else 
switch...case 
Iteration statements
while
do...while
for 
for enhanced
for with multiple initializers and expressions
Branching statements
Break and labeled break
Continue and labeled continue
return
Exception handling statements
throw
try...catch 
Checked and unchecked (runtime) exceptions
throws
Custom exceptions
What is exception handling?
Some best practices of exception handling
finally
Assert requires JVM option -ea
Exercise – Infinite loop
Answer
Summary
JVM Processes and Garbage Collection
What are JVM processes?
Loading
Linking
Initialization
Instantiation
Execution
Garbage collection
Application termination
JVM architecture
Runtime data areas
Classloader
Execution engine
Threads
Extending the Thread class
What is daemon?
Running threads extending Thread 
Implementing Runnable
Runing threads implementing Runnable
Extending Thread vs implementing Runnable
How to execute the main(String[]) method
Using IDE 
Command line with classes on classpath
Command line with a .jar file on classpath
Command line with an executable .jar file
Garbage collection
Responsiveness, throughput, and stop-the-world
Object age and generations
When stop-the-world is unavoidable
Exercise – Monitoring JVM while running an application
Answer
Summary
Java Standard and External Libraries
What are standard and external libraries?
Java standard libraries
java.lang
java.util
java.time
java.io and java.nio
java.sql and javax.sql
java.net
java.math
java.awt,  javax.swing, and  javafx
Java external libraries
org.junit
org.mockito
org.apache.log4j and org.slf4j
org.apache.commons
org.apache.commons.io
org.apache.commons.lang and lang3
org.apache.commons.codec.binary
Exercise – Comparing String.indexOf() and StringUtils.indexOf()
Answer
Summary
Java Collections
What are collections?
The java.util package
Apache Commons collections
Collections vs arrays
Here is what we are going to discuss
List - ArrayList preserves order
Prefer variable type List
Why is it called ArrayList?
Adding elements
size(), isEmpty(), clear()
Iterate and stream
Add using generics
Add collection
Implementing equals() and hashCode()
Locating element
Retrieving elements
Removing elements
Replacing elements
Sorting String and numeral types
Sorting custom objects
Comparing with another collection
Converting to array
List implementations
Set - HashSet does not allow duplicates
Preferring variable type Set
Why is it called HashSet?
Adding elements
size(), isEmpty(), and clear()
Iterate and stream
Adding using generics
Adding collection
Implementing equals() and hashCode()
Locating element
Retrieving elements
Removing elements
Replacing elements
Sorting
Comparing with another collection
Converting to array
Set implementations
Map – HashMap stores/retrieves objects by key
Preferring variable type Map
Why is it called HashMap?
Adding and maybe replace
size(), isEmpty(), and clear()
Iterate and stream
Adding using generics
Adding another Map
Implementing equals() and hashCode()
Locating element
Retrieving elements
Removing elements
Replacing elements
Sorting
Comparing with another collection
Map implementations
Exercise – EnumSet methods
Answer
Summary
Managing Collections and Arrays
Managing collections
Initializing collections
Collection constructor
Instance initializer (double brace)
Static initialization block
Factory methods of()
Using other objects and streams
Immutable collections
Immutable versus unmodifiable
Immutable without methods of()
Methods add() and put() confusion
java.util.Collections class  
Copy 
Sort and equals()
Reverse and rotate
Search and equals() 
Comparing two collections
Min and max elements
Add and replace elements
Shuffle and swap elements
Converting to a checked collection
Convert to a thread-safe collection
Convert to another collection type
Create enumeration and iterator
Class collections4.CollectionUtils
Manage arrays
Initialize arrays
Creation expression
Array initializer
Static initialization block
From collection
Other possible methods
Class java.util.Arrays
Class lang3.ArrayUtils
Exercise – Sort list of objects
Answer
Summary
Managing Objects, Strings, Time, and Random Numbers
Managing objects
Class java.util.Objects
equals() and deepEquals() 
hash() and hashCode()
isNull() and nonNull()
requireNonNull() 
checkIndex()
compare()
toString()
Class lang3.ObjectUtils
Managing strings
StringBuilder and StringBuffer
Class java.lang.String
Constructors
format()
replace()
compareTo()
valueOf(Objectj)
valueOf(primitive or char[])
copyValueOf(char[])
indexOf() and substring()
contains() and matches()
split(), concat(), and join()
startsWith() and endsWith()
equals() and equalsIgnoreCase()
contentEquals() and copyValueOf()
length(), isEmpty(), and hashCode()
trim(), toLowerCase(), and toUpperCase()
getBytes(), getChars(), and toCharArray()
Get code point by index or stream
Class lang3.StringUtils
Managing time
java.time.LocalDate
java.time.LocalTime
java.time.LocalDateTime
Period and Duration
Managing random numbers
Method java.lang.Math.random()
Class java.util.Random
Exercise – Objects.equals() result
Answer
Summary
Database Programming
What is Java Database Connectivity (JDBC)?
Connecting to the database
Closing the database connection
Structured Query Language (SQL)
Creating a database and its structure 
CREATE and DROP the database and its user
CREATE, ALTER, and DROP table
Create, read, update, and delete (CRUD) data
INSERT statement
SELECT-statement
UPDATE-statement
DELETE-statement
Using the PreparedStatement class
Exercise – Selecting unique first names
Answer
Summary
Lambda Expressions and Functional Programming
Functional programming
What is a functional interface?
Ready-to-use standard functional interfaces
Function<T, R>
Consumer<T>
Supplier<T>
Predicate<T>
Other standard functional interfaces
Chaining standard functions
Chain two Function<T,R>
Chain two Consumer<T>
Chain two Predicate<T>
identity() and other default methods
Lambda expressions
What is a lambda expression?
Re-implementing functions
Lambda limitations
Effectively final local variable
The this keyword interpretation
Method references
Exercise – Using the method reference to create a new object
Answer
Summary
Streams and Pipelines
What is a stream?
Stream operations
Creating a stream
Stream interface
empty(), of(T t), ofNullable(T t)
iterate(Object, UnaryOperator)
concat(Stream a, Stream b)
generate(Supplier)
of(T... values) 
The Stream.Builder interface
Other classes and interfaces
Intermediate operations
Filtering
Mapping
Sorting
Peeking
Terminal operations
Processing each element
Counting all elements
Matching all, any, or none
Finding any or first
Class Optional
Min and max
The toArray() operation
The reduce operation
The collect operation
Class collectors
Numeric stream interfaces
Creating a stream
range(), rangeClosed()
Intermediate operations
boxed() and mapToObj()
mapToInt(), mapToLong(), and mapToDouble()
flatMapToInt(), flatMapToLong(), and flatMapToDouble()
Terminal operations
sum() and average()
Parallel processing
Stateless and stateful operations
Sequential or parallel processing?
Exercise – Multiplying all the stream elements
Answer
Summary
Reactive Systems
How to process a lot of data quickly
Asynchronous 
Sequential versus parallel streams
Using the CompletableFuture class
Non-blocking 
The java.io versus java.nio package
Event loop, or run loop
Distributed
Scalable
Reactive 
Responsive
Resilient
Elastic
Message-driven
Microservices
Vert.x basics
The HTTP server as a microservice
Periodic service as a microservice
The HTTP client as a microservice
Other microservices
Reactive systems
Message-driven system
Message consumer
Message sender
Message publisher
Reality check
Exercise – Creating io.reactivex.Observable
Answer
Summary
Other Books You May Enjoy
Leave a review - let other readers know what you think
The purpose of this book is to give the readers a solid understanding of Java fundamentals, leading them through a series of practical steps from the basics to real programming. The discussion and the examples aim to stimulate professional intuition, using well-proven programming principles and practices.
After finishing this book, you will be able to do the following:
Install Java Virtual Machine and run it
Install and configure your integrated development environment (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
The targeted audience is those who would like to pursue a career in modern Java programming and the novice to intermediate Java programmer who would like to refresh their knowledge of the latest Java version.
Chapter 1, Java Virtual Machine (JVM) on Your Computer, introduces Java as a language and as a tool. It describes the motivation for Java creation, its history, its editions, architectural principles, and components. It also outlines the Java marketing position and the main areas of application. Then, a sequence of practical steps walk you through the process of Java machine installation and configuration on your computers and through its usage and main commands.
Chapter 2, Java Language Basics, introduces the basic concepts of Java as an Object Oriented Programming (OOP) language. You will learn about classes, interfaces, objects, and their relations, along with OOP concepts and features.
Chapter 3, Your Development Environment Setup, explains what development environment is and guides you through its configuration and tuning. It also has an overview of popular editors and build frameworks. The step-by-step instructions help the reader to create their own development environment, and configure it, including the setting of a classpath and using it in practice.
Chapter 4, Your First Java Project, uses everything that was learned so far and guides the reader through the process of writing a program and developer’s test and running them.
Chapter 5, Java Language Elements and Types, familiarizes the reader with Java language elements: identifiers, variables, literals, keywords, separators, comments, and similar ones. It also describes types—both primitive and reference. Special attention is applied to class String, enum types, and arrays.
Chapter 6, Interfaces, Classes and Objects Construction, explains the most important aspects of Java programming—Application Programming Interface (API), object factories, method overriding, hiding, and overloading. The usage of keywords this and super is also introduced here. The chapter concludes with the discussion of final classes and methods.
Chapter 7, Packages and Accessibility (Visibility), introduces the notion of a package and teaches the reader how to create and use it for better code clarity. It also describes different levels of accessibility (visibility) of classes and class members—methods and properties. It concludes with the discussion of the key OOP design concept of an encapsulation.
Chapter 8, Object-Oriented Design (OOD) Principles, presents a higher-level view on Java programming. It discusses the criteria of a good design and provides a guide to the well-proven OOD principles. It also demonstrates code examples that illustrate the discussed principles.
Chapter 9, Operators, Expressions, and Statements, helps you dive deeper into three core elements of Java programming: operators, expressions, and statements. You will see the list of all Java operators, learn details about the most popular ones, and be able to execute specific examples that illustrate the key aspects of each of them.
Chapter 10, Control Flow Statements, describes Java statements that allow building a program flow according to the logic of the implemented algorithm, including conditional statements, iterative statements, branching statements, and exceptions.
Chapter 11, JVM Processes and Garbage Collection, allows the reader to look under the hood of JVM and see that it is more complex than just program runner. It executes several service threads in addition to the application threads. One of the service threads executes an important mission of releasing the memory from unused objects.
Chapter 12, Java Standard and External Libraries, provides an overview of the most popular libraries included with JDK and the external ones. Brief examples demonstrate the library capabilities. The chapter also guides users how to find a library on the internet.
Chapter 13, Java Collections, introduces you to Java collections with code examples that demonstrate their usage.
Chapter 14, Managing Collections and Arrays, introduces you to classes that allow you to create, initialize, and modify collections and arrays. They also allow the creation of unmodifiable and immutable collections. Some of these classes belong to Java standard libraries, others to popular Apache Commons libraries.
Chapter 15, Managing Objects, Strings, Time, and Random Numbers, demonstrates classes and utilities from Java Standard Library and Apache Commons that every programmer has to master in order to become an effective coder.
Chapter 16, Database Programming, explains how to write Java code that can manipulate—insert, read, update, and delete—data in a database. It also provides a short introduction to SQL language and basic database operations.
Chapter 17, Lambda Expressions and Functional Programming, explains the concept of a functional programming. It provides an overview of functional interfaces that come with JDK and explains how to use them in lambda expressions.
Chapter 18, Streams and Pipelines, introduces the reader to the powerful concept of data stream processing. It explains what streams are, how to process them using lambda expressions, and how to build processing pipelines. It also shows how easily you can organize stream processing in parallel.
Chapter 19, Reactive Systems, provides an overview and the prospects for your future professional work. As more data gets processed and services become more sophisticated, the need for more adaptive, highly scalable, and distributed processes grows exponentially, and this is what we will address in this chapter—how such a software system looks in practice.
No prior knowledge of Java programming is expected from a reader, although some understanding of what programming is would help them to get the most from this book.
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/Introduction-to-Programming. We also have other code bundles from our rich catalog of books and videos available athttps://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/IntroductiontoProgramming_ColorImages.pdf.
There are a number of text conventions used throughout this book.
CodeInText: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: "Mount the downloaded WebStorm-10*.dmg disk image file as another disk in your system."
A block of code is set as follows:
html, body, #map { height: 100%; margin: 0; padding: 0}
When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:
[default]exten => s,1,Dial(Zap/1|30)exten => s,2,Voicemail(u100)
exten => s,102,Voicemail(b100)
exten => i,1,Voicemail(s0)
Any command-line input or output is written as follows:
$ mkdir css
$ cd css
Bold: Indicates a new term, an important word, or words that you see on screen. For example, words in menus or dialog boxes appear in the text like this. Here is an example: "Select System info from the Administration panel."
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.
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.
This book will be your guide to achieving an intermediate level of Java programming skills. Programming is not just about knowing the language syntax. It is also about the tools and sources of information necessary to write, compile, and execute a program or run a whole software system. The first step on this road is to learn the important components of Java, including Java Development Kit (JDK) and Java Virtual Machine (JVM).
This chapter will introduce Java as a language and a tool, and establish the most important terminology. It will also describe the motivation behind Java's creation, cover its history, editions, versions, and technologies, and outline Java's marketing position and main areas of application. Then, a sequence of practical steps will walk readers through the process of Java installation and configuration on their computers, and introduce the main Java commands.
In this chapter, we will cover the following topics:
What is Java?
Java platforms, editions, versions, and technologies
Java SE Development Kit (JDK) installation and configuration
Main Java commands
Exercise – JDK tools and utilities
Since this book is written for beginners, we will assume that you know almost nothing about Java. But even if you do know something, or even a lot, it is always helpful to review the basics, even if it's just so you can feel good about yourself by appreciating how much you have mastered already. So, we will start by defining the terms Java, JVM, compilation, bytecode, and more.
When talking about Java, people use Java, JVM, JDK, SDK, and Java platform as synonyms. The legal definition treats Java as Sun's trademark for a set of technologies, but we typically do not think about Java as a trademark. Most often, when somebody says Java, they mean a programming language that is used by humans to express sets of instructions (programs) that can be executed by a computer (not directly, but after the program is compiled/transformed into code that a computer understands). The human-readable Java program is called source code, and the computer-readable program (after all transformations) is called binary code, because it is expressed only using 1 and 0.
You can find the complete Java Language Specification (description) at https://docs.oracle.com/javase/specs/. It is much more accessible than one might expect, and it can be helpful even for a novice, especially if one uses it as a reference document. Do not feel discouraged by the formal language of the first few sections. Read what you can and come back later, as your understanding of Java grows and the motivation for deeper and more precise definitions increases.
Have you noticed that there are two similar terms, bytecode and byte code? In conversation, the difference is hardly noticeable, so people use them interchangeably. But there is a difference. Byte code (or Byte Code, to be precise) is a language that can be executed by a special program called JVM. By contrast, bytecode is the format (each instruction occupies one byte, thus the name) of the instructions generated by the Java compiler (another program) that reads the human-readable source code and transforms it into Byte Code.
Bytecode is a binary code expressed in the format JVM understands. JVM then reads (loads, using a program called class loader) bytecodes, transforms the instructions into binary code (instructions in a format a particular computer microprocessor, where JVM is running, understands), and passes the result to the CPU, a microprocessor that executes it.
A class is a file (with the extension .class) produced by the Java compiler (from the source code in a file with the same name and the extension .java). There are more than a dozen JVM implementations, created by different companies, but we will be focusing on Oracle JVM's implementation, which is called HotSpot. In Chapter 11, JVM Processes and Garbage Collection, we will look more closely at JVM's functionality, architecture, and processes.
On the same page as the Java Language Specification (https://docs.oracle.com/javase/specs), you can find the Java Virtual Machine Specification. We recommend that you use it as a source of references for the terminology and for the understanding of JVM functionality.
Since Java 9, applets (components that can be executed in a browser) are not supported anymore, so we will not talk much about them. An application is a Java program that can be (after compilation) executed on a computer where JVM is installed. So, JDK includes at minimum a compiler, JVM, and Java Class Library (JCL)—a collection of ready-to-use procedures that can be called by an application. But in reality, it has many other tools and utilities that can help you to compile, execute, and monitor a Java application. The subset of JDK that includes JVM, JCL, class loader, and supporting files allows the execution (running) of bytecode. Such a combination is called the Java Runtime Environment (JRE). Each Java application is executed in a separate JVM instance (copy) that has its own allocated computer memory, so two Java applications cannot talk to each other directly, but only via the network (web-services and similar means).
So, when people use SDK in reference to JDK, they are correct, but not precise.
The supporting libraries in the preceding definitions are Java standard libraries, also called JCL, and are necessary for executing bytecode. If a program requires some other libraries (not included in JCL), they have to be added at compilation time (see Chapter 3, Your Development Environment Setup, which describes how to do it) and included in the generated bytecode. Java platform can be one of the four: Java Platform Standard Edition (Java SE), Java Platform Enterprise Edition (Java EE), Java Platform Micro Edition (Java ME), or Java Card. There used to be the JavaFX Platform, too, but it has been merged into Java SE since Java 8. We will talk about the differences in the next section.
These are the most basic terms. Other terms will be introduced as needed throughout the book, in the corresponding contexts.
Java was first released in 1995 by Sun Microsystems. It was derived from C and C++, but did not allow users to manipulate computer memory on a very low level, which is the source of many difficulties, including memory leak related issues, that C and C++ programmers experience if they are not very careful about it. Java stood out due to its simplicity, portability, interoperability, and safety net, which allowed it to become one of the most popular programming languages. It is estimated that as of 2017, there are close to 20 million programmers in the world (close to 4 million of them are in the US), and approximately half of them use Java. And there are good reasons to believe that the need for software developers, including Java developers, will only grow in the future. So, studying Java looks like a step towards a stable career. And learning Java is not actually very difficult. We will show you how to do it; just continue reading, thinking, and trying all the suggestions in practice on your computer.
Java was conceived as a facility that allows users to write once, run anywhere – that is another term to explain and understand. It means that compiled Java code can run on all computers with operating systems that support Java, without the need for recompilation. As you understand already, support Java means that for each operating system, an interpreter exists that can transform bytecode into binary code. That's how run anywhere is implemented: anywhere where a Java interpreter is available.
After the concept proved to be popular and Java was firmly established as one of the major players among other object-oriented languages, Sun Microsystems made much of its JVM free and open source software, governed by the GNU General Public License (GPL). In 2007, Sun Microsystems made all of its JVM's core code available under free and open source distribution terms, except for a small portion of code to which Sun did not have the copyright. In 2010, Oracle acquired Sun Microsystems and declared itself a steward of Java technology with a relentless commitment to fostering a community of participation and transparency.
Today, Java is used in many areas, most prominently in Android programming and other mobile applications, in various embedded systems (various chips and specialized computers), desktop Graphical User Interface (GUI) development, and a huge variety of web applications, including network applications and web services. Java is also widely used for scientific applications, including the rapidly expanding areas of machine learning and artificial intelligence.
There were five primary goals in the creation of the Java language, according to Design Goals of the JavaTM Programming Language (http://www.oracle.com/technetwork/java/intro-141325.html). The Java language had to be:
Object-oriented and familiar
: This meant that it had to look like C++, but without unnecessary complexities (we will discuss the term object-oriented
in
Chapter 2
,
Java Language Basics
)
Architecture-neutral and portable
: This meant the ability
to use JVM as the environment that isolates the language (source code) from the knowledge of each particular operating system (often called the platform)
High performance
: It should work on par with the leading programming languages of the time
Interpreted
: I
t can be moved to an executing phase without linking (creating a single executable file from multiple
.class
files), thus allowing a quicker write-compile-execute cycle (modern JVMs, though, are optimized to keep the binary version of the often used
.class
files, to avoid repeating interpretation)
Multithreaded
: I
t should allow several concurrent execution jobs (threads), such as downloading an image and processing other user commands and data at the same time
Dynamic
: L
inking should happen during execution
Secure
: It had to be well protected from an unauthorized modification at runtime
The result proved these goals to be well-defined and fruitful, because Java became one of the main languages of the internet era.
In everyday discussions, some programmers use these terms interchangeably, but there is a difference between Java platforms, editions, versions, and technologies. This section is focuses on explaining it.
We hear the term platform almost every day. Its meaning changes depending on the context, but in the most general sense, it means a device or environment that allows someone to do something. It serves as a foundation, an environment, a platform. In the information technology realm, a platform provides an operating environment where a software program can be developed and executed. An operating system is a typical example of a platform. Java has its own operating environment, which comes, as we have mentioned in the previous sections, in four platforms (and six editions):
Java Platform Standard Edition
(
Java SE
): This is the edition most people mean when they say Java. It includes JVM, JCL, and other tools and utilities that allow for the development and deployment of Java applications on desktops and servers. In this book, we are going to stay within the boundaries of this edition, and will mention the other editions only in this section.
Java Platform Enterprise Edition
(
Java EE
): This is composed of Java SE, servers (computer programs that provide services to the applications), enhanced libraries, code samples, tutorials, and other documentation for developing and deploying large-scale, multitiered, and secure network applications.
Java Platform Micro Edition
(
Java ME
): This is a small-footprint (using little resources) subset of Java SE, with some specialized class libraries for developing and deploying Java applications for embedded and mobile devices – phones, personal digital assistants, TV set-top boxes, printers, sensors, and so on. There is also a variation of Java ME for Android programming (with its own JVM implementation), developed by Google. It is called
Android SDK
.
Java Card
: This is the smallest of the Java platforms, for developing and deploying Java applications onto small embedded devices, such as smart cards. It comes in two editions (quotes are taken from the official Oracle documentation found at
http://www.oracle.com/technetwork/java/embedded/javacard/documentation/javacard-faq-1970428.html#3
):
Java Card Classic Edition
, which
targets smart cards as deployed today on all vertical markets, based on ISO7816 and ISO14443 communication.
Java Card Connected Edition
, which is developed
to support a web application model, with servlets running on the card, and TCP/IP as basic protocol
and
runs on high-end secure microcontrollers, typically based on a 32-bit processor and supporting a high-speed communication interface like USB
.
Since its first release in 1996, Java has evolved through nine major versions:
JDK 1.0 (January 23, 1996)
JDK 1.1 (February 19, 1997)
J2SE 1.2 (December 8, 1998)
J2SE 1.3 (May 8, 2000)
J2SE 1.4 (February 6, 2002)
J2SE 5.0 (September 30, 2004)
Java SE 6 (December 11, 2006)
Java SE 7 (July 28, 2011)
Java SE 8 (March 18, 2014)
Java SE 9 (September 21, 2017)
Java SE 10 (March 20, 2018)
There are several suggestions regarding changing the Java versioning scheme. Since Java 10, a new time-based versioning$YEAR.$MONTH of JDK has been introduced. Also, a new Java version is planned to be released every six months, in March and in September of each year. So, Java 11 will be released in September 2018, with JVM version 18.9. We will show you how to display which JDK version you are using shortly.
The word technology is overloaded. Programmers use it for almost anything. If you look at Oracle's list of Java technologies (https://www.oracle.com/java/technologies/index.html), you will find the following list:
Embedded
, which
includes all of the previously listed Java platforms except for Java EE, with some modifications, usually with a smaller footprint and other optimizations
Java SE
, which
covers Java SE and Java SE Advanced, which includes Java SE and some monitoring and management tools for an enterprise level (
larger than just a development computer
) installation
Java EE
, as described previously
Cloud
, which
includes cloud-based reliable, scalable, and elastic services
But in the Oracle glossary (http://www.oracle.com/technetwork/java/glossary-135216.html), the following technologies are added to the list:
JavaSpaces
: A technology that provides distributed persistence
Jini Technology
: An
Application Programming Interface
(
API
)
that enables the networking of devices and services automatically
Elsewhere, on the front page of the Oracle Java 10 documentation (https://docs.oracle.com/javase/10), client technologies are listed as follows:
Meanwhile, in the Oracle Java tutorial (https://docs.oracle.com/javase/tutorial/getStarted/intro/cando.html), Java Web Start and Java Plug-In are mentioned as deployment technologies for deploying your applications to end users.
However, the biggest list of Java technologies that Oracle provides is on the page dedicated to the Technology Network (http://www.oracle.com/technetwork/java/index.html). In addition to Java SE, Java SE Advanced and Suite, Java Embedded, Java EE, Java FX, and Java Card, there are also listed Java TV, Java DB, and Developer Tools. If you go to the Java SE or Java EE pages, under the Technologies tab, you will find more than two dozens APIs, and various software components listed as technologies, too. So, one should not be surprised to find anywhere any kind of list of Java technologies.
It seems that anything related to Java has been called a technology at least once, somewhere. To avoid further confusion, from now on, in this book, we will try to avoid using word technology.
From now on, every time we talk about Java, we mean Java SE version 10. We will refer to it as Java 10, or Java, or JDK, used as synonyms, unless otherwise specified.
Before you can do any Java development on your computer, you will need JDK installed and configured. In order to do this, search the internet for the JDK download and select any link that starts with https://www.oracle.com/. The best, as of this writing, should be http://www.oracle.com/technetwork/java/javase/downloads/index.html.
If you follow the preceding link, you will see this section:
Let us call this page Page1, for further references. Now, you can click the Download link under JDK. The other two download links offer JRE, which, as you know already, only allows you to run already compiled Java programs; we need to write a program, compile it into bytecode, and then run it.
After you click, you will see a page (Page2) with this section:
These are the Java installers for different operating systems (OS). You need to choose the one that fits your OS and click the corresponding link (do not forget to click Accept License Agreement using the radio button; if in doubt, read the license agreement via the link Oracle Binary Code License Agreement for Java SE). For Linux, there are two installers – one in Red Hat Package Manager Format (.rpm), and one that is just an archived (.tar) and compressed (.gz) version. Also, noticed that in this list, there are only installers for 64-bit operating systems. As of this writing, it is not clear yet if the 32-bit version is to be dropped officially, although it was available as an early access build.
Select the installer that you need, and download it.
Now is the time to install Java, which basically consists of the following four steps:
Expand the installer
Create directories
Copy files into these directories
Make the Java executables accessible without typing the full path
To find the detailed installation instructions, go back to Page1 and click on the Installation Instructions link. Find the link for your operating system and follow the provided steps, but choose only those that are related to JDK.
Eventually, you will come to the point when you are able to run the command java -version, which will display the following:
As you can see, it shows the version for Java as 10.0.1, and for JRE and JVM as 18.3 (build 10.0.1). It is not clear yet if future versions of Java, JRE, and JVM are going to follow the same format.
Anyway, if the java -version command displays the version you tried to install, it means that you have installed Java correctly and can now enjoy working with it. From now on, every time a new version comes out, you are going to be prompted to upgrade, and you can do it by just clicking the provided link. Alternatively, you can go to the page with the installers (Page2), download the corresponding installer, launch it, and repeat the process already familiar to you.
In practice, though, programmers do not upgrade their Java installation every time. They keep their development version the same as the Java in their production environment (in order to avoid potential incompatibility). If they would like to play with a new version before upgrading the production, they might have two versions of Java installed on their computer, in parallel. In Chapter 3, Your Development Environment Setup, you will learn how to do this, and how to switch between them.
In the previous section, you saw one example of a Java command, the one that displays the JVM version. By the way, the command java starts the JVM, and is used to run bytecodes of the compiled Java programs (we will demonstrate how to do this in detail in Chapter 4, Your First Java Project).
Now, if you only run java, the output will display the short version of help. Since it is quite long, we will show it in several parts. Here is the first section:
It shows three ways to run JVM:
To execute a class, a
.class
file that contains bytecode
To execute a jar file, a file with the extension
.jar
that contains
.class
files (may be even the whole application) in a ZIP format, which also includes a Java-specific manifest file
To execute the main class in a module (a group of
.class
files and other resources that is better structured than a
.jar
file), typically an application, or a part of it
As you can see, in each of the preceding commands, a main class has to be supplied explicitly. It is the .class file that has to be executed first. It acts as the main entrance into the application, and starts the chain of loading other classes (as they are needed) to run the application. An example of such a command would be:
java MyGreatApplication
In fact, this means that there is a file, MyGreatApplication.class, in the current directory, but we should not specify the file extension. Otherwise, JVM will look for the file MyGreatApplication.class.class, which it will not find, of course, and fail to run anything.
In this book, we are not going to use any of these commands explicitly, and will leave it up to the editor to run it behind the scenes, because a modern editor does not just help write and modify the source code; it can also compile and execute the written code. That's why it is called not just the editor, but the Integrated Development Environment (IDE).
Nevertheless, we will continue to overview all of the java command options, so you will have an idea what is going behind the scenes in your IDE. To enjoy car driving, one does not need to know the details of the engine's inner workings, but it is helpful to have some idea about the principles of its operation. Besides, as your professional level grows and the applications you work on grow too and have to handle many requests, you will need to adjust the JVM configuration, so here is the first sneak peek under the hood.
Here is the next section of the output of the java command:
In the preceding screenshot, you can see two deprecated options followed by options related to classpath and module path. The last two are very important options. They allow the specifying of the location of the classes your application consists of, and the location of the libraries your application uses. The latter can be classes written by you or third-party libraries.
The concept of modules is out of the scope of this book, but module path is used very similarly to the classpath. The classpath option tells JVM where to look for the classes, while the module path tells JVM about the location of the modules. It is possible to use both in the same command line.
For example, let us assume that you have the file MyGreatApplication.class (which contains the bytecode of your program, MyGreatApplication.java) stored in the directory dir2, which is a subdirectory of the directory dir1, and your terminal window currently shows the content of the directory dir1:
As you can see, there is another directory, dir3, which we created to store another file, SomeOtherProgram.class, that is used by your application. We also put in dir4 a library of other supporting .class files, collected in SomeLibrary.jar. The command line to run your application then looks like this:
java -cp dir2:dir3:dir4/SomeLibrary.jar MyGreatApplication //on Unix
java -cp dir2;dir3;dir4\SomeLibrary.jar MyGreatApplication //on Windows
Alternatively, we can put SomeOtherProgram.class and MyGreatApplication.class in some.jar or a some.zip file, and place it in dir5. Then, the command will take one of the following forms:
java -cp dir4/SomeLibrary.jar:dir5/some.zip MyGreatApplication //Unix
java -cp dir4/SomeLibrary.jar:dir5/some.jar MyGreatApplication //Unix
java -cp dir4\SomeLibrary.jar;dir5\some.zip MyGreatApplication //Windows
java -cp dir4\SomeLibrary.jar;dir5\some.jar MyGreatApplication //Windows
Instead of -cp, we could use the options -classpath or --class-path. They are just three different conventions, so that people used to one of them can write a command line intuitively. None of the styles are better or worse than the others, although each of us has preferences and opinions. If neither of the classpath options is used, JVM looks for classes only in the current directory. Some of the classes (standard libraries) are always located in certain directories of Java installation, so there is no need to list them with a classpath option. We will talk about setting the classpath in more detail in Chapter 3, Your Development Environment Setup.
The next section of the java command output lists options that allow for validating that everything is set correctly before actually executing the application:
Since modules are outside of the scope of this book, we are skipping these and moving on to the next section of the output:
The -D option allows for setting a parameter with a value that is accessible to the application. It is often used to pass some values or flags to the application, which the application can use to change its behavior. If more information needs to be passed, then the .properties file is used (with many flags and various values), while the location of the property file is passed with the option -D. It is completely up to the programmer what has to be in the .properties file or in the value passed with the option -D. But there are best practices related to the application configuration, which also depend on the particular framework or libraries you are using. You will learn them over time, and these practices are beyond the beginner programmer course.
The -verbose option provides more information (than we have seen on these screenshots) and some specific data, depending on the flags class, module, gc, or jni, where gc stands for garbage collector, which will be discussed in Chapter 11, JVM Processes and Garbage Collection. For the other flags, you can read the official Oracle documentation, but chances are, you will not use them anytime soon.
The -version option displays the version of Java that is installed. This is very useful from day one, because it allows for checking, at any time, what version of Java is currently in use. In the previous section, we demonstrated how to do it, and the output it produces. When a new version of Java is released, many programmers install it in parallel with the one they are currently using, and switch between them, either to learn new features or to start writing code for a new version, while maintaining the old code written for the old version. You will learn how to have two versions of Java installed on the same computer, and how to switch between them, in Chapter 3, Your Development Environment Setup.
We will skip the module-related options.
The rest of the options in the preceding screenshot are related to the help. The options -?, -h, -help, and --help display what we are showing in these screenshots, and the options -X and --help-extra provide additional information. You can try all of them on your own.
The last section of the help output looks as follows:
We will not discuss these options. Just note how to use the long option (with two hyphens) explained in the last preceding line.
As mentioned earlier, a program written in Java is called a source code, and is stored in a .java file. The compilation command javac reads it and creates a corresponding .class file with Java Byte Code.
Let us run the command javac without specifying a .java file. It will show help. Let us review it in sections:
The help tells us that this command has the following format:
javac <options> <source files>
To compile just a few files, one can list them in the command line after options (if the file is not in the current directory, one has to prepend the filename with an absolute or relative path). Listed files are separated by colons (:) for Oracle Solaris, or semicolons (;) for Windows, and can be directories, .jar files, or .zip files. It is also possible to list all source files in a file and provide this filename using the @filename option (see the preceding screenshot). But do not try to remember all of this. You will rarely (if ever) run the commands java or javac explicitly. You will probably use an IDE that will do it for you (see Chapter 3, Your Development Environment Setup). That is also the reason we are going to skip most of the options listed in the preceding screenshot and will mention only two of them: --class-path (or -classpath, or -cp), which specifies where to find the .class files required by the currently compiled code, and -d, which indicates where to put the created .class files.
Here is the next section of javac help:
