Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon

Free eBook - The Java Workshop

5 (3 reviews total)
By David Cuartielles , Andreas Göransson , Foster-Johnson
  • A new free eBook every day on the latest in tech
  • 30 permanently free eBooks from our core tech library
  1. 1. Getting Started
About this 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 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.
Publication date:
October 2019
Publisher
Packt
Pages
606
ISBN
9781838986698

 

2. Learning the Basics

Overview

In this chapter, we will be executing programs that do not have the typical linear flow that we have seen so far. You will first learn to use if, else, else if, and switch-case statements to control the flow of your programs. You will practice running for, while, and do-while loops in order to perform repetitive tasks in Java, and how to pass command-line arguments to modify how programs run. By the end of this chapter, you will be able to implement immutable, static (global) variables, alongside Java's variable type inference mechanism.

 

Introduction

Business applications have lots of special-case conditions. Such conditions may include finding changes in allocation rules starting at a particular year, or handling different types of employees differently based on their designation. To code for such special cases, you will require conditional logic. You basically tell the computer to perform a set of actions when a particular condition is met.

Before we delve into advanced Java topics, you need to know the basics of Java syntax. While some of this material might seem simple, you'll find you need to use the techniques and syntax shown in this chapter repeatedly in your applications.

As you've seen in Chapter 1, Getting Started, Java's syntax borrows heavily from C and C++. That's true for conditional statements that control the flow of your programs as well. Java, like most computer languages, allows you to do this. This chapter covers the basic syntax of the Java language, especially ways in...

 

Controlling the Flow of Your Programs

Imagine paying a bill from your e-wallet. You will only be able to make the payment if the credit balance in your e-wallet is greater than or equal to the bill amount. The following flowchart shows a simple logic that can be implemented:

Figure 2.1: A representative flow chart for an if-else statement

Here, the credit amount dictates the course of action of the program. To facilitate such scenarios, Java uses the if statement.

With the if statement, your application will execute a block of code if (and only if) a particular condition is true. In the following code, if the happy variable is true, then the block of code immediately following the if statement will execute. If the happy variable is not true, then the block of code immediately following the if statement will not execute.

boolean happy = true;// initialize a Boolean variable as true
if (happy) //Checks if happy is true
    System.out...
 

Looping and Performing Repetitive Tasks

In this chapter, we cover using loops to perform repetitive tasks. The main types of loop are as follows:

  • for loops
  • while loops
  • do-while loops

for loops repeat a block a set number of times. Use a for loop when you are sure how many iterations you want. A newer form of the for loop iterates over each item in a collection.

while loops execute a block while a given condition is true. When the condition becomes false, the while loop stops. Similarly, do-while loops execute a block and then check a condition. If true, the do-while loop runs the next iteration.

Use while loops if you are unsure how many iterations are required. For example, when searching through data to find a particular element, you normally want to stop when you find it.

Use a do-while loop if you always want to execute the block and only then check if another iteration is needed.

Looping with the for Loop

A for loop executes the same block...

 

Handling Command-Line Arguments

Command-line arguments are parameters passed to the main() method of your Java program. In each example so far, you've seen that the main() method takes in an array of String values. These are the command-line arguments to the program.

Command-line arguments prove their usefulness by giving you one way of providing inputs to your program. These inputs are part of the command line launching the program, when run from a Terminal shell window.

Exercise 15: Testing Command-Line Arguments

This exercise shows how to pass command-line arguments to a Java program, and also shows how to access those arguments from within your programs:

  1. Using the techniques from the previous exercises, create a new class named Exercise15.
  2. Enter the following code:
    public class Exercise15 {
        public static void main(String[] args) {
            for (int i = 0; i < args.length; i++) {
      ...
 

Summary

This chapter covered a lot of Java syntax—things you need to learn to be able to tackle the more advanced topics. You'll find yourself using these techniques in just about every Java application you write.

We started out by controlling the flow of the program using conditional statements such as if, else if, else, and switch statements. We then moved on to the different loops that can be used to perform repetitive tasks. After this, we looked at how to provide values during runtime using command-line arguments. This is one way to pass inputs to your Java applications. Every example in this chapter created a class, but we have not yet done much with these classes.

In the next chapter, you'll learn about classes, methods, and object-oriented programming, and how you can do a lot more with classes.

About the Authors
  • David Cuartielles

    David Cuartielles is a doctorate in interaction design and a postgraduate in telecommunications. He has a strong interest in building technology for humans, and that implies creating platforms and tools that help people to easily perform complex tasks. He is a co-founder of the Arduino platform and also lectures at the Malmo University. He teaches at different universities all over the world, and has spoken in the fields of technology, education, and free/open licensing models. As the CTO in education for Arduino, he advises governments about possible ways of creating new educational programs using state of the art technology (and not just Arduino).

    Browse publications by this author
  • Andreas Göransson

    Andreas Göransson is a software consultant focusing on Android application and platform development. He has several years of experience from teaching software development in different languages at the university in Malmö. In the past few years, he has been helping small start-ups an

    Browse publications by this author
  • Foster-Johnson

    Eric Foster-Johnson is a veteran programmer who writes enterprise software in Java, Grails, and other JVM technologies. He is a consultant for ObjectPartners. He has authored and co-authored more than 20 books, including Red Hat RPM Guide, Teach Yourself Linux, and Perl Modules.

    Browse publications by this author
Latest Reviews (3 reviews total)
Your Workshop series is fantastic.
Service was great and prompt
5 * for the very good offers in terms of price and variety.
Recommended For You
The Python Workshop

Learn the fundamentals of clean, effective Python coding and build the practical skills to tackle your own software development or data science projects

By Andrew Bird and 4 more
The C++ Workshop

Learn to create high-performance, error-free programs by understanding the core principles and techniques behind programming in C++

By Dale Green and 2 more
Responsive Web Design with HTML5 and CSS - Third Edition

Harness the latest capabilities of HTML5 and CSS to create a single UI that works flawlessly on mobile phones, tablets, and desktops — plus everything in-between

By Ben Frain
The Complete Python Course [Video]

Master Python and OOP concepts and structure your programs like a professional

By Codestars By Rob Percival and 1 more