Zero-Day Java Guide 1 – Installation and Hello Variables

Computers can do some amazing things: track trends in data to predict the stock market, identify text and handwriting in images, and even perform delicate surgery! Ironically, the computers that we praise so much are really the dumbest invention of mankind. They can’t do any of these things by themselves; they were told very precisely how to perform these operations by a human.

At the very low level, computers can only understand binary, ones and zeros, which are incomprehensible to humans. Imagine reading this book in binary! This one of the big motivations behind why people have invented programming languages: they are human-readable, logical, and have a precise syntax that can be converted into binary to tell a computer what to do. Programmers, developers, and software engineers write source code in programming languages to build desktop apps, mobile apps, hardware interfaces, and even airplane controls!

The journey that we’re about to embark on will take us through one such programming language: Java. We’ll start our journey the same way we would start with any other programming language: building the iconic “Hello World” program. Beyond that, we’ll move on to talk about what variables are and how to define them. Building on our knowledge of variables, the next section will show us operations that we can perform on those variables. From that knowledge, we’ll use operators to make decisions in our programs and repeat code. Towards the end of this book, we’ll get to the real power behind Java: object-oriented programming.

“The journey of a thousand miles begins with one step.” – Lao Tzu

What is Java?

Java is a programming language originally developed by Sun Microsystems (now Oracle) in 1991. Specifically, James Gosling is credited with Java’s creation. Since then, it’s had many revisions and has grown to be one of the most widely-used programming languages. On GitHub.com, a popular website to host software projects, there are well over a million projects that use Java. It’s used everywhere from native desktop applications that we run on our computers to web servers that bring us our favorite websites to mobile apps that we download to our phones. This is the type of programming language where one can just create a file and start coding without having to configure any compiler to a specific system or memorizing messy terminal commands. This is even easier using other programs, called Integrated Development Environments (IDEs), to help with writing Java code.

JavaVM

Since its conception, the motto for Java has always been “Write Once, Run Anywhere.” This paradigm is becoming more standard to the world of programming languages. Decades ago, other popular languages, such as C and C++, have to be recompiled for each machine we run it on. The job of the compiler is to convert human-readable source code into binary that our computer can understand. However, Java’s compiler will convert Java source code into Java byte code, which can only be understood by the Java Virtual Machine (JVM). The JVM is installable on any major operating system: Windows, Mac OS X, Linux, and more. Therefore, a Java program can be run by any operating system that has the JVM installed. Odds are, our machine already has it installed by default. However, we’ll need to install the utilities that we can use to compile our own Java code, and, although we could type in our Java code into a text editor, we’re going to use an IDE that will make writing Java code much easier.

Eclipse and JDK Setup

JDK Setup

JDK-Download-1

JDK-Download-2

Before we can begin programming in Java, we’ll need to install the tools that allow us to compile Java source code into Java byte code to be run by the JVM. These are the Java Developer Tools (JDK), and they can be found at Oracle’s website. We need to download the latest version and the appropriate version of the JDK for our operating system: 32-bit or 64-bit (x86 and x64 respectively). Go through the installer, pressing “Next” at each step and allowing it to complete. The installer will copy the Java tools to an appropriate folder (C:Program FilesJavajdk-… on Windows for example). If we were on Mac OS X, we would already have Java and the JDK installed, even though Apple uses an earlier version of Java. To verify this, we can open a terminal and type “javac -help” and it should print out options. In order to get the same effect on Windows, we would have to add the JDK directory to our PATH environment variable, but that’s not necessary for Eclipse because Eclipse can find our JDK directory by itself if we installed it in C:Program Files for example.

Eclipse

Eclipse-Download-1

Eclipse-Download-2

After we install the JDK, we have the barebones tools to compile and run Java code. Whereas coding Java in a text editor, compiling it, and running it may work for a small number of files, to properly manage a larger project, we’ll need an Integrated Development Environment (IDE). We’ll be using Eclipse since it’s free, open-sourced, and one of the most common IDEs to start Java development. To download Eclipse, we’ll need to visit the official Eclipse website and click the “Download” button. We have to be careful which Eclipse package we download. Eclipse has many different packages for different programming languages and systems like C/C++, PHP, and web applications. We’ll need to download the “Eclipse IDE for Java Developers” package in the same architecture (32-bit or 64-bit) as our computer.

Eclipse should be a ZIP file or a DMG on Windows or Mac, respectively. After opening or mounting the archive file, we’ll either find a folder or the application executable. On Windows, we’ll move the eclipse folder somewhere else in our filesystem, and inside is the eclipse.exe file that we can create a desktop shortcut to if we want. On Mac OS X, we can simply drag-and-drop the application executable in our Applications folder.

After launching Eclipse, it will ask us for a workspace to use. We can either choose the default workspace Eclipse gives us, or we can create our own folder to act as our workspace. Within our workspace folder, we’ll store different projects created and managed by Eclipse. Developers commonly have multiple workspaces for different contexts, such as one for work and one for personal projects. For our purposes, we’ll only need a single workspace.

Eclipse

After selecting a workspace, Eclipse will have a greeting screen that you can exit out of by clicking on the ‘X’ on top-left tab. Finally, we’ll be able to see the Eclipse IDE. It might seem overly complicated at first, but all of those views will make sense very soon when we get to coding in Java. On the left, we’ll see our Package Explorer view that contains all of our projects and their related files. To the right of that is the main window where we’ll type in our Java code. Clicking on a file will open that file in the main window. At the bottom of the main window, there are several tabs such as Problems, Javadoc, Progress, and, most importantly, Console. We’ll be using the Console to view our program’s output. Right of the main window, we have our Outline view. This view keeps track of any member variables, methods, or inner classes that we have in the source code file that we’re currently editing. However, this view won’t be immediately useful when we’re talking about variables, operations, and control flow that are all contained in a single method, but this view will become invaluable when we move on to object-oriented programming.

Java Basics

Hello World

In this section, we’re going to write our very first Java program! It’s a longstanding custom to write a program that prints “Hello World!” to the console when writing our first program in a new programming language so we’ll be doing exactly that. To begin, we’ll need to create an Eclipse project first by going to File->New Java Project.

Eclipse-New-Project

We’ll name it “MyFirstJavaProject” or something similar to that. Under the JRE section, make sure that we’re using JavaSE-1.8 or whatever the latest version of Java is at the moment. The new features will become apparent towards the end of the book when we’re talking about lambda expressions, for example. We’ll click on “Finish” at the bottom to create our project. After creating that project, we should see it in our Package Explorer view on the left pane. If we expand that project, we’ll see a folder called src, which stands for “source,” that doesn’t have anything in it.

Eclipse-Package-Explorer

Let’s add a source code file. We can do this by right-clicking on the src folder and clicking New->Class. We can name this class “HelloWorld” (with no spaces).

Eclipse-New-Class-Dialog

HelloWorld-Java

Although a Java class is not quite the same as a source code file, each Java source code file can only have a single top-level construct that is the name of the Java source code file. We’ll talk more about what classes and nested classes are towards the end of this book, but keep in mind that there is a distinction between a Java class and a Java source code file. There are other fundamental Java constructs, such as interfaces, that also reside in a Java source code file, but we’ll talk more about those later as well. This difference becomes more apparent if we expand any source code file in our Package Explorer and see that the first item after we expand will be the class (or interface).

In this paragraph, I’ll just give a short description of what packages are even though we won’t be using them. A large, complicated Java project might have tens or even hundreds of Java classes or interfaces. To better organize them, Java has packages which group related classes together. For example, in the Android API, there are hundreds of packages grouping similar software components such as views, location providers, and media players. Packages are meant to contain classes that support each other or share much functionality, and they are represented in our filesystem as folders within our source directory. When we don’t specify a package, Java uses a default package and stores any classes in the default package directly in the source folder.

Anyway, after Eclipse creates our class, it’ll appear in the main window and we should see the source code for our class. The first thing we have to do is to tell Java where to start the program. We do this by using the main method. In most compiled programming languages, there is a method or function, usually called “main,” that the system, or in our case, the JVM, will look for when we tell it to run an executable file. It signifies the entry point of the entire program. This concept works because these main methods have a very particular signature. In Java, the main method, or entry point of our program, looks exactly like this:

 public static void main(String[] args) {
 }

Let’s add this within the curly braces of the HelloWorld class. We see that Eclipse will automatically indent our code for us, which ultimately makes it more human-readable (the original purpose of a programming language anyway). This syntax might seem strange at first, but we’ll learn more about what the parts of it are when we talk about methods. For now, let’s say that this is the exact syntax of our main method. Within the curly braces, we can type our Java code, and it’ll be executed by the JVM line-by-line essentially. If we were to run our program right now, Eclipse would select the Console tab automatically and we would see a blank console. This is because we haven’t done anything in our main method yet! For us to print something out to the console, we’ll have to use to following line of code

 System.out.println(“Hello World!”);

HelloWorld-Final
It’s important that we type this out instead of copying-and-pasting it so we get a better feel for how to type Java code. It’s also important that we type out that code very precisely. As I’ve mentioned before, a programming language is very strict in it’s syntax. I’ll explain more about that line of code and console output in the next section, but all that’s left to do is to run it. We can run our code by right-clicking on the source code file in our Package Explorer and selecting Run As->Java Application.

Run-As

The console window should appear on the bottom pane with the text “Hello World!”
Congratulations! We’ve just written our first Java application!

Console-Output

Console Output

In the previous section, we wrote our very first Java application: HelloWorld. In this section, we’re going to learn more about console output and dissect our HelloWorld program, particularly the line that prints text out to the console. Throughout this book, we’ll be using the Java console to get input and display output. The console is simply a text interface where we can interact with the program and see it’s output. It’s similar to a command line or terminal, except we can’t run any standard commands on it. In fact, the earliest of computers didn’t have a graphical operating system like Windows, Mac OS X, or Linux; they just had a command line with a blinking cursor that users would type commands into!

Let’s take apart the line of our program that actually prints text to the console. If we remember from our HelloWorld program, we used the following line to print out to the console:

 System.out.println(“Hello World!”);

The first phrase we see is “System.” This is retrieving the operating system’s console streams. Next is “out.” This indicates that we want to use the standard output stream. Finally, we have the method call “println(“Hello World!);” The name of the method is “println” (short for print line). Following all method calls must be a set of parentheses that contain arguments, if any, to that method, namely “Hello World!” in our case. But “Hello World!” is what we call a String, more precisely a string of characters. To put this all together, we are telling the operating system’s standard output stream to print the line being represented as a string “Hello World!” We’ll expand our knowledge on this later, but this is essentially what the line of code does. We’ll be using it later on to print whatever we want to the console to see the consequences or results of operators or loops.

Errors

In this section, we’ll learn about the difference between compile-time and run-time errors as well as general tips on how to spot the sources of errors and how to fix them. Luckily, IDEs have grown to be very intelligent in their means to help the developer fix errors by proposing solutions. It is very important to note that the suggested solutions DO NOT necessarily align with what our intentions are. They’re simply just suggestions on how to make the error go away, not necessarily how to fix your program’s logic. We can use them for general guidance and common errors, but we shouldn’t rely on them for every error we might encounter.

There are two main types of errors that we might encounter in while writing Java code: compile-time and run-time. Compile-time errors occur when we try to run the Java program and it crashses. These kinds of errors are very easily picked up by Eclipse and any good IDE will suggest a fix for them. Attempting to run the error will cause a syntax error to occur and the entire program crashes without executing a single line of code. If our project has any compile-time errors, when we try to compile, Eclipse will ask us if we really want to compile incorrect code. This is usually a sign that we need to go back and look for compile-time errors.

Compile-time-error

On the other hand, run-time errors, as their name suggests, occur when we try to execute a Java application. Run-time errors compile perfectly fine, but, if we tried to run a Java application with a run-time error, it would crash when the JVM arrived at the byte code of the error. Any lines of code above the run-time error in the Java file will run just fine, however. Although IDEs are getting smarter and finding them, these types of errors are significantly more difficult to detect.

Run-time error

When errors occur, Eclipse will help us find the exact line that caused that error to occur. In the console output, we might see something like

Run-time-console-output

 Exception in thread “main” java.lang.SomeKindOfException: For something strange we tried to do!
 at java.lang.SomeKindOfException.someMethod(SomeKindOfException.java:55)
 …
 at HelloWorld.main(HelloWorld.java:9)

This is called the stack trace, and it’s very helpful for assessing what went wrong and where it went wrong. SomeKindOfException would obviously be replaced by a real type of exception that gives us some clue as to what went wrong. For example, if the console said FileNotFoundException, it’s intuitive to think that we were attempting to access a file that didn’t exist at a given file path. After the type of exception, there’s a short comment that explains even further. Following an exception, we’ll see a list of indented statement that start with “at” and list off method calls, source code files, and line numbers. If we click on one of those blue links, Eclipse will take us to that source code file and line number. This being said, it won’t be useful to look at Java’s Integer class, for example, since that’s probably not where the error occurred. We should skim that list of method calls until we find a class that we’ve written, like “at HelloWorld.main(HelloWorld.java:9)” for example. Clicking on that blue link will take us to line 9 in our HelloWorld.java file, the exact spot where the JVM said the error occurred. From this information, we can have a good chance at fixing the error.

In this section, we created our very first Java program that printed out “Hello World!” to the console. We then dissected our HelloWorld program to and saw how we can print anything we want to the console. In the next subsection, we looked at how we can handle any potential errors that might appear when we’re programming in Java as well as how to go about fixing them using Eclipse’s debugging tools. In the next section, we’re going to delve into Java code and talk about how we store information.

Variables

If we remember back to our algebra class, we know that, mathematically, we can have containers for information called variables. This is true in programming as well. Programmers need a way to store data in a program, and we do this through variables. In this section we’re going to learn about the different types of variables as well as how we can store multiple values in a single variable.

Variable Types

It is important to note that in Java, variables are strongly-typed, meaning that when we want to declare a variable, we must specify the type of variable it is. Java has many built-in primitive types that can hold different kinds of numbers, characters, and boolean values. From the table below, you can see that most of the Java primitive types are some kind of number. Take note that only floats and doubles can hold decimal values; the rest of the number primitive types can only hold integers, or positive and negative numbers with no decimal part.

Data-types

Now that we’ve seen all of the variable types, let’s see how we can declare a variable:

int someNumber;

The first thing that we have to do is to state the variable type; then, we need a name for the variable. This name allows us to refer to the content of that variable. We see that the statement ends with a semicolon. All statements in Java need to end with a semicolon because it tells the Java compiler that this is the end of a complete statement. In the above statement, we’re essentially declaring a space in our computer’s memory for an integer. We haven’t set it to any value, so Java will set the value to be zero, by default. In fact, zero is the default value for all number types. A character’s default value is ‘\u0000’, and boolean’s default value is false. If we wanted to declare and initialize this variable to some value like 5, we can do something like this

int someNumber = 5;

After this line, someNumber will have an integer value of 5. This statement is the longer equivalent to

int someNumber;
someNumber = 5;

We can declare multiple values and set them equal to each other as well.

int anotherNumber = someNumber; // anotherNumber has the value 5 as well

One thing to note is that, as you progress down the table of number values, the number types are allowed to hold values that are a type above. This means that a double can hold a value such as 3, even though 3 is technically an integer. However, the double will represent it as 3.0. This does not work in both directions, however, because Java will throw an error if you try to store a value of 3.14 in a variable whose type is int.

Characters and booleans are a little different than number types. For booleans, the only two possible values are true or false. chars are single-character unicode values and are denoted by single quotes.

boolean lightOn = true;
char firstLetter = ‘A’;

Variables can’t be named anything. First and foremost, we can’t name a variable after a reserved Java keyword, such as int or boolean. A variable can’t start with a number or have any whitespace in it. Although variables can start with a dollar sign and underscore, it’s against Java standard conventions. Throughout this book, we’ll be using the camelCase naming convention where the first word is lowercase and every successive word is capitalized. Also, it doesn’t help to name variables short, one-or-two-letter names such as km when you mean keyMap. The only place where that makes sense to do so is in loop counters, which we’ll get to soon! We’ve covered all of the Java primitive types, and now we’re going to move on to another useful data type called a String.

