Java Programming The Beginning Beginner's Guide PDF
Java Programming The Beginning Beginner's Guide PDF
TABLE OF CONTENTS
ABOUT THE BEGINNING BEGINNERS GUIDE SERIES . 4
CHAPTER 1: WRITING YOUR FIRST PROGRAM . 8
CHAPTER 2: INPUT AND OUTPUT.. 22
CHAPTER 3: VARIABLES.. 40
CHAPTER 4: CONDITIONALS AND LOOPS .. 56
CHAPTER 5: DEALING WITH DATA.. 77
CHAPTER 6: PUTTING IT ALL TOGETHER. 103
ONLINE COURSES FROM LEARNTOPROGRAM 125
Were going to be using a language called Java in this book. Installing Java on your
machine is rather simple and the process is generally the same for most major operating
systems. With your browser youre going to want to navigate to oracle.com. Oracle is the
company that maintains Java, and the JDK (Java Development Kit) that you need to
download to write code in Java.
Once at Oracle.com, find Downloads on the top menu bar and click on Java for
Developers under Popular Downloads.
Figure 1.2: Oracle.com with the Downloads menu open.
After clicking that link you will see a download page. A dialog box will appear that reads
JDK, with a download button under it. When you click it, it will redirect you to a page
where you can select your operating system. The website will provide a set of instructions
detailing how to go about installing the JDK onto your computer. Figure 1.3: The terminal
in the authors computer. Note that the author changed the default colors through the
terminals preferences
In the event that youd rather not go through the process of installing a JDK to your
machine I recommend you use the virtual Linux server provided by my friends at
Koding.com. Point your browser to www.Koding.com and register for their free account.
The free account gives you a virtual Linux machine that you can access through your web
browserand it can compile and run Java code right out of the box! No downloads are
required.Its what I used to write the code well be using in this book.
Once you have your account, click the button to turn on your Virtual Machine(VM) and
get coding.Youll be using a text editor on Koding to type Java files and the terminal to
run them.
Figure 1.4: Command Line (or Terminal) in Koding.com.
Writing and Running Your Code
Now that you have your environment setup, its time to (finally) write some code. Well
write code in a text editor. A text editor is different than a word processor. A word
processor will introduce invisible formatting code into a file. If you were to run code
written in a word processor it would likely cause an error due to the embedded formatting
code.
A text editor, on the other hand, saves the text you enter as pure text without
introducing any unnecessary formatting. The text produced by a text editor can be easily
processed by the Java compiler. Within the command line environments in the
Koding.com virtual machine and on the Mac there are two text editors you can use. They
are known as nano and vi. These text editors have a heritage that goes back to the 1970s
so as you use themyou can truly feel old school! The other option is to use the default
text editor on Koding, TextEdit on a Mac or Notepad on Windows. Theyre all rather selfexplanatory, although some may need a few settings changed to highlight Java code. As a
side note, make sure that whenever you first save your code files, you save them as
filename.java.
nano
Nano is an easy to use Linuxbased editor. Its pretty intuitive. You can simply start typing
your code when the nano environment loads. Nano has a number of control codes which
are listed at the bottom of your screen for your reference. The most important to note are
CTRLO which saves your file and CTRL-X which exits nano and returns you to the
command line.
By default, nano will save your file in the same folder you were in when you opened nano
itself.
It should be at least somewhat evident what this code does. The println() function prints
content to the command line. In this case you are printing two strings. Strings are simply
lines of characters. Strings are always enclosed in quotes.
Once youve typed the code, its time to run it. In nano, save your file by typing CTRL-W.
When prompted, enter the filename
HelloWorld.java. The .java extension indicates that this is a Java source code file. Next
enter CTRLX to quit and youll return to the command line. In vi, enter command mode
and then save your file by typing :w HelloWorld.java. This writes your file under the
appropriate file name. Finally, in vi, hit :q to quit and return to the command line. In any
other editor, including the one on Koding, generally you can open a menu and click save
as just like you would in any other computer program.
Notice that the filename we gave this program matches the name of the class
(HelloWorld). This is the Java standard. This standard makes class files easily identifiable
in build when you have multiple source files. So for housekeeping purposes, whenever
you make a new .java file make sure that the name of the class in the code (which is
written after public class in the first line of the code.) matches the name of the file. This
way anyone reading your code willknow which .class file is associated with what.java
file.
Figure 1.7: Saving your file in Koding.
Now that you have typed your code into an editor, open your terminal, and your cursor
should appear at the prompt. Run the program by entering the following at the prompt
(dont type the $that just represents the prompt itself):
$ javac HelloWorld.java $ java HelloWorld
The first line here commands Java to compile the source code that you wrote into whats
known as Javabyte code and write it to a .class file. This byte code is executed by the
Java Virtual Machine (or JVM) whenever you run your program. JVMs can be installed on
numerous devices, from cellphones to supercomputers, and they all do the same thing: run
Java code. The result of this is Javas ability to run on multiple platforms. So long as a
JVM is installed on a machine, it can run the compiled Java code that you write.
The second line instructs Javato actually run whats in the .class file. Note thatthe .class
is implied. You dont have to type it when you run your code. If you open the folder where
the file is saved, you will see it as a .class file though.
If youve done everything correctly you should see the result of your program printed
before the next prompt.
Figure 2.1: Execution of the Square.java program which takes input from the user via the
Java .nextFloat() function.
On the first line of this program, we encounter the import statement. Imports are used in
many languages to add an additional library of commands to the language that are not in
the language core. In this case, were adding the Scanner object from the util library
which contains a number of utilities and useful objects.
If you want to import the entire library, all you have to do is replace Scanner with an
asterisk (*).
For example:
import java.util.*;
While this is useful, understand that in much larger programs importing an entire
libraryjust to get one object like were doing here makes your program less efficient. Its
like grabbing your whole tool box when you just need a hammer.
Now, based on context and the program execution, youve probably already guessed what
the nextInt()function does. Lets break it down:
public static void main (String[] args) {
Scanner grabAge = new Scanner(System.in);
System.out.println(How old are you?);
int age = grabAge.nextInt();
}
The first line of this class creates a Scanner object. Scanners are the object we use to
obtain input from the command line.
In the example above, whatever the user types at the prompt How old are you? is going
to be assigned to the variable agevia the Scanners nextInt method. Were going to take a
closer look at variables in the next chapterfor right now, just consider variables a
temporary storage place for values. These values can be strings, floats, or integers. You
must declare variables before using them. Generally the syntax is the datatype followed by
a name to reference the variable.
You may be wondering what a datatype is. Datatype determines what a variable can
contain, and what operations can be performed on it. Some examples of datatypes include
integers, strings, and floating point numbers.
Heres an example of the declaration of an integer variable:
int name;
Note: Int indicates that the datatype for this variable is an integer.
Remember to import the Scanner object or the util library before declaring a Scanner
object. Otherwise, your program will encounter an error.
Lets try a new example. Create a new file in your text editor called StringInput.java. You
can do this in vi, for example, by typing the following command on the command line: vi
StringInput.java.
Key in the following code:
import java.util.Scanner;
public class StringInput{
public static void main (String[] args) {
Scanner input = new Scanner(System.in); System.out.println(Whats your name? );
String name = input.nextFloat();
System.out.println(Hello + name); }
}
Exit your text editor and compile the program from your command line with the command
javac StringInput.java.
Figure 2.2: Uhoh. This cant be good. Weve made an error. How do we fix it?
So what happened? Instead of compiling and allowing the code to run, the program exited
with an error. Luckily the error is easy to fix. The nextFloat() function is designed to
accept the float datatype and only that datatype. When you enter anything that isnt a
floating point number, it causes the error you see in figure 2.2. We have a different
function that is intended for string use, called nextLine().
Edit your code as follows:
import java.util.Scanner; public class StringInput{
public static void main (String[] args) {
Scanner input = new Scanner(System.in); System.out.println(Whats your name? );
String name = input.nextLine();
System.out.println(Hello + name); }
}
Note: The scanner has a function to obtain every kind of data type.
Here are some examples:
nextLine() : Strings
nextInt(): Integers
nextFloat(): Floating point numbers nextDouble(): Doubles
You can probably recognize the pattern. The documentation of the methods for the
Scanner object is available here:
http://docs.oracle.com/Javase/7/docs/api/Java/util/Scanner.html
Learning how to read the Java documentation is an important skill itself.
Figure 2.3:
So much better with nextLine()!
When youre working with strings, you should use the nextLine() function which does not
scan for a datatype other than Strings. Itll always return whatever the user enter into the
prompt as a string, including numbers or symbols.
Errors
The preceding example was probably one of the first examples of an error that youve
encountered. This type of error is known as a Runtime error. Its one of three types of
errors that can occur when writing Java code.
These three types are:
Syntax errors:
Syntax errors are issues with the formatting of your code. Examples include forgetting
semicolons, not closing your brackets or misspelling method names. Text editors generally
do a great job of pointing these out, so fixing them is rather simple.
Runtime errors:
Runtime errors are a bit trickier to catch. Syntactically, all runtime errors are correct, so
your text editor wont point them out to you. The issue occurs when something
unexpected happens and results in the program failing to execute at runtime. The result is
your program fails to compile or execute properly. Examples include trying to divide by
zero or trying to call up a file that doesnt exist. Javawont encounter the error until it
attempts to execute the code.
Logic errors:
These are errors in the actual logic behind the program. They are the most challenging
errors to fix, because the code isnt technically wrong, its just not giving the correct
result. Some logical errors go undetected even after the program is released. Examples
include things like dividing where you should be multiplying, printing the wrong output,
or opening thewrong file. If you have a logic error, youre having a PICNIC. (Problem In
Chair, Not In Computer.)
Parameterized Input
Your current workflow forces you to compile and then run your code before passing input.
Including parameters with your Java command passes input and executes your code in
tandem. The resulting command looks like this:
$ java ClassName arg1 arg2 arg3
In the example above, we still use the Java command and the class name of the program
wed like to run. We follow the class name with arguments which get sent as input to the
program. This could be advantageous in situations where we want our program to run
unattendedlike when were crunching numbers. For example, if we wanted a program to
receive the users name and age as input, the parameters might look something like this:
$ java moreInput Keshav 17 The values Keshav and 17, which are separated by a
single space, are passed to the program. Lets see how. Key in the following example and
save it as MoreInput.java:
public class MoreInput{
public static void main (String[] args) {
System.out.println(Your name is: + args[0]); System.out.println(Your age is: +
args[1]);
System.out.println(All the arguments: );
System.out.println(args[0] + , + args[1]); }
}
Next, lets run the program and supply command line arguments as input:
$ java MoreInput Keshav 17 You should get a result similar to the one pictured in figure
2.4:
Figure 2.4: Command line parameters being processed as input on the Koding command
line.
NOTE: The terms parameter and argument can be used interchangeably.
The arguments come into Java numbered sequentially, so in our case, the users name is
argument number zero and the age is argument number one. In code, we call these args[0]
and args[1], respectively. If you study the screenshot carefully, you may notice something
interesting-args[1] is not the first parameter.
This is because Java starts counting at 0, rather than 1. This means that the first argument
we entered, which in this case was a name, is actually in slot 0. As a result Java is often
referred to as a zero-indexed language.
Output to a Filestream
So far the codes output has only been directed to the command line. This doesnt always
have to be the case. Output can be directed to a file for more permanent storage. Being
able to store data (more or less) permanently is an important skill for programmers to
learn. Lets write a program in which we ask the user to enter several pieces of data and
we then store those in a file.
Key in the following code:
import java.io.*;
import java.util.Scanner; public class Storage{
public static void main (String[] args) {
Scanner grab = new Scanner(System.in);
System.out.println(Whats your name?); String name = grab.nextLine();
System.out.println(Whats your email?); String mail = grab.nextLine();
System .out.println(Whats your favorite band?);
This is definitely the most complex program weve written yet. Go ahead and run it on the
command line and make sure you dont get any errors.If youre having issues remember to
check the imports. If everything runs correctly, your command line should look something
like this:
Figure 2.5: The program stored the data in a file called Keshav .txt which is now available
in the directory listing by using the ls command on the command line.
Note: I wrote and saved the file in a separate folder, and needed to navigate to where the
file was beforehand using the cd (change directory) command.
While the code for this program is somewhat longer than what you are used to at this
point, it is still fairly straightforward. When the program runs it prompts the user for their
name, email, and name of their favorite band. We then create a new variable called saver.
Saver takes the information the user typed and formats it to increase readability. It then
prints the information to a file.
The objects we use to print to a file are located in the Java.io library and were going to
need a couple of objects, so import the whole thing.
The fname variable , which stores the filename for the file were creating, is populated
bythe variable that holds the users first name. When we create the new PrintWriter object,
we pass in the filename. This is required so the PrintWriter knows what to name the file it
creates.
The next part of the program is where the action happens:
public static void main (String[] args) {
try{ PrintWriter saver = new PrintWriter(fname);
saver .println(Name: + name);
saver.println(Email: + mail);
saver.println(Band: + band);
saver.close();
}
catch(FileNotFoundException e){
System.out.println(Oh no, it didnt work!);
}
System .out.println(name + | + mail + | + band + has been stored to + name +
.txt.);
}
}
The first thing we do in the program is create a PrintWriter. This is an object that allows
us to create and then print to raw text (.txt) files. We named it saver and pass in the string
fname as a parameter. When the writer created our file, this string becamethe files name.
Next we use our PrintWriter object and began printing strings to the text file. Finally we
closed the object and printed to the console that we have created a file with the
information that the user provided us with.
Note that this entire process is done within a try-catch statement. A trycatch statement is
used to handle exceptions, which are events that interfere with the execution of your
program. In the try block we put code that could possibly cause (AKA throw) an
exception. In the catch block, we put code that executes if an exception is thrown. The
parentheses contain the type of exception and the name we give it. In thiscase we just print
Oh no, it didnt work! in the event that we get an exception.
Figure 2.6 We opened Keshav.txt in the text editor and you can see the data that has
been written to the disk.
Congratulations! Youve written a program that stores data permanently. You are well on
your way to being a programmer!
Chapter 3: Variables
In the previous chapter, we looked at input and output, which allow us to get data into and
out of our Javaprogram. In this chapter well take a closer look at one of the most
important aspects of programming variables. You may not equate variables with
computer programming, but youve likely been using variables since high school if you
took courses in Algebra, Chemistry, and Physics. In classic solve for x problems, x is a
variable.
Lets first take a look at how the Java programming environment handles variables.
Declaring and Initializing Variables
Java is what is known as a strongly-typed language. This means that variables need to be
declared before they can be used. In Java, variables are differentiated by the type of data
they hold. The type of data is referred to the variables datatype.
There are two types of variables in Java: primitive type and class (also called reference)
type.
Primitive Variables
In Java, there are eight primitive data types. They are the byte, short, int, long, float,
double, boolean and chars.
The declaration and initialization statements are generally very short, and reserve a
specific amount of memory depending on what type the variable is. Heres an example of
a declaration and initialization for an integer, done in one line:
int name = 93;
Class Variables
Class type variables, also called reference type variables, are generally more complex than
primitive types. In most cases primitive types are the building blocks of class type
variables. When you declare and initialize a class type variable, the name doesnt
represent the object itself, rather it points to the memory location that has all of the parts
and information that make up the object.
There are hundreds of different class type variables out there, and they all do different
things. One youve already encountered is a Scanner.
Heres the declaration and initialization, one more time:
Scanner name = new Scanner(<parameters>);
Strings
Strings in Java are actually class or reference type variables. They can, however, be
declared like primitives. This was a sort of short cut put in by the Java developers to make
dealing with strings a bit easier, as theyre one of the most common datatypes and are used
just as much as the primitives. (Think about how much youve used them already!)
If you like, you can declare strings like you would class type variables, but theres really
no advantage in doing so.
It would look like this:
String blogName = new String(Edukwest!);
NOTE: Due to strings being class type, they cannot be compared like primitive types
Save your file as Variables.java and run it with the Java command. Your output should
appear similar to figure 3.1
Floating Point Values: Floating point variables contain more precise numbers that have a
whole number and fractional amount represented by a decimal point value.
Variables are dynamic, in that the value can be changed or reassigned through the life of
the program. Imagine, for example, that in a video game you have a variable that tracks
the players score. As the players score changes, that value would go up until the game is
over. Once the game ends, the value inside the players score variable might be reassigned
the value zero.
Consider the following code:
import java.util.*; public class Var2{
public static void main (String[] args) { Scanner names = new Scanner(System.in);
String firstName, lastName, middleName, fullName;
System .out.println(Whats your first name?);
firstName = names.nextLine();
System.out.println(Whats your last name?);
lastName = names.nextLine();
fullName = firstName + + lastName;
System.out.println(fullName);
System.out.println(Whats your middle name?);
middleName = names.nextLine();
fullName = firstName + + middleName + + lastName;
System.out.println(fullName);
}
}
Entering the code and running the program yields the following result:
Figure 3.2: During the lifetime of the fullName variable, the value is reassigned
Note that when we first declare the fullName variable, it is assigned the values of first
and last concatenated by the + sign. That value is then printed to the console. As the
program continues to execute, the value of fullName is reassigned to include the variable
middle as well. When a variable is assigned a new value, its original value is cleared and
replaced with the new value.
In this program, we also declared four Strings in one line. Due to all the variables being of
the String type, we were able to separate the four strings names with commas, and assign
them values later on. Being a statically typed language, Java requires us to declare our
variables before use. Being a staticallytyped language doesnt necessarily mean we have
to assign initial values (or initialize) the variables upon declaration. You can do this with
all types of variables.
Arithmetic with Variables
Variables are frequently used as part of arithmetic expressions in Java. Arithmetic in Java
is no different than the arithmetic you learned in grade school. The following symbols are
used:
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus
If you are new to programming, modulus may be unfamiliar to you, but the concept is
easymodulus is the remainder after division. For example:
10 % 3 = 1
11 % 3 = 2 12 % 3 = 0
I frequently use modulus when programming in order to determine if a number is even or
odd. Any even number used with modulus two will result in zero.
Talk the Talk: Mostprogrammers will say mod for short when they are talking about
modulus.
Math with variables looks pretty much as youd expect. There are a few oddities that well
cover later though.
Key in the following example program. Youre free to forgo copying the comments:
public class MathDemo{
public static void main (String[] args) {
int alpha = 3; int bravo = 13;
System .out.println(alpha + bravo); System.out.println(alpha bravo); System.out.println(bravo * alpha);
System.out.println(bravo / alpha); //Note:
13/3 is not really a whole number.
System.out.println(bravo % alpha);
System .out.println((double)bravo/(double)alp ha);
/* Because weve casted the numbers as doubles, the real value is displayed. */
}
}
In this program, two variables are declared as alpha and bravo. Then the operands are put
in five expressions using addition, subtraction, multiplication, division and modulus.
Both of these numbers, however, are integers. Integers can only be whole numbers
between (2^31)-1 or -2^31. So expressions of the integer datatype have any numbers after
the decimal point truncated.
This means that if an expression results in 3.9, but is printed as an int, itll simply print 3.
We can avoid this issue by doing whats known as type casting. This changes the
variables type just before doing the math and printing, meaning well get the real answer
rather than an approximation.
Java requires you to identify the types of your variables. When using
variables of different types together, you may have to explicitly state what
type of variable you want the answer to be. As a rule of thumb: small
variables types automatically transfer up, but large variables must
manually be casted down.
This is the hierarchy:
byte < short < int < long < float < double
Using an int with a float requires no typecasting. Getting an answer as an
int with a float and int DOES require you to explicitly cast your variable.
A final print statement uses the modulus statement in an expression. When you run the
program with the Java command, the result should appear similar to this:
Figure 3.3: Java program evaluating several mathematical expressions and outputting the
result to the console.
When working with arithmetic in programming, its important to keep in mind the order of
operations. Java will always follow the order of operations when doing math. As a result
its a good idea to make sure that any expressions you formulate take into account the
Figure 3.4: Different expressions are evaluated in a Java program demonstrating the order
of operations.
Was the result always what you expected? The order of operations determines what part of
a mathematical expression is evaluated first. Expressions are evaluated from left to right
generally, but the specific order of operations is:
1) Parenthesis 2) Exponents
3) Multiplication 4) Division
5) Addition
6) Subtraction
NOTE: Despite multiplication coming before division and addition coming before
subtraction, Java treats them as though they are on the same level and evaluates them left
to right.
A common error made by new programmers is to incorrectly interpret the order of
operations within a math-related problem. When this happens, a program will still run, but
often give an incorrect result.
There are many more advanced mathematics tools available in Java within the Math class.
Utilizing this class will allow you to round numbers, use exponents, square roots, and
much more. The documentation is available here:
http://docs.oracle.com/Javase/7/docs/api/Java/lang/Math.html
Working with Strings
Manipulating strings is a common task for programmers. Imagine, for example, youre
given a list of data where first and last names are combined into a single field. Using
string manipulation techniques, youd have to separate them into separate fields by
extracting data from the string.
Java s String Methods will allow you to manipulate strings in every way imaginable.
You can see the documentation on the String Methods here:
http://docs.oracle.com/Javase/7/docs/api/Java/lang/String.html
Lets work with a few String Methods. Copy the following program. This program
demonstrates just a few of the string functions. You dont have to type the embedded
comments if you dont want to. They are just for your reference.
public class Strings{
public static void main (String[] args) {
String phrase = The quick brown fox jumped over the lazy dogs.;
//Prints the number of characters in the String System.out.println(phrase.length());
//Finds the index of the word fox.
System.out.println(phrase.indexOf(fox));
//Replace jumped with a new word.
System.out.println(phrase.replace(jumped , hopped));
//Changes case
System.out.println(phrase.toUpperCase()); System.out.println(phrase.toLowerCase());
} }
Once you run the program, you should see a result similar figure 3.5:
Figure 4.1: Program being tested for three different types of user responses
This program is pretty straightforward. Whats new is the if statement. In this case were
determining if the value the user entered is greater than or equal to 21. The portion of the
if statement written like this: age>=21 is known as the condition. Every conditional
statement has a condition that is evaluated to be true or false. If its true, the code indented
underneath and in brackets the conditional statement is executed. If its false generally its
skipped.
Note in the example shown in figure 4.1, the program responds You are legally able to
drink only if the user enters a value 21 or greater. Java uses brackets to contain blocks of
code, so after you open the bracket make sure you close it back up or else your program
wont compile properly. Make sure that you only keep the code you want to execute
within the brackets of the conditional.
If the code block that runs if the condition is true extends more than one line, please note
that each line should be within the brackets of the conditional. Its also good practice to
have the same level of indentation below the conditional statement. It wont affect how the
code runs, but it makes the code look much cleaner. Other programmers reading your code
will thank you.
What Else?
The program we wrote responds only if the conditional is evaluated as true. If the
conditional is evaluated as false, the user receives no response. This is likely confusing for
the user. Were going to add to the program so that it reacts one way if the condition is
evaluated as true and another way if the condition is evaluated as false. Add the indicated
code to your class.
import java.util.*;
public class Drink{
}
else{
System.out.println(Sorry, you didnt make honor roll. Better luck next time.); }
}
}
Test your program and see what kind of result you get. Your result should be similar to
what appears in figure 4.3:
With apologies to those 59 and older, this program provides feedback based on the age the
user enters. First the user enters their age and this value is assigned to the variable age.
The value entered by the user is then tested in the first part of the if statement. If the age is
less than 18, the program responds with Youre a kid! Go to school.
If the first condition turns out to be false, the else if condition is evaluated. If the age is
less than 29 the appropriate advice is dispensed. If not, the next statement is evaluated. If
none of the conditions associated with the else if statements are found to be true, then the
unfortunate else statement at the end of the program runs.
Keep in mind that else if statements are only run if all of the previous conditions are found
to be false. Note also the indentation used throughout the else/else if/else is consistent.
This is for housekeeping purposes. Readability is a important part of programming.
While Loops
Loops allow you to run a block of code a number of times. Each time that block of code is
executed is known as an iteration. Loops are critical to many different types of programs.
Imagine a card game where turns are taken and cards are dealtall with loops. If you
think about it, you can probably identify loops in many different types of software that
you use every day. The process of waiting for the user to input something, processing that
input and then waiting for the user again is often coded in a loop structure.
Lets code a simple loop:
public class Loop{
public static void main (String[] args) {
int tracker = 0;
while(tracker<100){
System.out.println(tracker);
tracker += 5; }
}
}
Run the program with the Java command and the result should appear something like what
you see in figure 4.4:
band = bandName.nextLine();
if(!band.equals(XXX)){
System.out.println( band + ROCKS!); }
}
} Note: Due to strings being a reference type, you have to use the .equals() method to
check for equality. This method returns true if the strings are equal and false if not.
Run the program with the Java command and you should see a result similar to figure 4.5:
System.out.println(x);
X*=300000; }
}
Youll note that the continuation condition will always be true in this examplethe value
of x will always be greater than zero. The value of x very rapidly gets out of hand and, in
fact, becomes too big to store in memory. I ran this in the Koding.com environment. It
took me about 10 minutes to stop the execution of the program as kodings environment
was lagging due to the program.
Figure 4.6: At this point the environment was frozen due to an endless loop. Every so
often it would print Infinity a couple hundred times and then freeze right back up.
You can try this example on your own. Im not responsible for any damage done.
(Damage wont be permanenthave fun!)
For loops
So weve determined that forgetting to put a proper iterator in your while loop can be bad
for your program. How can we avoid having an endless while loop? The answer is a for
loop. For loops do the same thing as while loops, however they will only execute a set
number of times because you are forced to place an iterator and variable as part of the
loops syntax in addition to a conditional. As a result its extremely difficult to create a for
loop that executes endlessly.
Heres an example of a very simple for loop. It does the same thing as our first loop: Prints
0 to 100, while counting by fives.
This loop is in a file called Loop3:
public class Loop3{
public static void main (String[] args) {
for(int x = 0; x<100; x+=5){ System.out.println(x); }
}
}
The syntax of the loop is simple. First we have a local variable x that is initialized and
declared. Local variables cannot be accessed or changed outside of the loop. Then, we
have a conditional. The conditional fulfills the same purpose as in the while loop. When it
is no longer true the loop will stop iterating. Finally we have whats known as an iterator.
This is a reassignment of the variable you initially declared for this loop. The iterator is
the reason that its generally hard to accidently make an endless loop. Note that these three
statements are separated by semicolons as though they were the end of lines. Heres the
result of executing this code:
Figure 4.7: The result of the for loop is the same as the result of our original while loop.
Unlike variables which store a single unit of data, weve stored multiple elements in our
array. Im sure you can imagine a number of situations where this could be convenient. In
this case, all of the members or elements of our array are strings. This is because we
declared our array as a String array. String is the data type of the arrays members.
Here is another array to add to your code. This time its comprised of double values:
double [] gpas = {
3.25, 2.26, 1.99, 3.55, 4.0, 3.21, 2.56, 3.06 ,
2.72
};
Now, heres where arrays become a bit more interesting. Arrays have a number of built-in
methods that you can use to manipulate them; There are included functions that do things
like count the members of the list or sort them. You could write your own code to do all
this, but it would be a lot of work.
Before we start with the really fancy stuff, lets take a look at how we extract data from
the Array. Go ahead and copy the code below. Youre free to skip over the comments if
you like. Remember to keep the file name and the class name consistent!
public class Arrays{
public static void main (String[] args) {
String[] groceries = {
oranges,apples,milk,bread,butt er,pepper,salt,sugar,pears
};
double[] gpas = {
3.25, 2.26, 1.99, 3.55, 4.0, 3.21, 2.56, 3.06 , 2.72
};
Once youre sure that the code is typed correctly in your text editor, execute the code with
the Javacommand. Dont forget to compile! Your output should look like this:
Figure 5.1: Java Arrays program output using the Koding.com environment
Pay special attention to the print statements. Youll note that each print statement
references one of our arrays and a specific index within that list surrounded by brackets.
Lists in Java, like most languages, are indexed, meaning that each member of the list is
assigned a number used to reference it. The first member of a list is always index zero.
Our grocery list would have the following indexes:
Index Member
0 oranges 1 apples
2 milk
3 bread
4 butter
5 pepper
6 salt
7 sugar
8 pears
When combined with print method, the general form of retrieving data from an array is:
ArrayName[#];
Where # is the index you are pointing to.
One thing to keep in mind is that your array is only as long as you initially make it. If you
try to access a non-existent array index, your program is going to exit with an error. Lets
add one line to our current program:
System.out.println(gpas[9001]);
When you run the program you should see an output similar to the following:
Weve manipulated and stored a lot of data so far. We have not, however, organized much
data.
Arrays are a powerful organizational tool. One reason is because of the sort() method. It
does exactly what it sounds likeit sorts the members of the array. The sort method is
called a bit differently from normal methods though. Sort() is called as a static member of
the array class like this:
Arrays.sort(<Array>);
Make a new file and copy this code. My file is called ArraySortDemo.java:
import java.util.Arrays;
public class ArraySortDemo{
public static void main (String[] args) {
String[] groceries = {
oranges,apples,milk,bread,butter,pepper, salt,sugar,pears
};
System.out.println(___UNSORTED ARRAY___);
for(String a:groceries){
System .out.print(a + );
}
System.out.println();
System.out.println(___SORTED ARRAY___);
Arrays.sort(groceries);
for(String a:groceries){ System.out.print(a + ); }
System.out.println();
}
}
Note: Dont worry if you dont understand the for loops. Theyre used to print our array.
Well cover them in the next section.
Run your program with the Java command. Your output should look something like this:
Figure 5.3: After the sort() function runs, the groceries list is reindexed. Its now in
alphabetical order!
The sort method will also order numbers from smallest to largest, and organize other
primitive data.
Printing Arrays
So far the only way weve bee n printing information from arrays is through referencing
an individual array element. But what if we need to print out a whole array?
Copy this file below:
public class PrintingArrays{
public static void main (String[] args) {
int[] oneToTen = { 1,2,3,4,5,6,7,8,9,10
};
System.out.println(oneToTen);
}
}
Executing the code above results in non-readable text:
Figure 5.4:
Passing the variable name printed an internal reference used by the Java compiler. Odd.
Instead, we have to use a loop. There are several ways to do this; Im going to show you
the two easiest and most frequently used.
With a for loop
The first method uses a simple for loop to print out the array. Replace the print method
with these few of code in PrintingArrays:
for(int x = 0; x<oneToTen.length; x++){ System.out.println(oneToTen[x]); }
Now if you run your program youll see that the contents of your array have been printed:
to the square brackets containing the dynamic variable x rather than a static number the
index that we are calling, which was originally index zero, switches to index one.
The number of iterations is set using the .length property which returns the total number
of elements in our array.
With a for-each loop
The second method of printing is through the use of a modified for loop called a for-each
loop. The syntax for this loop is simpler than that of the regular for loop.
Add the following code to the end of your PrintingArrays program:
System.out.println(_______With a for each loop______);
for(int print:oneToTen){ System.out.println(print); }
The first line in this snippet of code prints a separator, so we know which loop is
generating the output.
Next is the foreach loop. The statement within the for loops parentheses is shorter,
consisting of two components rather than three. This statement also fails to conform to
what weve learned about traditional for loops, as it lacks an iterator and conditional. This
different statement is what makes this a for-each loop rather than a regular for loop.
Whatever code is put inside the loop will be performed for each member of the array.
In this case were printing the array.
The statement within the parentheses of the loop consists of a variable declaration, whose
type must match the type of the array you intended to call the loop on and the name of the
array you intend to use the loop on.
If you, for example, wanted to print our grocery list array, the for-each loop would look
like this:
for(String item: groceries){
System.out.println(item); }
bigger programs this means they can cause it to run slower than if we just used arrays.
ArrayLists, just like Scanners, are reference or class type objects. Their declaration looks
like this:
ArrayList name = new ArrayList();
It should be noted that ArrayLists cannot be filled upon initialization like arrays. The only
way to fill them is through the .add() method. You should also be aware that unless you
put an integer in the parenthesis of the ArrayLists constructor it will be made with a
default size of ten slots.
If your ArrayList is full the .add() method will simply add a new member and append
what you placed in the parenthesis to the end of the list.
Now lets try an example. I put mine in a file called ArrayLists:
public class ArrayLists{
public static void main (String[] args) {
ArrayList languages = new ArrayList(3); languages.add(Spanish);
languages.add(French);
languages.add(English);
System.out.println(languages.size());
languages.add(German);
System.out.println(languages.size()); }
}
The first line in the main method declares a new ArrayList that we named languages and
gave it a size of three.
Talk the Talk: There are several ways to say you used a method. The most common terms
are call or invoke. When I programmer says I invokedthe method he or she is really
saying they used the method.
The next three lines of code invoke the add method to fill up the ArrayList. Then the size
method is called to see how large the ArrayList is. After that one more element is
appended to the end of the ArrayList, increasing the size from the original three slots to
four.
When you run the code, your output should appear something like this:
Figure 5.6:
We can see how the size of our ArrayList increased when we added an element to the end.
Java printed two notes in addition to the output of the program. This occured because we
are using an unparameterized ArrayList. An unperamiterized ArrayList is an ArrayList
thats type hasnt been specified. As a result variables of different types can be stored
within the same ArrayList and cause exceptions due to type mismatches.
To alleviate this issue, we have to type our list to take one specific object like arrays do.
Rather than a standard declaration and instantiation, we add a slight modification to each
part so it looks like this:
ArrayList<DataType> name = new ArrayList<DataType>();
Talk the Talk: An unparamaterized ArrayList accepts whats known as a generic type. A
generic type is a type that can be specified later by the programmer in order to improve
functionality. The type can be anything, including custom classes that you implement and
design yourself.
Lets modify the code in our ArrayLists.java file to follow this practice:
public class ArrayLists{
public static void main (String[] args) {
ArrayList <String> languages = new ArrayList<String>(3);
languages.add(Spanish);
languages.add(French);
languages.add(English);
System.out.println(languages.size());
languages.add(German);
System.out.println(languages.size()); }
}
Now when we recompile and run our code, theres no problem!
Figure 5.7: Much better. Typing our ArrayList got rid of that pesky warning.
Now the final thing to know about ArrayLists is how to obtain data from them. Unlike
arrays, we dont reference by indexes. Instead, we use a method to retrieve the data: The
.get(#) method. The number in the parentheses is the index value of the element you want
to access. Just like Arrays, ArrayLists are zero-based.
Add the following line to your code, recompile and run to see it in action:
System.out.println(languages.get(0));
When you recompile and run, the output should look something like this:
Figure 5.8:
We got then printed the first element of our ArrayList.
There are a number of other methods for ArrayLists that are rather useful. The most
notable being the .set() method, which replaces values much like reassigning with arrays.
The official documentation is located here:
http://docs.oracle.com/Javase/7/docs/api/Java/util/ArrayList.html
Immutables
Immutables are very similar to ArrayLists with one important exception: Immutables are
non-dynamic. This means once an Immutable is defined the values within it cannot be
changed. Lets start a new program where we will define an Immutable.
Copy this code into a file named ImmutablesDemo.java: import java.util.*;
public class ImmutablesDemo{
public static void main (String[] args) {
//Note: Arrays cannot be made immutable. So instead, we use Lists.
String [] turn = {600, 800, 1024, 1280, 1366, 1920};
List<String> list = Java.util.Arrays.asList(turn);
List<String> unmodList =
Collections.unmodifiableList(list);
for(String p: unmodList){
System .out.println(p);
}
System.out.println();
System.out.print(unmodList.get(0));
unmodList.add(464); }
}
Compile the code then run it using the Java command and carefully examine the output.
Figure 5.9: Note that were able to access the complete immutable, a single index within
the immutable, but when reassigning a value within an immutable, an error is generated.
An immutable is non-dynamic and once initiated, the values within it cannot be changed.
Immutable are for storing data that does not change over the life of a program. For
example, in the program above, the screen widths are unlikely to change.
HashTables
HashTables are yet another data structure. They are perfect for storing paired data,
sometimes known as key: value data. In this type of data, instead of a numerical index,
each data point is indexed by a key which is determined by the programmer. State names
and state capitals or towns and zip codes are both examples of where HashTables can be
useful for storing data.
Seasoned programmers may find HashTables to be very similar to Dictionaries. This is
because HashTables were derived from them. (Dictionaries are the parent class of
Hashtables)
Consider the following program:
import java.util.*;
public class HashTabs{
public static void main (String[] args) {
Hashtable <String,String> statesAndCapitols = new Hashtable<String,String>();
statesAndCapitols .put(Connecticut,Hartford); statesAndCapitols.put(New
York,Albany); statesAndCapitols.put(Mississippi,Jackson);
statesAndCapitols.put(Maine,Augusta); statesAndCapitols.put(Montana,Helena);
statesAndCapitols.put(Texas,Austin);
String ConnCap = statesAndCapitols.get(Connecticut);
System.out.println(ConnCap);
} }
When you run the program with the Java command youll see the output Hartford. This
is the result of the key (or index) for Hartford being Connecticut. Note the print
Figure 5.10: Output demonstrating two of the functions used with dictionariesvalues()
and keySet()
Youll note that the values() function returns all of the values in the dictionary, while the
keySet() function returns all of the keys. This short chapter can only give you a broad
introduction to working with data in programming. Almost every program, to some
degree, works with data. Being effective at working with data is an important part of any
programmers toolbox.
Figure 6.1: Creating the class (left) and driver class(right) in Koding
Examine the following line:
numOfAnimals++;
This line is designed to increment the value of numOfAnimals, the internal housekeeping
variable that keeps track of how many instances of Animal that we generate. The actual
instance is generated with the code in the driver class which can be seen here in a file
called AnimalDriver.java:
public class AnimalDriver{
public static void main (String[] args) {
Animal myDog = new Animal(19, 12, brown, true);
}
}
Adding Some Methods
Lets change up and add to our initial code:
public class Animal{
private static int numberOfAnimals = 0; public int length;
public String color;
public double weight; public boolean hasFur; public boolean isHungry;
public Animal(int Length, double Weight, String Color, boolean Fur, boolean Hungry){
color = Color;
weight = Weight;
hasFur = Fur;
Running the new code should result in output similar to the following:
Figure 6.3: Two instances of Animal objects are createdSparky and Rover.
Extending Classes
The object oriented structure does more than allow us to simply represent objects as code
in one file. It allows us to build an entire hierarchy of objects to represent our real life
problem space. Lets take another look at Vehicles.
In the world we have numerous types of vehicles. Some work on the ground, some work
in the water and others in the air. To properly represent a vehicle in an object oriented
manner, we need to determine what they all have in common. All vehicles have a top
speed, a weight and a color. All vehicles are either moving, or still.
As a result we can create a new object that contains all of these common attributes, so we
dont have to code them each time we want to create a variant of a vehicle.
Copy the following code, and save it as Vehicle.java:
public class Vehicle{
int topSpeed;
String color;
double weight; boolean isMoving;
public Vehicle(int setSpeed, String setColor, double setWeight, boolean tellIfMoving){
topSpeed = setSpeed; color = setColor;
weight = setWeight;
isMoving = tellIfMoving;
}
public boolean startMoving(){
isMoving = true;
return Vehicle is moving.; }
public boolean stopMoving(){
isMoving = false;
return Vehicle isnt moving.; }
}
The code above summarizes the basic attribute of vehicles. But if we need to represent a
car, there is information we need that wouldnt be relevant if we were representing a boat.
But we would still need all of the attributes described in the Vehicle class. Does this mean
we copy all of this code into two different files in just to represent these types of vehicles?
We could, but that would be inefficient. Instead we extend the vehicle class.
By extending the vehicle class, we create what is known as a child class. The child class
inherits the fields, methods and even the constructor of the parent (Vehicle in our case)
class.
Open up a new file in your text editor, and save the following code as
GroundVehicle.java:
public class GroundVehicle extends Vehicle{
int numWheels; String vehicleType;
public GroundVehicle(int setSpeed, String setColor, double setWeight, boolean
tellIfMoving, int setNumWheels,String type){
super (setSpeed, setColor, setWeight, tellIfMoving); numWheels = setNumWheels;
vehicleType = type;
}
public String startMoving(){
isMoving = true;
return vehicleType + is driving;
}
public String stopMoving(){
isMoving = false;
return vehicleType + isnt driving; }
public String whatColor(){
return color;
}
}
The first line of this code is slightly different from what youre used to from this chapter.
There is the addition of the extends keyword followed by Vehicle. This notifies Java that
GroundVehicle is a child of Vehicle. In other words GroundVehicle is derived from
Vehicle.
In Java, all classes, regardless of if they contain the extends keyword, are an extension of
the Object class. As a result at the top of every hierarchal tree sits the Object class.
Our tree appears as follows:
GroundVehicle is a Vehicle which is an Object.
Talk the Talk: In object oriented programming when a programmer references the parent
of a child they say the child class shares an is a/an relationship with the parent class.
The next lines of the code add two new fields to our object. numWheels contains the
number of wheels our GroundVehicle object has. The vehicleType variable allows us to
pass in a string like car, motorcycle or truck. Both of these new variables exist in
addition to all of the variables in the Vehicle class. Vehicles variables can be accessed
through the super keyword. Since GroundVehicle is a subclass of Vehicle,
GroundVehicle has inherited Vehicles attributes and functionality.
The super keyword allows you to reference fields, constructors and methods of the direct
parent (class after the extends keyword) class.
We already referenced the constructor by using the super keyword in the constructor of
our GroundVehicle class. We treated the super keyword like the instantiation statement of
Vehicle.
The normal instantiation would look like this:
new Vehicle(100,Orange,1034.2, false);
new Vehicle has been replaced by super within the constructor and as a result all of
the hidden fields within GroundVehicle will be populated upon construction due to us
invoking the parent classs constructor.
After the constructor we have three methods. They change one variable within the vehicle
class and then return a string that confirms their change. Read the name of the first two
methods in GroundVehicle and then the first two methods in Vehicle. When methods in a
child class share the same name as methods in their superclass, they override the
superclass method. We are changing the functionality of the method and nothing more. If
we changed anything more, such as the return type, we would be overloading the method.
Remember, we need a driver class in order to use our objects.
Copy the following code into a file named VehicleDriver.java:
public class VehicleDriver{
public static void main(String[] args){
Vehicle transportationMachine = new Vehicle(50,Blue,210,false);
System.out.println(transportationMachine.startMoving());
}
} The resulting output of this code is:
Figure 6.4: The output is the string we typed in the Vehicle Driver class, as that is what we
put after the return statement.
Lets add some additional code to our VehicleDriver to get a better idea of whats going
on. Add this code into your Vehicle Driver class:
GroundVehicle horseAndBuggy = new GroundVehicle(5, Black, 300, false, 4,Horse
and Buggy);
String result = horseAndBuggy.startMoving();
System.out.println(result);
Once we recompile and run the output looks something like this:
Figure 6.5: The more specific method in our GroundVehicle class resulted in a more
specific output.
The first line of this code snippet is the instantiation for the GroundVehicle object which
we use to make a horse and buggy. The next line makes a string, and sets it to the output
of the startMoving method. The final line prints result.
Finally lets look at one more thing that class extensions are capable of.
Copy these last few lines into the driver class:
Vehicle goKart = new GroundVehicle(25,Yellow, 3, true, 4, GoKart );
System.out.println(goKart.startMoving());
Look at the declaration and instantiation of the object. They do not match. However when
we compile and run this code, there are no issues due to the fact that GroundVehicle is a
type of Vehicle. Since the GroundVehicle class is derived from the Vehicle class, a Vehicle
type variable can be used to hold a GroundVehicle type object, like weve done in our
code.
However a GroundVehicle type variable cannot be used to hold a Vehicle type object! A
GroundVehicle is a Vehicle, but a Vehicle is not necessarily a GroundVehicle.
GroundVehicle has parameters that not all Vehicles have, an example being number of
wheels.
This is true in all programming trees. The less vague objects can be contained within more
vague variables. Vaguer objects however cannot be contained within a more specific
variable.
This also means that you can place a GroundVehicle, or a Vehicle within an Object type
variable, as all reference type objects are derived from the Object class. (Everything is an
object.)
At this point you may be wondering what happens when you call the startMoving
method on the next line. Will it use the more specific method within the GroundVehicle
class or the vague method within the Vehicle class?
Well if you compile and run the code, the result looks like this: