Explore 1.5M+ audiobooks & ebooks free for days

Only $12.99 CAD/month after trial. Cancel anytime.

The Java Workshop: Learn object-oriented programming and kickstart your career in software development
The Java Workshop: Learn object-oriented programming and kickstart your career in software development
The Java Workshop: Learn object-oriented programming and kickstart your career in software development
Ebook1,242 pages5 hours

The Java Workshop: Learn object-oriented programming and kickstart your career in software development

Rating: 0 out of 5 stars

()

Read preview

About this ebook

Get to grips with the fundamentals of Java programming and learn to build useful applications with the help of real-world examples and engaging practical activities

Key Features
  • Build a solid foundation in Java and focus on developing real-world applications
  • Implement the fundamental concepts of object-oriented programming in your code
  • Work with external data storage systems and learn how to efficiently handle data
Book Description

Java is a versatile, popular programming language used across a wide range of industries. Learning how to write effective Java code can take your career to the next level, and The Java Workshop will help you do just that. This book is designed to take the pain out of Java coding and teach you everything you need to know to be productive in building real-world software.

The Workshop starts by showing you how to use classes, methods, and the built-in Collections API to manipulate data structures effortlessly. You'll dive right into learning about object-oriented programming by creating classes and interfaces and making use of inheritance and polymorphism. After learning how to handle exceptions, you'll study the modules, packages, and libraries that help you organize your code. As you progress, you'll discover how to connect to external databases and web servers, work with regular expressions, and write unit tests to validate your code. You'll also be introduced to functional programming and see how to implement it using lambda functions.

By the end of this Workshop, you'll be well-versed with key Java concepts and have the knowledge and confidence to tackle your own ambitious projects with Java.

What you will learn
  • Write clean, well-commented Java code that's easy to maintain
  • Debug logical errors and handle exceptions in your Java programs
  • Implement object-oriented and functional programming paradigms
  • Use regular expressions to search for information in text data
  • Work with information stored in databases using JDBC
  • Make HTTP requests from Java applications and parse the response data
  • Secure your data with cryptography and encryption
  • Write unit tests to validate your code with JUnit
Who this book is for

This Java coding book is designed for anyone who is new to Java. Whether you're an aspiring software developer, or are just curious about learning to code, then this book will get you on the right track. No prior programming experience is required.

LanguageEnglish
PublisherPackt Publishing
Release dateOct 31, 2019
ISBN9781839218118
The Java Workshop: Learn object-oriented programming and kickstart your career in software development

Related to The Java Workshop

Related ebooks

Programming For You

View More

Reviews for The Java Workshop

Rating: 0 out of 5 stars
0 ratings

0 ratings0 reviews

What did you think?

Tap to rate

Review must be at least 10 words

    Book preview

    The Java Workshop - David Cuartielles

    9781838986698cov_Low_Res.png

    The Java Workshop

    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 authors, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be 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.

    Authors: David Cuartielles, Andreas Göransson, and Eric Foster-Johnson

    Technical Reviewers: Scott Cosentino, Ashley Frieze, Corey Hendrey, David Parker, Darryl Pierce, and Shubham Shrivastava

    Managing Editor: Manasa Kumar

    Acquisitions Editor: Sarah Lawton

    Production Editor: Shantanu Zagade

    Editorial Board: Shubhopriya Banerjee, Bharat Botle, Ewan Buckingham, Megan Carlisle, Mahesh Dhyani, Manasa Kumar, Alex Mazonowicz, Bridget Neale, Dominic Pereira, Shiny Poojary, Abhishek Rane, Erol Staveley, Ankita Thakur, Nitesh Thakur, and Jonathan Wray

    First Published: October 2019

    Production Reference: 4141220

    ISBN: 978-1-83898-669-8

    Published by Packt Publishing Ltd.

    Livery Place, 35 Livery Street

    Birmingham B3 2PB, UK

    Table of Contents

    Preface

    1. Getting Started

    Introduction

    Writing, Compiling, and Executing Your Hello World Program

    Exercise 1: Creating Your Hello World Program in Java

    Basic Syntax and Naming Conventions

    Printing Out Different Data Types

    Variables and Variable Types

    Exercise 2: Printing Different Types of Data

    Primitive versus Reference Data Types

    Null

    Chars and Strings

    Exercise 3: Declaring Strings

    Doing Some Math

    Exercise 4: Solving a Simple Trigonometry Problem

    Comments Help You to Share Code

    CLI versus GUI

    Exercise 5: Running the Code from the CLI

    Activity 1: Obtaining the Minimum of Two Numbers

    Summary

    2. Learning the Basics

    Introduction

    Controlling the Flow of Your Programs

    Exercise 1: Creating a Basic if Statement

    Comparison Operators

    Exercise 2: Using Java Comparison Operators

    Nested if Statements

    Exercise 3: Implementing a Nested if Statement

    Branching Two Ways with if and else

    Exercise 4: Using if and else Statements

    Using Complex Conditionals

    Exercise 5: Using Logical Operators to Create Complex Conditionals

    Using Arithmetic Operators in an if Condition

    The Ternary Operator

    Exercise 6: Using the Ternary Operator

    Equality Can Be Tricky

    Exercise 7: Comparing Decimal Values

    Comparing Strings

    Using switch Statements

    Exercise 8: Using switch

    Exercise 9: Allowing Cases to Fall Through

    Using Java 12 Enhanced switch Statements

    Exercise 10: Using Java 12 switch Statements

    Looping and Performing Repetitive Tasks

    Looping with the for Loop

    Exercise 11: Using a Classic for Loop

    Exercise 12: Using an Enhanced for Loop

    Jumping Out of Loops with Break and Continue

    Exercise 13: Using break and continue

    Using the while Loop

    Exercise 14: Using a while Loop

    Using the do-while Loop

    Handling Command-Line Arguments

    Exercise 15: Testing Command-Line Arguments

    Converting Command-Line Arguments

    Exercise 16: Converting String to Integers and Doubles

    Diving Deeper into Variables — Immutability

    Comparing Final and Immutable

    Using Static Values

    Using Local Variable Type Inference

    Activity 1: Taking Input and Comparing Ranges

    Summary

    3. Object-Oriented Programming

    Introduction

    The Anatomy of a Class

    Working with Objects in Java

    Checking the Precedence of a Class with instanceof

    Exercise 1: Creating the WordTool Class

    Activity 1: Adding the Frequency-of-Symbol Calculation to WordTool

    Inheritance in Java

    Overriding and Hiding Methods

    Avoiding Overriding: Final Classes and Methods

    Overloading Methods and Constructors

    Recursion

    Annotations

    Interfaces

    Inner Classes

    Documenting with JavaDoc

    Activity 2: Adding Documentation to WordTool

    Summary

    4. Collections, Lists and Java's Built-In APIs

    Introduction

    Arrays

    Activity 1: Searching for Multiple Occurrences in an Array

    Sets

    Lists

    Exercise 1: Creating the AnalyzeInput Application

    Maps

    Iterating through Collections

    Exercise 2: Bringing Analytics into the AnalyzeInput Application

    Sorting Collections

    Exercise 3: Sort the Results from the AnalyzeInput Application

    Properties

    Activity 2: Iterating through Large Lists

    Summary

    5. Exceptions

    Introduction

    A Simple Exception Example

    NullPointerException – Have No Fear

    Catching Exceptions

    Exercise 1: Logging Exceptions

    Throws and Throw

    Exercise 2: Breaking the Law (and Fixing It)

    The finally Block

    Activity 1: Designing an Exception Class Logging Data

    Best Practices for Handling Exceptions

    Where Do Exceptions Come from?

    Summary

    6. Libraries, Packages, and Modules

    Introduction

    Organizing Code into Packages

    Importing Classes

    Exercise 1: Importing Classes

    Fully Qualified Class Names

    Importing All Classes in a Package

    Dealing with Duplicated Names

    Static Imports

    Creating a Package

    Naming Your Package

    Directories and Packages

    Exercise 2: Creating a Package for a Fitness Tracking App

    Building JAR Files

    Exercise 3: Building a JAR File

    Defining the Manifest

    Exercise 4: Building an Executable JAR File

    Build Tools

    Maven

    Exercise 5: Creating a Maven Project

    Exercise 6: Adding Java Sources to the Maven Project

    Exercise 7: Building the Maven Project

    Exercise 8: Creating an Executable JAR with Maven

    Using Gradle

    Exercise 9: Creating a Gradle Project

    Exercise 10: Building an Executable JAR with Gradle

    Using Third-Party Libraries

    Finding the Libraries

    Adding a Project Dependency

    Exercise 11: Adding a Third-Party Library Dependency

    Using the Apache Commons Lang Library

    Exercise 12: Using the Apache Commons Lang Library

    Using Modules

    Creating Modules

    Exercise 13: Creating a Project for a Module

    Exercise 14: Creating a Second Module Using the First One

    Activity 1: Tracking Summer High Temperatures

    Summary

    7. Databases and JDBC

    Introduction

    Relational Databases

    Relational Database Management Systems

    Installing a Database

    Exercise 1: Running the H2 Database

    Introducing SQL

    Exercise 2: Creating the customer Table

    Inserting Data into a Table

    Exercise 3: Inserting Data

    Retrieving Data

    Relating Tables

    Exercise 4: Creating the email Table

    Selecting Data from Multiple Tables

    Modifying Existing Rows

    Exercise 5: Modifying email Data

    Deleting Data

    JDBC—Accessing Databases from Java

    Connecting to Databases

    Querying Data with JDBC

    Exercise 6: Querying Data with JDBC

    Sanitizing User Input

    Using Prepared Statements

    Transactions and Rollback

    Exercise 7: Using Prepared Statements with Transactions

    Simplifying JDBC Programming

    Using Object-Relational Mapping Software

    Database Connection Pooling

    Non-Relational, or NoSQL, Databases

    Activity 1: Track Your Progress

    Summary

    8. Sockets, Files, and Streams

    Introduction

    Listing Files and Directories

    Separating Directories from Files

    Exercise 1: Listing the Contents of Subdirectories

    Creating and Writing to a File

    Activity 1: Writing the Directory Structure to a File

    Reading an Existing File

    Reading a Properties File

    Exercise 2: Creating a Properties File from the CLI

    What are Streams?

    The Different Streams of the Java Language

    What are Sockets?

    Creating a SocketServer

    Writing Data on and Reading Data from a Socket

    Activity 2: Improving the EchoServer and EchoClient Programs

    Blocking and Non-Blocking Calls

    Summary

    9. Working with HTTP

    Introduction

    Exploring HTTP

    HTTP Request Methods

    Representational State Transfer

    Request Headers

    Using HttpUrlConnection

    Exercise 1: Creating a HEAD Request

    Reading the Response Data with a GET Request

    Exercise 2: Creating a GET Request

    Dealing with Slow Connections

    Requesting Parameters

    Handling Redirects

    Creating HTTP POST Requests

    Exercise 3: Sending JSON Data with POST Requests

    Parsing HTML Data

    Exercise 4: Using jsoup to Extract Data from HTML

    Delving into the java.net.http Module

    Exercise 5: Getting HTML Contents Using the java.net.http Module

    Activity 1: Using the jsoup Library to Download Files from the Web

    Summary

    10. Encryption

    Introduction

    Plaintext

    Ciphertext

    Ciphers

    Keys

    Symmetric Key Encryption

    Exercise 1: Encrypting the String Using Advanced Encryption Standard

    Block Ciphers

    Initialization Vectors

    Stream Ciphers

    Asymmetric Key Encryption

    Exercise 2: Encrypting the String Using the RSA Asymmetric Key Encryption

    Encrypting Files

    Exercise 3: Encrypting a File

    Summary

    11. Processes

    Introduction

    Launching a Process

    Sending Input to a Child Process

    Capturing the Output of a Child Process

    Storing the Output of a Child Process in a File

    Activity 1: Making a Parent Process to Launch a Child Process

    Summary

    12. Regular Expressions

    Introduction

    Decrypting Regular Expressions

    Character Classes

    Character Sets

    Quantifiers

    Anchors

    Capturing Groups

    Escaped Characters

    Flags

    Exercise 1: Implementing Regular Expressions

    Activity 1: Regular Expressions to Check If the Entrance is Entered in the Desired Format

    Regular Expressions in Java

    Exercise 2: Extracting the Domain Using Pattern Matching

    Exercise 3: Extracting Links Using Pattern Matching

    Summary

    13. Functional Programming with Lambda Expressions

    Introduction

    Background

    Functional Programming

    Side Effects

    Deterministic Functions

    Pure Functions

    Exercise 1: Writing Pure Functions

    Immutability of State

    Exercise 2: Creating an Immutable Class

    Activity 1: Modifying Immutable Lists

    Immutable Collections

    Exercise 3: Overriding the String Method

    Functional Interfaces

    Lambda Expressions

    Exercise 4: Listing Spare Tires

    Summary

    14. Recursion

    Introduction

    Delving into Recursion

    Exercise 1: Using Recursion to Overflow the Stack

    Trying Tail Recursion

    Exercise 2: Using Recursion to Calculate Factorials

    Processing an XML Document

    Exercise 3: Creating an XML File

    Introducing the DOM XML API

    Exercise 4: Traversing an XML Document

    Activity 1: Calculating the Fibonacci Sequence

    Summary

    15. Processing Data with Streams

    Introduction

    Creating Streams

    Parallel Streams

    Encounter Order

    Closing Streams

    Terminal Operations

    Intermediate Operations

    Exercise 1: Using the Stream API

    Activity 1: Applying Discount on the Items

    Using Collectors

    I/O Streams

    Exercise 2: Converting CSV to a List

    Activity 2: Searching for Specifics

    Summary

    16. Predicates and Other Functional Interfaces

    Introduction

    Predicate Interface

    Exercise 1: Defining a predicate

    Activity 1: Toggling the Sensor States

    Consumer Interface

    Exercise 2: Producing Side Effects

    Function

    Exercise 3: Extracting Data

    Activity 2: Using a Recursive Function

    Activity 3: Using a Lambda Function

    Summary

    17. Reactive Programming with Java Flow

    Introduction

    Publisher

    SubmissionPublisher

    Subscriber

    Subscription

    Exercise 1: A Simple Application with a Single Publisher and a Single Subscriber

    Processor

    Exercise 2: Using a Processor to Convert a Stream of Strings to Numbers

    Activity 1: Let NumberProcessor Format Values as Integers

    Summary

    18. Unit Testing

    Introduction

    Getting Started with Unit Tests

    Introducing JUnit

    Writing Unit Tests with JUnit

    Exercise 1: Writing a First Unit Test

    Exercise 2: Writing a Successful Test

    Deciding What to Test

    Writing Parameterized Tests

    Exercise 3: Writing a Parameterized Test

    When Tests Won't Work—Disabling Tests

    Test Setup

    Exercise 4: Using Test Setup and Cleanup Methods

    Mocking

    Testing with Mocks Using Mockito

    Exercise 5: Using Mocks when Testing

    Activity 1: Counting the Words in the String

    Summary

    Appendix

    Preface

    About

    This section briefly introduces the coverage of this book, the technical skills you'll need to get started, and the software requirements required to complete all of the included activities and exercises.

    About the Book

    Java is a versatile, popular programming language used across a wide range of industries. Learning how to write effective Java code can take your career to the next level, and The Java Workshop will help you do just that. This book is designed to take the pain out of Java coding and teach you everything you need to know to be productive in building real-world software.

    The Workshop starts by showing you how to use classes, methods, and the built-in Collections API to manipulate data structures effortlessly. You’ll dive right in to learning about object-oriented programming by creating classes and interfaces and making use of inheritance and polymorphism. After learning how to handle exceptions, you’ll study the modules, packages, and libraries that help you organize your code. As you progress, you’ll discover how to connect to external databases and web servers, work with regular expressions, and write unit tests to validate your code. You’ll also be introduced to functional programming and see how to implement it using lambda functions.

    By the end of this Workshop, you'll be well-versed with key Java concepts and have the knowledge and confidence to tackle your own ambitious projects with Java.

    About the Chapters

    Chapter 1, Getting Started, covers the basics of writing and testing programs, a first step towards building all the code that you will find in this book.

    Chapter 2, Learning the Basics, covers the basic syntax of the Java language, especially ways to control the flow of your applications.

    Chapter 3, Object-Oriented Programming, provides an overview of OOP and details the aspects that make Java a popular language.

    Chapter 4, Collections, Lists, and Java's Built-In APIs, covers the popular Java collections framework, which is used to store, sort, and filter data.

    Chapter 5, Exceptions, provides recommendations on how to deal with exceptions on a more conceptual level, providing a list of best practices that any professional programmer will follow.

    Chapter 6, Libraries, Packages, and Modules, introduces you to various ways to package and bundle Java code, along with tools to help you build Java projects.

    Chapter 7, Databases and JDBC, shows how to use JDBC to access relational databases from your Java applications.

    Chapter 8, Sockets, Files, and Streams, aids you in working with external data storage systems.

    Chapter 9, Working with HTTP, explains how to create programs that connect to a specific web server and downloads data.

    Chapter 10, Encryption, explores how applying encryption to your software is vital to safeguard yours, or your customers, integrity, data, and business.

    Chapter 11, Processes, briefly discusses how processes function and are dealt with in Java.

    Chapter 12, Regular Expressions, decrypts what regular expressions mean and looks at how this comes in handy in Java.

    Chapter 13, Functional Programming with Lambda Expressions, discusses how Java doubles up as a functional programming language, and how lambda expressions are used to perform pattern matching in Java.

    Chapter 14, Recursion, looks at a couple of problems that are solved using the recursion technique.

    Chapter 15, Processing Data with Streams, explains how you can use streams to write more expressive programs with fewer lines of code, and also how you can easily chain multiple operations on large lists.

    Chapter 16, Predicates and Other Functional Interfaces, explores some of the valid use cases of functional interfaces.

    Chapter 17, Reactive Programming with Java Flow, talks about the Java Flow API and the advantages of the Reactive Streams specification.

    Chapter 18, Unit Testing, delves into testing with JUnit, one of the primary testing frameworks for Java.

    Conventions

    Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: You can nest if statements within any block of code, including the block of code that follows an if statement..

    Words that you see on the screen, for example, in menus or dialog boxes, also appear in the text like this: Click on Create New Project.

    A block of code is set as follows:

    if (i == 5) {

    System.out.println(i is 5);

    }

    i = 0;

    New terms and important words are shown like this: This kind of data is what we call a variable type.

    Large code snippets are truncated and the corresponding names of the code files on GitHub are placed at the top of the truncated code. The permalinks to the entire code are placed below the code snippet. It should look as follows:

    Exercise02.java

    6  if (distanceToHome > maxDistance) {

    7  System.out.println(Distance from the store to your home is);

    8  System.out.println( more than + maxDistance + km away.);

    9  System.out.println(That is too far for free delivery.);

    https://packt.live/32Ca9YS

    Before You Begin

    Each great journey begins with a humble step. Our upcoming adventure with Java is no exception. Before we can do awesome things using Java, we must be prepared with a productive environment. In this small note, we shall see how to do that.

    Installation of JRE

    To install JRE on your systems, refer to: https://www.java.com/en/download/manual.jsp.

    Installation of JDK

    To install JDK on your systems, refer to: https://www.oracle.com/technetwork/java/javase/downloads/index.html.

    Installation of IntelliJ IDEA

    While all the code present in the course runs on all Java compilers, we have used IntelliJ IDEA on our systems. All the instructions in the exercises and the activities are tailored to work on IntelliJ. To install IntelliJ on your system, visit jetbrains.com/idea/.

    If you have any issues or questions about installation please email us at [email protected].

    Installing the Code Bundle

    Download the code files from GitHub at https://packt.live/2Jgzz6D and place them in a new folder called C:\Code. Refer to these code files for the complete code bundle.

    1. Getting Started

    Overview

    In this chapter, we will be covering the fundamentals of Java. You will first learn to write and compile your first Hello World! program—traditionally the first step to practicing any new language. We will then discuss the differences between the command-line interface (CLI) and Graphical User Interface (GUI), and the relative benefits of both. By the end of this chapter, you will understand the basic concepts behind variables, know how to hold data within them, and, even, how to comment on your own code.

    Introduction

    When learning how to program in almost any programming language, the first example you will typically test is called hello world. It is the simplest application possible; the aim is to write the expression hello world to whatever user interface the programming environment offers. Executing this program will introduce you to the basics of writing code using the IntelliJ editor, utilizing different types of data to be printed to the user interface and adding comments to your code.

    When writing your first program, you will also discover how Java's syntax is constructed and how it relates to other languages such as C or C++. Understanding the syntax is key to starting to read code. You will learn how to distinguish where commands and functions begin and end, how parameters are passed over between blocks of code, and how to leave comments that will help you when revisiting your software in the future.

    This chapter covers the basics of writing and testing programs as a first step toward building all the code that you will find in this book.

    Writing, Compiling, and Executing Your Hello World Program

    In the preface, you saw how to install the IntelliJ development environment. While it is possible to write Java code with literally any text editor, we believe it is good to see how to create applications using state-of-the-art tools such as the aforementioned software package.

    However, prior to guiding you step by step through getting your first program to run, we should take a look at the code that will become your first executable running on Java. The following code listing shows the program. Read through it, and we will later revise what each one of the parts is doing:

    public class Main {

        public static void main (String[] args) {

            System.out.println(Hello World!);

        }

    }

    The first line is what we call a class definition. All programs in Java are called classes. A program might consist of several classes. Classes carry inside them everything they need to perform the task they were designed for. For a class to be executable in Java, it must contain a method called main. In this program, you can see how the Main class contains a method called main that will be printing the sentence Hello World! to the system's default output.

    The code included in the class definition (public class Main) indicates that the class itself is public, which means that it will be accessible from other programs running on your computer. The same happens for the method definition (public static void main(String[] args)). There is, however, a series of other things that require our attention:

    static signifies that there is nothing in the system instantiating the main method. Because of the way the Java Virtual Machine works, the main method needs to be static, or it will not be possible to execute it.

    void indicates that the main method will not be returning anything to any code calling it. Methods could, in fact, send an answer to a piece of code executing it, as we will see later in the book.

    main is the name of the method. You cannot assign this a different name, since it is the method that makes the program executable and needs to be named this way.

    String[] args are the parameters of the main method. Parameters are passed as a list of strings. In other words, the program could take arguments from other parts within your computer and use them as data. In the particular case of the main method, these are strings that could be entered on the command-line interface (CLI) when calling the program.

    Exercise 1: Creating Your Hello World Program in Java

    IntelliJ provides you with a pre-made hello world template. Templates help you to get started faster with your code, as they provide the components you may need to speed up development. Templates can also be used for educational purposes; this is the case when it comes to testing hello world.

    For this first exercise, start with the editor. We will leave some options as they are by default. We will later see how to personalize some of the options to better suit our needs:

    Open IntelliJ and you will see a window giving you several options. Click on Create New Project. It should be the first option in the list:

    Figure 1.1: Creating a new project on IntelliJ IDE

    Figure 1.1: Creating a new project on IntelliJ IDE

    A new interface should appear. The default options here are meant for creating a Java program, so you just need to click Next:

    Figure 1.2: Creating a new Java project

    Figure 1.2: Creating a new Java project

    Check the box to create the project from a template. Click on Java Hello World and then click Next:

    Figure 1.3: Create a Java Hello World project from template

    Figure 1.3: Create a Java Hello World project from template

    Name the project chapter01. Then, click Finish:

    Figure 1.4: Create a Hello World Project

    Figure 1.4: Create a Hello World Project

    As we haven't chosen a folder to store the projects (intentionally), IntelliJ will offer you the possibility to create a default project folder inside your user space. Click OK:

    Figure 1.5: Default project folder option on IntelliJ IDE

    Figure 1.5: Default project folder option on IntelliJ IDE

    You will see a popup with tips on how to use the software. If you have never used a development environment of this type before, then this is a good way to get information about how it functions every time IntelliJ boots up. Choose your preferences and then click Close:

    Figure 1.6: Tip on how to use the IDE

    Figure 1.6: Tip on how to use the IDE

    IntelliJ reminds you regarding the possibility of using a special tab dedicated to learning more about the environment in relation to programming. Click Got It.

    The editor presents a menu bar, a code navigation bar, a project navigation area, and the actual editor where you can see the code we explained earlier. Now it is time to test it. Click on the Run button (this is the triangle on the right-hand side of the code navigation bar).

    Figure 1.7: Execute the program by clicking on the Run button

    Figure 1.7: Execute the program by clicking on the Run button

    When the program runs, a terminal window unfolds at the bottom of IntelliJ. Here, you can see how the software called your JVM, the program's outcome, and a line from the editor reading Process finished with exit code 0, which means that no errors occurred.

    Figure 1.8: JVM showing the output

    Figure 1.8: JVM showing the output

    Note

    Since we took all the options by default for this example, you will see that our program is called Main.java. In the following chapter, we will see how to create programs that we then name ourselves.

    Basic Syntax and Naming Conventions

    The first thing you will have noticed in the hello world program, when it comes to syntax, is how we group the code into blocks marked within sets of curly braces—{ and }. The Main class contains the main method. In other words, main is nested inside Main. This is how classes are defined in Java – in principle, they contain all of the methods they are going to use.

    Another aspect of the Java syntax is that capitalization matters. If a command is defined as Print, it differs from another command called print, and the compiler will identify them as different. Capitalization falls under a convention, an unwritten rule among programmers on how names should be formatted in Java. You will have noticed that the class is called HelloWorld. In Java, the convention establishes that methods, classes, variables, and so on should be named by joining words together using capitals as a way to mark the separation between words. In addition, the names of classes should start with capitals.

    Note

    When you are starting off, it is easy to get confused between syntax, which is rigid and must be respected for the compiler to function, and conventions, which are intended for developers to better understand how code is supposed to function.

    To some extent, the Java compiler doesn't care about whitespace characters, but there is a convention about using them to make code more readable. The first code listing you saw (Figure 1.8) can be rewritten as shown in Example02.java that follows. It will have the exact same result once compiled and executed:

    public class Main {

        public static void main(String[] args) {

            System.out.println(Hello World!);

        }

    }

    The System.out.println(Hello World!) function call will print out the expected message on the CLI. The command is nested inside the main(String[] args) method definition, which is nested inside the class definition. You could add more blank spaces, but it will not affect the functionality of the program. This is part of the syntax of Java, but also of other programming languages such as C, C++, and Scala.

    Also, note that Hello World! is a String, a type of data. The following section will explore what types of data can be sent as parameters to the System.out.println() method call.

    Printing Out Different Data Types

    In Java, it is common to define methods that have the capability to use different sets of parameters. For example, the System.out.println() method can print other types of data that are not just pieces of text. You could, as an example, try to print out a simple number and see the result. Example03.java adds a couple of lines to the code to showcase different types of data:

    public class Main {

        public static void main(String[] args) {

            System.out.println(This is text);

            System.out.println('A');

            System.out.println(53);

            System.out.println(23.08f);

            System.out.println(1.97);

            System.out.println(true);

        }

    }

    The previous example will print out four lines to the CLI, representing the different arguments given to the System.out.println() method. The outcome will look as follows:

    This is text

    A

    53

    23.08

    1.97

    true

    Process finished with exit code 0

    You see six different types of data in this result: some text, a character, an integer number, two different kinds of decimal numbers, and a truth statement. In the Java programming language, we define those types of data as String, char, int, float, double, and boolean, respectively. There is a lot more to learn about data types, but let's first introduce a new topic: variables. This will help to understand why data types are important.

    Variables and Variable Types

    Variables are human-readable names given to slots of your computer memory. Each one of those slots can store some data, such as a number, a piece of text, a password, or the value of the temperature outside. This kind of data is what we call a variable type. There are as many variable types as there are data types in our programming language. The type of data we are using defines the amount of memory allocated to store the data. A byte (which is made up of 8 bits) is smaller than an integer (which is made up of 32 bits). A string comprises several characters, hence making it bigger than an integer.

    byte, int (short for integer), String, and char (short for character) are variable types. To make use of a variable, you need to define it for the compiler to understand that it needs it in order to allocate some space for storing data. The variable definition is done by first determining its type, followed by the variable's name, and then you can optionally initialize it with a certain value.

    The following code listing shows how to define a couple of variables of different types:

    // a counter

    int counter = 0;

    // a String

    String errMsg = You should press 'NEXT' to continue;

    // a boolean

    boolean isConnected = false;

    This next exercise will take you through how to modify the code listing from Example03.java in order to print out the values coming from the variables.

    Exercise 2: Printing Different Types of Data

    In this exercise, we shall declare variables of different data types and print it as an output. To do so, perform the following steps:

    Open IntelliJ. If you didn't get to try the code listing from Example03.java, let's start by creating a new project using the HelloWorld template:

    Figure 1.9: Create a new Java project

    Figure 1.9: Create a new Java project

    Once you have reached the step where you have the code generated by the development environment, copy all of the code, erase it, and paste in the code from the Example03.java listing instead:

    Try out the code, and check that the outcome is what it should be, as explained in Printing Out Different Data Types.

    Start by declaring a new variable of the String type and initialize it:

    public class Main {

        public static void main(String[] args) {

            String t = This is text;

            System.out.println(This is text);

            System.out.println('A');

            System.out.println(53);

            System.out.println(23.08f);

            System.out.println(1.97);

            System.out.println(true);

        }

    }

    Next, substitute the text in the first System.out.println() command with the variable. As the variable is linked to the piece of memory containing the string, executing the program will give the same result:

    public class Main {

        public static void main(String[] args) {

            String t = This is a text;

            System.out.println(t);

            System.out.println('A');

            System.out.println(53);

            System.out.println(23.08f);

            System.out.println(1.97);

            System.out.println(true);

        }

    }

    Continue by declaring a variable of the char type, another of the int type, one of the double type, and finally, one of the boolean type. Proceed to use the variable names instead of the values when printing out to the CLI:

    public class Main {

        public static void main(String[] args) {

            String t = This is a text;

            char c = 'A';

            int i = 53;

            float f = 23.08f;

            double d = 1.97;

            boolean b = true;

            System.out.println(t);

            System.out.println(c);

            System.out.println(i);

            System.out.println(f);

            System.out.println(d);

            System.out.println(b);

        }

    }

    With this example, not only have you learned about different types of data and the variables that store this data, but also about how methods can handle more than one data type.

    Note

    Notice how the float type, when defined, requires the letter f to be appended after the number. This way, Java will be able to distinguish between these two types of decimal variables.

    Primitive versus Reference Data Types

    Some data types are built on top of others. For example, strings are made of sequences of characters, so, in a sense, without characters, there would be no strings. You could say that characters are more core to the language than strings are. Like characters, there are other data types that are used to define the properties of a programming language. These data types, fundamental for the construction of the language itself, are what we call primitive data types.

    The following table describes some of the basic types of variables you will find in Java, along with their characteristics:

    Figure 1.10: Basic types in Java

    Figure 1.10: Basic types in Java

    The eight primitive data types represent truth levels (boolean), integral numbers (byte, short, int, and long), floating point numbers (float and double), and characters (char). Exercise 2, Printing Different Types of Data showcased how to use variables from some of these types within our programs.

    Note

    String is not a primitive data type. It is what we call a reference data type. A mnemotechnic that could help you remember why it is called reference is that it is not linking to the actual data, but to the position in memory where the data is stored; hence, it is a reference. There are other reference data types that you will be introduced to later in the book. Note that float and double are not precise enough to deal with some uses of decimal numbers, such as currencies. Java has a high-precision decimal data type called BigDecimal, but it is not a primitive type.

    Null

    In the same way that primitive data types have a default value, reference data types, which could be made of any kind of data, have a common way to express that they contain no data. As an example of a reference typed variable, the default value for a string that is defined as empty is null.

    Null is a lot more complex than that, though—it can also be used to determine termination. Continuing with the example of the string, when stored in memory, it will be made of an array of characters ending with null. In this way, it will be possible to iterate within a string, since there is a common way to signify that you have reached its end.

    It is possible to modify the content of the computer memory during the execution of a program. We do this using variables in code. The next code listing (Example04.java) will show you how to create an empty variable of the String type and modify its value while the program is running:

    public class Main {

        public static void main(String[] args) {

            String t = null;

            System.out.println(t);

            t = Joe ...;

            System.out.println(t);

            t = went fishing;

            System.out.println(t);

        }

    }

    The previous example shows how to declare an empty string, how its value can be modified throughout the program, and how the program will cope with displaying the content of an empty string. It literally prints out the word null on the CLI. See the full outcome of the program:

    null

    Joe ...

    went fishing

    Process finished with exit code 0  

    The program declares an empty variable, and by assigning new values to it, overwrites the variable's contents with new content.

    Chars and Strings

    As explained in Primitive versus Reference Data Types, strings are made of sequences of characters. A character is a symbol representing a letter in the alphabet, a digit, a human-readable symbol such as the exclamation mark, or even symbols invisible to the eye, such as

    Enjoying the preview?
    Page 1 of 1