Strings

A String is a sequence of characters. That’s why it’s called a String! It’s supposed to represent a string of characters, including special characters. A String isn’t a primitive type, and we know this because String is capitalized. All of the primitive types are lowercase, but, by convention, class types are capitalized. Therefore a String is actually what we call a reference type. We can declare a String like any other variable, except the value is in double quotes.

String myFirstName = “Mohit”;

If we have two strings, we can concatenate them together using the plus operator that we’ll talk more about in the next section. We can also get the length of the string by calling an instance method on the variable called length().

String myFullName = myFirstName + “ Deshpande”;
myFirstName.length();

Suppose we wanted to store an entire file in a String. We’ll need to think of a clever way to encode things like line breaks, tabs, or quotes. Java has constructs called escape characters that we can directly insert into Strings so that when we go to print the String out to a console, we’ll see the line breaks and quotes. For example, if we wanted to insert a quote or new line.

String quote = “Neil Armstrong said \n\t\”That\’s one small step for a man, one giant leap for mankind.\” \n \\”;

If we were to print quote out to the console, it would appear something like this

Neil Armstrong said
    “That’s one small step for a man, one giant leap for mankind.”
 \

Escape-Sequences

The above table shows the most common escape sequences that Java support. When using an escape sequence, we can just type that exact sequence of characters, and Java will treat it as an escape sequence and not as just two subsequent characters. Now that we’ve covered the different types of variables, we’re going to learn how to store multiple values into a single variable.

Arrays

Let’s suppose that we want to store a list of names or a list of grades. We could create a new variable for each name or for each grade. This would get cumbersome very fast if we had 30 names, for example. We want to be able to create a single variable to store all of those values. Luckily, we have a construct in Java that allows us to do that: arrays.

Arrays

An array allows us to store multiple values in a single variable. Take the above image for example. This is roughly what an array looks like in our computer’s memory. We’re declaring an array of doubles called grades and assigning it these values. A very important concept to remember is that Java arrays are zero-indexed. This means that the first element or entry is at position zero. You can think of the index as being the distance from the first element. The distance from the first element to the first element is zero; the distance to the second element from the first element is one; and so and and so on. The length of an array is constant and cannot be changed after declaration or initialization.

double[] grades = new double[10]; // declaring an array with 10 elements
grades[0] = 90.7; // changing the 1st element
grades[1] = 87.4; // changing the 2nd element
…
grades[9] = 94.7; // changing the 10th element

The ellipsis just takes place of the other elements. This is how we can access and change values of an array, using the square bracket notation with the index inside of the brackets. As you see in the above example, this might get very cumbersome if we have a large array. For this exact reason, we can declare and initialize the array at the same time using curly braces. Note that the length of the array is still fixed since we are providing the number of elements in the curly braces.

double[] grades = { 90.7, 87.4, …, 94.7 };

We can declare an array of any type, but we are not allowed to mix types in an array. In the above example, we can’t add a String in the array of doubles. We can even declare multidimensional arrays, although we won’t be using them for our purposes. For example, suppose we wanted to store two-dimensional coordinates for a video game we’re developing. We could do the same thing with nested curly braces.

int[][] points = { {1, 2}, {3, 4}, {5, 6}, {1, 1} };
points[0][0] = 4; // set’s the x of the first ordered pair to 4: { {4, 2}, …}

Arrays are a Java construct that allow us to store multiple values into a single variable. It is important to note that Java arrays can only hold a single type and are a fixed length. They are also zero-index, meaning to access the nth element, we need to use the(n-1)th index. In other words, array elements start counting at zero.

To recap, in this section we learned about the different types of Java variables, how to declare them, and how to initialize them to values. Most of Java’s primitive data types are numbers, with the exception of chars, which are characters, and booleans, which are only true or false values. Among the number types, only floats and doubles can hold decimal values. We also learned that Strings can hold a sequence of unicode characters and are good for storing alphanumerical data such as text. After learning about the variable types, we saw how we can store multiple values in a single variable using a construct called an array. Strings and arrays are zero-indexed, meaning that the first character or element is at index zero. In the next section, we’re going to see how we can use operators to perform actions on these variables.