How To Program With Java Ebook
How To Program With Java Ebook
net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
Contents
Legal Junk.................................................................................................................................................... 9
Links ...................................................................................................................................................... 10
Audio..................................................................................................................................................... 10
Video ..................................................................................................................................................... 10
Chapter 1 .................................................................................................................................................. 11
Variables ............................................................................................................................................... 12
Control Structures ................................................................................................................................. 15
Data Structures ..................................................................................................................................... 18
Syntax ................................................................................................................................................... 21
Tools ..................................................................................................................................................... 24
Chapter 2 .................................................................................................................................................. 28
The Java Hello World Program .............................................................................................................. 29
Java Hello World (part II) ...................................................................................................................... 35
Chapter 3 .................................................................................................................................................. 38
What is a Method?................................................................................................................................ 39
Object Oriented Programming in Java .................................................................................................. 42
Java Arrays ............................................................................................................................................ 45
What are Java Arrays?....................................................................................................................... 48
Primitive Data Types ............................................................................................................................. 51
What do primitive data types look like in Java? ................................................................................ 51
Strings ................................................................................................................................................... 54
String Object or Primitive? ............................................................................................................. 54
String Concatenation ........................................................................................................................ 55
Packages ............................................................................................................................................... 57
What is a Java Package? .................................................................................................................... 57
Why are Java Packages Useful?......................................................................................................... 57
What do Packages look like in Code? ................................................................................................ 57
What do Java packages look like in code?......................................................................................... 58
Imports ................................................................................................................................................. 60
What are Java Imports? .................................................................................................................... 60
What do Java imports look like in Code? .......................................................................................... 60
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
Legal Junk
Copyright 2013 by Ecosim Software Inc.
All rights reserved. No part of the contents of this eBook may be reproduced or transmitted in any form or
by any means without the written permission of the publisher.
This book expresses the authors views and opinions. The information contained in this book is provided
without any express, statutory, or implied warranties. Neither the author, EcoSim Software Inc., nor its
resellers or distributors will be held liable for any damages caused or alleged to be caused either directly
or indirectly by this book.
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
Audio
Throughout this eBook, there are audio guides that accompany certain lessons and
can be used as an addition to the written content. These audio segments are pulled
from the How to Program with Java podcast, and if you really enjoy listening, you
can feel free to subscribe to the podcast here.
Video
As an added bonus, there are now links to video segments provided in this eBook. The
links will take you to a YouTube video that can be used as a valuable learning tool.
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
10
Chapter 1
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
11
Variables
I want this content to provide anyone walking in off the street the knowledge to
be able to write their first program with the Java programming language with as
little pain as possible.
So, lets get started with our first topic: The 5 basic concepts of any programming language. You might
say, Why are we talking about any programming language? I thought this was about Java. Well, Ive
found that its important to remember that a lot of programming languages are very similar and
knowing whats common between all programming languages will help you transition into any other
programming language if you need to! For example, with the Java programming knowledge I had
obtained, it took me less than a month to learn how to program in a language called Objective C (which
is used for iPhone apps). Thats powerful stuff!
So, here are the 5 basic concepts of any programming language:
1.
2.
3.
4.
5.
Variables
Control Structures
Data Structures
Syntax
Tools
I recognize that these words probably look foreign to you, but dont worry; Ill do my very best at taking
the mystery out of them. Now, theres a lot to say about each of these 5 concepts, so Ill only talk about
item #1, variables!
What is a variable?
Variables are the backbone of any program, and thus the backbone of any programming language. Wiki
defines a variable as follows:
In computer programming, a variable is a storage location and an
associated symbolic name which contains some known or unknown quantity or
information, a value.
Okay, well, thats kind of cryptic. To me, a variable is simply a way to store some sort of information for
later use, and we can retrieve this information by referring to a word that will describe this
information. For example, lets say you come to my website www.howtoprogramwithjava.com and the
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
12
first thing I want to do is ask you what your name is, so I can greet you in a nice way the next time you
visit my website. I would put a little text box on the screen that asks you what your name is that text
box would represent a variable! Lets say I called that text box your Name. That would be
the symbolic name (or word) for your variable (as described from our wiki definition above). So now,
when you type your name into the text box, that information will be stored in a variable called your
Name. I would then be able to come back and say What value does the variable your Name
contain? The program will tell me whatever it was you typed into that text box.
This concept is extremely powerful in programming and is used constantly. It is what makes Facebook
and Twitter work, its what makes paying your bills via your online bank work, and its what allows you
to place a bid on eBay. Variables make the programming world go around.
Now, if we want to get more specific, when it comes to the Java programming language, variables have
different types. Brace yourself here, for Im going to try to confuse you by explaining an important concept in three sentences. If I
were to be storing your name in a variable, that type would be a String. Or, lets say I also wanted to
store your age; then that type would be stored as an Integer. Or, lets say I wanted to store how much
money you make in a year; then that type would be stored as a Double.
What the heck are String, Integer and Double?
Excellent question! In Java, the programming language wants to know what kind of information you are
going to be storing in a variable. This is because Java is a strongly typed language. I could teach you
about what the difference is between a strongly typed language and a weakly typed language, but that
will likely bore you right now, so lets just focus on what a type is in Java and why its important.
Typing in Java allows the programming language to know with absolute certainty that the information
being stored in a variable will be a certain way. So like I said, if youre storing your age, you would use
the Integer type and thats because in Java an Integer means you have a number that wont have any
decimal places in it. It will be a whole number like 5, 20, 60, -60, 4000 or -16000. All of those numbers
would be considered an Integer in Java. What would happen if you tried to store something that wasnt
an Integer into an Integer variable like the value $35.38? Well, quite simply, you would get an error in
the program and you would have to fix it! $35.38 has a dollar sign ($) in it as well as a decimal place
with two digits of accuracy. In Java, when you specify that a variable is a type Integer, you are simply
not allowed to store anything except a whole number.
Now, I dont want to go into too much detail about Types, for this is better suited to programming basic
concept #3 Data Structures. Thats all I will touch on for now, but it will all make sense in time so dont
worry!
In summation, we talked about what a variable is and how you can store information in a variable and
then retrieve that information at some later point in time. The variable can have a name and this name
you give to the variable is usually named after the kind of content youll be storing in the variable, so if
Im storing your name in the variable, youd name the variable your Name. You wouldnt HAVE to give
it that name. You could name the variable Holy Crap Im Programming, but that wouldnt make a
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
13
whole lot of sense considering you are trying to store a persons name. Makes sense right? Finally,
variables have types and these types are used to help us organize what can and cannot be stored in the
variable. Hint: having a type will help to open up what kind of things we can do with the information
inside the variable. Example: if you have two Integers (lets say 50 and 32), you would be able to
subtract one variable from the other (i.e. 50 32 = 18). This is pretty straight forward right? But, if you
had two variables that stored names (i.e. Trevor and Geoff), it wouldnt make sense to subtract one
from the other (i.e. Trevor Geoff) because that just doesnt mean anything! Types are also a
powerful thing, and they help us to make sense of what we CAN do with our variables and what we
CANNOT do!
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
14
Control Structures
These are the 5 basic concepts of any programming language. Heres a breakdown
again of those concepts:
1.
Variables
2.
3.
Control Structures
Data Structures
4.
5.
Syntax
Tools
Weve already discussed what a variable is, so now lets talk about control structures. What on earth is
a control structure!? Wiki describes it as follows:
A control structure is a block of programming that analyzes variables and chooses
a direction in which to go based on given parameters. The term flow
control details the direction the program takes (which way program control
flows). Hence it is the basic decision-making process in computing; flow control
determines how a computer will respond when given certain conditions and
parameters.
That definition is obviously a bunch of technical terms that no beginner to programming would
understand, so let me try to describe it in laymen terms. When a program is running, the code is being
read by the computer line by line (from top to bottom, and for the most part left to right) just like you
would read a book. This is known as the code flow. As the code is being read from top to bottom, it
may hit a point where it needs to make a decision. This decision could make the code jump to a
completely different part of the program, or it could make it re-run a certain piece again or just plain
skip a bunch of codes.
Think of this process like if you were to read or choose your own adventure book. For example, you get
to page 4 of the book and it says if you want to do X, turn to page 14, and if you want to do Y, turn to
page 5. That decision that must be made by the reader is the same decision the computer program
must make; however, only the computer program has a strict set of rules to decide which direction to
go (whereas if you were reading a book, it would be a subjective choice based on whomever is reading
the book). This decision that must be made will in turn affect the flow of code, which is known as
a control structure!
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
15
Okay, that doesnt seem to be such a hard concept. A control structure is just a decision that the
computer makes. However, what is it using to base that decision on? Well, its simply basing its
decision on the variables that you give it! Let me show you a simple example, heres a piece of Java
code:
if (yourAge < 20 && yourAge > 12)
{
// you are a teenager
}
else
{
// you are NOT a teenager
}
You can see above that we have a variable and its name is yourAge, and we are comparing yourAge to
20 and 12. If youre less than 20 AND youre more than 12, then you must be a teenager (because you
are between 13 and 19 years of age). What will happen inside of this control structure, is that if the
value assigned to yourAge variable is between 13 and 19, then the code will do whatever is inside of the
first segment (between those first two curly braces { } ), and it will skip whatever is inside of the second
code segment (the second set of curly braces { } ). And if you are NOT a teenager, then it will skip the
first segment of code and it will execute whatever is inside of the second segment of code.
Lets not worry too much about what the code looks like for the moment, as Ill touch on how to write
the code out properly in section #4 syntax. The only concept you need to try and wrap your head
around right now is that there is a way in programming to choose which lines of code to execute and
which lines of code to skip. This will all depend on the state of the variables inside of your control
structure. When I say state of a variable, I just mean what value that variable has at any given moment,
so if yourAge = 15, then the state of that variable is currently 15 (therefore, youre a teenager).
Youve now seen one control structure and Ive tried to explain it as best I could. This control structure
is known as an if...else structure. This is a very common control structure in programming; let me hit
you with some other examples. Heres a while loop control structure:
This while loop control structure is also very handy, and its purpose is to execute code between those
curly braces { } over and over and over until the condition becomes false. Okay, so whats
the condition? Well, the condition is between the round brackets ( ), and in this example it
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
16
checks yourAge to see if you are less than 18. So if you are less than 18, it will continuously execute the
code inside the curly braces { }. Now, if you were 18 or older before the while loop control structure is
reached by the code flow, then it wont execute ANY of the code inside of the curly braces { }. It will just
skip that code and continue on executing code below the while loop control structure.
There are a few other examples of control structures in Java, but I dont want to overwhelm you with
them right now
Weve learned that code flows from top to bottom and for the most part left to right, just like a book.
Weve learned that we can skip over certain codes or execute certain parts of a code over and over
again, and this is all achieved by using different control structures. These control structures
are immensely important to programming, for they make the programs function properly. For
example, you wouldnt want people to be able to login to your Facebook account if they enter the
wrong password right? Well, thats why we use the if...else control structure. If the passwords
match, then you will be logged in or else a password is incorrect screen will be shown. So, without
control structures, your programs code will only flow in one way, and it would essentially only do one
thing over and over again, which wouldnt be very helpful. Changing what the code does is based on a
variable is what makes programs useful to us all!
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
17
Data Structures
1.
2.
3.
4.
5.
Variables
Control Structures
Data Structures
Syntax
Tools
Data structures, what are they, why are they useful? Well, lets turn to a quick definition from wiki:
In computer science, a data structure is a particular way of storing and
organizing data in a computer so that it can be used efficiently.
Okay, that definition is a little more down to earth. But, there is a lot of meat behind data structures.
Let me try to explain the point of data structures by giving you an example Lets use a list of contacts
as the example! You probably have a list of contacts somewhere in your life, whether its in one of your
email programs or an address book in a kitchen drawer. There are a bunch of contacts, and that list of
contacts could grow (or shrink) at any given moment. If you were to try and represent all those contacts
as variables in a computer program, how would you do it? Well, theres a right way and a wrong way.
For the purposes of our example, lets say we need to keep track of 10 contacts.
First, the WRONG WAY:
If we need to store 10 contacts, we would probably define 10 variables, right?
String contact1, contact2, contact3, contact4, contact5, contact6, contact7, contact8,
contact9, contact10;
contact1 = "John Smith ([email protected])";
contact2 = "Jane Smith ([email protected])";
contact3 = //... etc.
In the world of programming, this is just a terrible way of trying to store 10 different variables. This is
because of two main reasons:
1. The sheer amount of text that youll need to write in your program
Sure, right now we only have 10 contacts, so its not too bad, but what if we had 1,000
contacts! Imagine typing that out a thousand times! Forget about it!
2. The flexibility of code
If we need to add another contact, we wouldnt be able to do it without manually
editing our code. We would have to go into our code, physically write out contact11,
and then try to store whatever information is needed into the new variable. This is just
crazy talk!
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
18
Again, lets not worry about all those symbols and confusing brackets and semi-colon because well
cover that later. All I need you to understand right now is that there is a way to store a bunch of
contacts into something called a data structure (in the case of our example, a List). Okay, so, whats so
great about a List? Well, for one thing, you can add and remove things from a list with ease. If you
started with 10 contacts, its a piece of cake to add another contact to the list. How you ask? Just like
this:
Voila! Weve added another contact to our contacts list! So, you may be saying, The right way looks
like just as much typing as the wrong way. Youve got a point, but the main difference is that with the
first approach, you had to create 10 unique variables (i.e. contact1, contact2, contact3,
contact4), but with the second approach, we only created 1 variable ( contacts), for we only had to
create 1 variable, and because we can say contacts.Add(someRandomContact) means that our code is
much more flexible and dynamic. When I say dynamic, I mean that the outcomes of the program can
change depending on what variables you give to it. Thats really the key to using data structures! We
want our code to be as dynamic as possible; we want it to be able to handle a bunch of situations
without having to write more and more code as the days go by.
In essence, a data structure is just a way to get around having to create tons of variables. Now, there
are a bunch of other data structures in Java, but Ill just quickly touch on the ones we use most often
when programming. The next one Ill talk about is the HashMap. This doesnt sound as straightforward
as our last data structure (the List), but its really just a fancy name for a fairly simple concept. So, what
is a hash map? Heres a visual representation:
Honda -> Civic, Prelude
Toyota -> Corolla, Celica, Rav4
Ford -> Focus, Mustang
Audi -> R8
What you see here is the make of a car on the left, which points to different models of that make. This
is known in the programming world as a Key/Value pair. The key in this case is the Make of the car (i.e.
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
19
Toyota, Honda, Ford, and Audi) and the value in the case is the model (i.e. Civic, Corolla, Focus, and R8).
That is how a HashMap works, and its just another data structure! This concept is use all over the place
on the web. For example, if you have ever filled out a quote for automobile insurance online, youve
probably had to choose the make and model of your car. I bet you that information was presented on
screen by using a HashMap (just like I showed you above)! When you select Toyota from one drop
down list, the second drop down list will need to change its contents to only show models of cars made
by Toyota. If you change the first drop down to Honda, the second drop down list will change again to
show cars made by Honda.
How about I show you what a HashMap looks like in Java code?
Wow, theres a lot of stuff going on in there, but dont be intimidated because all you need to
understand right now is the concept that this HashMap data structure stores key/value pairs. In our
case, a make is the key and a List of models is our value. Now, thats kind of interesting. Did you see
what we did there? I just said that we have a HashMap data structure and we are storing a List inside
the HashMap (which is another data structure). This is done on a fairly regular basis in the programming
world. We can use one data structure inside of another! So, if the point of data structures is to help us
minimize the number of variables we need to create, then we are really saving ourselves the hassle of
creating a lot of variables!
Okay, so lets sum up everything weve talked about. A data structure is a way
of storing and organizing data in such a way that it can be used efficiently. The point is to avoid
creating crap loads of variables people! Java allows us to do this by using Lists and HashMaps (as well
as many other data structures, but these two are the most common). These two data structures can
grow and shrink without you having to worry about coding all of that behind the scenes stuff. When
you add to a List, the new element is there and is usable (like magic). When you remove from the List,
the element is now gone (poof!). This saves us from creating and deleting variables in our code
manually.
Alright, that about sums up what I need you to know for our next section: syntax. In my opinion as
a veteran programmer, syntax is the one thing that will discourage you from learning to program. It
takes practice and patience to understand, but I promise you, it will become second nature in time. So
please be patient and be excited to learn about syntax in Java because once you get the hang of it, youll
be on your way to programming like a champ!
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
20
Syntax
Welcome back to our fourth lesson in our five part series on the 5 basic concepts
of any programming language.
1.
2.
3.
4.
5.
Variables
Control Structures
Data Structures
Syntax
Tools
What is syntax? As always, lets hop over to wiki for a quick definition:
In computer science, the syntax of a programming language is the set of rules that define the
combinations of symbols that are considered to be correctly structured programs in that language.
Alright, so I would say thats almost English, but what do they mean by combinations of symbols that
are correctly structured? Well, I would choose a different word than symbols. I would define syntax to
be a particular layout of words and symbols. An example of this in the case of Java would be round
brackets (), curly brackets {}, and variables, among other things. Think of it like this: when you look at
an email address ([email protected]), you can immediately identify the fact that its
an email address right? So why is that? Why does your brain make the connection that its an email
address and not a website address? Well, its because an email address has a particular syntax. You
need some combination of letters and numbers, potentially with underscores (_) or periods (.) in
between followed by an at (@) symbol and by a website domain (company.com). That is a defined
combination of letters and symbols that are considered correct structure in the language of the
internet and email addresses.
So, syntax in a programming language is much the same, for there are a set of rules that are in place,
which when you follow them, allows your programming language to understand you and allow you to
create some piece of functioning software. However, if you dont abide by the rules of a programming
languages syntax, youll get errors
How about an example of syntax in Java? Well youve seen it already back when we talked about
variables and control structures. To define a variable in Java, you need to do this:
There are four parts to the syntax of creating a variable in Java. The first is the word String. This is the
variables type. Remember when we talked about variable types in the first part of this series? I
mentioned String, Integer and Double. These are three different variable types that allow you to
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
21
store three different kinds of data. A String in this case, allows you to store regular letters and special
characters.
The second part to this variable creation syntax is the variable name, and in this case I arbitrarily
chose helloVariable. I could have just as easily chosen holyCowThisIsAVariableName. Variable
names can be made up of letters and numbers, but the only special characters they can contain are
underscores (_). They also usually start with a lower case letter, but they dont have to. Thats just kind
of an accepted and suggested convention (at least in the Java world). The third part of the syntax for
creating a variable is the value that the variable will hold. In this case, we have a String variable, so we
have the value "Hello Everyone!
In java, Strings are defined by wrapping regular letters/numbers/special characters in quotes ( ).
Again, thats just the syntax that Java uses. The last part of this syntax is the part that marks this
particular code segment as being complete. In Java, we use the semi-colon (;) to mark a part of our
code as complete. You will see that almost every line of code in Java will end with a semi-colon (;).
There are certain exceptions to this; for example, control structures arent marked with semi-colons but
they use curly braces to make their beginning and end. Think of it like putting a period at the end of
every sentence. If we didnt put a period, we would just have one long unstructured run on sentence,
and that wouldnt help us to understand anything thats being said.
So, as I mentioned before, the syntax of any programming language will likely be your biggest hurdle as
a new developer, but as you see more and more examples of code and are introduced to more and
more syntax in the language, you will become comfortable. There is good news though, for people
have realized that dealing with syntax can be tough, so certain companies (or groups of enthusiasts,
a.k.a nerds) have created tools to help us with the syntax of programming languages. These tools are
called IDEs or Integrated Development Environments, which you can download onto your computer
and use to create programs. These IDEs have built in syntax checkers (much like the grammar checker
in MS Word) that will let you know if your syntax is incorrect, and it will even give you hints with what it
thinks you meant to put! Dont you worry because Ill cover those tools in the next section of this
chapter.
Lets sum up. We have learned that syntax just means that theres a correct way to write down your
code, and this allows the programming language understand what it is that youre trying to tell it to do.
Unfortunately for us, computers cant read our minds (yet!) and know what it is that we want them to
do, so some very smart people have created this computer language; when understood by
programmers, it allows us to tell the computer what actions we would like it to carry out and whether
that action be to send a bill payment to our credit card company or to play a game of poker online with
a virtual table full of strangers. Syntax is our systematic way to talk to a computer and convey our
wishes.
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
22
I hope I have taken a little bit of mystery out of the term syntax, and I look forward to teaching you
about our final subject tools! A developers best friend
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
23
Tools
Welcome back to our fifth lesson in our five part series on the 5 basic concepts of any programming
language. In this java tutorial, the concept well talk about concept is tools.
1.
2.
3.
4.
5.
Variables
Control Structures
Data Structures
Syntax
Tools
What are tools? Well, I dont think we need to go to wiki to define this one, as many of you should
already know what a tool is. In the real world, a tool is something (usually a physical object) that allows
you to get a certain job done in a timelier manner. Well, this holds true within the programming world
too. A tool in programming is a piece of software that, when used while you code, allows you to get
your program done faster!
There are probably tens of thousands, if not hundreds of thousands of different tools across all the
programming languages, but Ill focus on the main tools that everyone is likely to use.
The first and most important tool, in my opinion, is an IDE. An Integrated Development Environment is
a piece of software that will make your coding life so much easier. IDEs will check the syntax of your
code to ensure you dont have any errors, they will organize your files and give you a nice way to view
them (i.e. applies color schemes to your code so its easier to interpret), they tend to have code
completion (which will actually fill in some code for you, in common scenarios), and allow you to
navigate through your code easily. There are many other advantages of using an IDE, but I think you get
the idea. In the Java world, the IDE I use most often is:
Spring (STS)
This IDE is free and full of features, its what I use whenever I program (both at work and at home)
For the purposes of this java tutorial, I will focus on just this one tool, as it will be the most important
thing you use when you begin programming. So, lets install Spring STS! The first thing youll need to
know is that the Spring STS IDE, and all IDEs in Java require the Java Development Kit to be installed on
your computer, so how about we download that now as well here.
Step 1 To download the Java Development Kit (JDK), go to the Oracle Java Development website
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
24
Step 2 Run the downloaded file and leave all options default as you click next
Special Note: This installer will likely popup another installer for the Java Runtime Environment (JRE),
so if it looks like your install has stopped for no reason, check to see if you have any other pop-ups that
may be hidden that require you to click Next.
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
25
Step 3 Click this link to go to the Spring STS download page and skip the registration (if you like):
Step 4 Choose the appropriate version of STS to install. Ive highlighted the windows versions, but I
believe there is a MAC version as well:
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
26
Step 5 Now, once youve downloaded that file, run it and start the installation process. Leave all the
options set to their defaults as you click next. Do it until you get to this screen.
Here you will choose the directory where you installed your Java SDK. The default location is:
C:\Program Files\Java\jdk1.6.0_33
There, now you have successfully installed Spring STS and you are ready to begin programming! Thats
all I will cover. You are now ready to learn how to write your first java program (also known as the Java
Hello World program).
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
27
Chapter 2
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
28
This isnt always the easiest task to accomplish when you are new to a programming language. So, as it
pertains to Java, if you can accomplish all of these tasks and successfully write your Java Hello World
program, then you are off to a good start. Now, we have already covered step 1 above, in Chapter 1. So
lets move on to step 2, writing the code.
First, launch your Spring STS tool, youll notice that you get stuck on this screen:
Youll just need to pic a folder that will house your development files. I usually choose C:\DEV\,
but its your choice. So, pick a folder and click OK.
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
29
Now, with Spring STS open, youll need to start a new project, so choose File -> New -> Java
Project. Youll be presented with this screen:
Be sure to fill out a program name. I used hello World, but you can use any name you like for
this project. Next, you should have the JRE installed so Click Finish.
You may or may not be presented with this window, but if you are just click the Remember my
decision and click
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
30
Yes:
Now, if all went well, you should see something like the following:
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
31
We need to create a new file for this project, so click File -> New -> Class. You should now see
this screen:
Be sure to fill out two fields: Package and Name. The Package I used was com.helloworld. and the
Name I used was Hello World. You can see this in the screenshot above. Now click Finish.
This should have created a new Class file called HelloWorld.java, and you should now see something
like this on your screen:
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
32
Now we are ready to write some code! If you like, you can copy/paste the following code into your
HelloWorld.java file:
package com.helloworld;
public class HelloWorld
{
public static void main(String[] args)
{
System.out.println("Hello World");
}
}
Now, for the final step, youll need to run this! If you right click, your mouse anywhere in the code area,
youll get a menu that will have a menu item named Run As, hover over it and select Java
Application. This will run your code and output Hello World into your console. If you dont see
the console, just click Window -> Show View -> Console, like so:
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
33
Voila, you have just setup, coded, and ran your first Java program! Welcome to your first
accomplishment as a Java developer.
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
34
It was created automatically by our IDE (the Spring STS program youre using to code) when we created
the HelloWorld.java file. Well talk about why this line is important later, but for now just know that it
needs to be there or well get errors.
The second line is:
public class HelloWorld
This line is important for two reasons. The first reason is that it represents the Class. Now when I say
Class, I dont mean a class of students with a teacher. I mean a Java Class file. These Class files represent
a blueprint for an Object in Java. Objects, in Java, are the foundation of the programming language,
because Java is an Object Oriented programming language. Objects in Java represent exactly what they
sound like, an Object in real life. Think of an Object like a noun (person, place or thing). Our example of
HelloWorld.java isnt a great one, as Hello World doesnt really mean anything in the real world.
So, the second reason that this line is important is that the name Hello World has to be exactly that
name because thats the name of the file that we created (HelloWorld.java). We chose to name this file
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
35
HelloWorld.java for no particular reason, but since we chose that name, the name of our declared
Class needs to match. One thing to note is that Java is case sensitive, so that means Hello World is not
the same as hello world. Capital and non-capital letters matter.
One thing I havent yet touched on with this line of code is the first word, public. In Java, there are
four levels of visibility for your code: public, protected, package and private. Essentially all this means is
whether or not other Class files will be able to have access to this particular file. When we say public
that means that any other file can look and interact with this Class file. This concept of visibility is also
used with something called methods. Whats a method you ask? Good segue into the next line of code:
public static void main(String[] args)
The first thing you may notice is that word public again. It means the same thing as it did before,
except now its saying that this particular chunk of code (the code between the curly braces {}) is also
public. Again, this means that any other Class files can access this particular chuck of code! This seems
like a pretty easy concept right?
Now, I said that I would segue into what a method was. Well, you see how I keep referring to this code
as a chunk of code. Well, now its time for me to use the technical term for this chunk of code. Its
called a method! Methods are essentially chunks of code that you can run over and over again by
calling that chunk of code. Calling a method means that I wish to execute all the lines of code that
are present between those curly braces {} of that method. Furthermore, we always give names to our
methods just like we always give names to our variables. For this particular piece of code, the methods
name is main.
So now allow me to re-iterate:
public class HelloWorld
{
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
36
future java tutorial. That just leaves us with (String[] args). This is known as the parameter or
argument section of the method. You see, in Javas syntax, a method can have variables passed in so
we can use them and modify them inside the method if we wish. This is denoted with the parenthesis ()
after the method name.
The last thing I want to quickly point out is the String[] args. Ive mentioned what a String was in
our first lesson on variables, but why are there square brackets [] after the String variable type? This is
just Javas syntax for an Array. I mentioned what an Array was in the Data Structures lesson, but to
refresh your memory, just think of it as a list of Strings. Think of it like a kind of grocery list: Lettuce,
Tomato, Bananas, Pasta sauce, etc. This could represent an Array of Strings and this Array would
be referenced by the variable name args! See?
String[] args
This one is pretty simple to explain. All this code does is output whatever is in quotes into your Console
window in your IDE (Spring STS). This line of code is used most often when you just want to quickly take
a look at the state of a variable at any given moment. For example, if you had a variable
called outsideTemperature and this variable just updated its own value every 30 minutes. Lets say you
want to see what the variables state was (in other words, see what the outside temperature is); then
you could write System.out.println(outsideTemperature). The value that the variable has would
then display in your Console window in your IDE.
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
37
Chapter 3
The Basics
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
38
What is a Method?
What is a method in Java? Well, weve already touched on what a method is in
the Java hello world section, but I want to get more return in depth on the power
of methods (or functions). So first off, youve never heard me say the word
function before, so before I talk about methods, allow me to start with an explanation of what a
function is. In Java, methods and functions are really the same thing. For the sake of argument, Ill just
use the term method from now on. For example, a method in Java could look like this:
Now, this method is a little different. There are two main things that are different. The first thing is the
code public Integer addTheseTwoNumbers1, and you see how weve put the word Integer next to
the public keyword. This indicates that this block of code will return (or spit out) an Integer value.
The second thing that indicates that this block of code is different is the fact that it has a return
statement. When you specify, youre saying that this block of code will be returning (or sending back)
whatever is to the right of it. How about we see what that same block of code would look like if it was a
method that didnt return anything?:
Can you spot the differences? First, theres no code saying public Integer, but it says public void.
The void modifier indicates that this block of code wont be returning anything. The second thing to
notice is that theres no more return keyword in the method.
So, what is a method in Java? Well, a method is that a piece of code that
could perform some operations, then return something back to whatever happened to call the
method. Furthermore, a method will perform some operations, without needing to return anything
when its done, and the flow of code will just continue back from whatever called the method. Either
way, a method will execute some block of useful code that can be called repeatedly from anywhere in
your program (as long as its declared public).
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
39
To illustrate how the code flow could differ between method calls, lets take a look at this program:
public class MyProgram
{
public static void main(String[] args)
{
//---------------------------------------------//
// here's our method call that returns a value //
Integer resultOfAddition = addTheseTwoNumbers1(5, 24);
//---------------------------------------------//
System.out.println(resultOfAddition);
//----------------------------------------------------//
// here's our method call that doesn't return a value //
addTheseTwoNumbers2(3, 13);
//----------------------------------------------------//
}
public static Integer addTheseTwoNumbers1 (Integer firstNumber,
Integer secondNumber)
{
return firstNumber + secondNumber;
}
public static void addTheseTwoNumbers2 (Integer firstNumber,
Integer secondNumber)
{
Integer addedValue = firstNumber + secondNumber;
}
}
If you were to copy/paste this code into your IDE (Spring STS) and run it, youll see the following output:
29
This may or may not surprise you. If I were to look at this for the first time, Id probably guess that you
would see 29 and then 16. I would guess this because I see addTheseTwoNumbers1(5,
24) and addTheseTwoNumbers2(3, 13), so naturally 5 + 24 = 29 and 3 + 13 = 16. Why didnt we see
these two numbers as the output? Well thats because for one of the calls we used a return statement
and for the other we didnt. Since one method returns a value, we can then use that value and display it
in our console (by using System.out.println()). Whereas with the second method, we dont have a
value being returned, so all that happens is that the two numbers are added together, and then we exit
the method and the code continues to flow without invoking the System.out.println() code.
Why dont we just always use methods that return values? They seem more useful because they give us
something that we can work with. Well, thats just because a method that returned a value was more
useful to use with this particular example. There are times when you dont need something returned;
for example, if you created a method to send an email to someone:
public void sendEmail(String contactAddress)
{
String emailContents = "this is a test email.";
Email.send(contactAddress, emailContents);
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
40
You see? We dont want anything back, but we want to have the code send the email and go about its
business. Okay, so I hope Ive helped answer the question What is a method in Java? and that you
understand everything entirely.
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
41
All these words represent Objects in Java. This really is, in essence, Object Oriented programming
(generally known as O-O programming). What we can now go about doing, is in fact arrange these four
Objects on to some sort of piece of paper and begin to distinguish what sort of attributes each one of
these Objects contains. What do I mean by the attributes? Well, in O-O development, this is known as
identifying the has a relationships. To provide an example, a Branch has an address, a Book has a
title, a Customer has a name. We will map out the most important attributes that each one of these
Objects contain and build ourselves a terrific starting point for the design of our Java application.
Object Oriented development allows developers to think in terms of real life things or Objects and
simply solve issues with all those Objects. Its important to remember that Java is actually not the only
O-O programming language in existence, as it was initially started nearly five decades ago and plenty of
modern programming languages utilize Object Oriented principles. Some of these languages include
C++, C#, Objective-C, Python, Ruby, and Visual Basic.
What would the Objects from our example look like in code? Lets take a look at the Book Object:
public class Book
{
private String author;
private String title;
private Integer isbn;
private Integer numberOfPages;
public String getAuthor()
{
return author;
}
public void setAuthor(String author)
{
this.author = author;
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
42
}
public String getTitle()
{
return title;
}
public void setTitle(String title)
{
this.title = title;
}
public Integer getIsbn()
{
return isbn;
}
public void setIsbn(Integer isbn)
{
this.isbn = isbn;
}
public Integer getNumberOfPages()
{
return numberOfPages;
}
public void setNumberOfPages(Integer numberOfPages)
{
this.numberOfPages = numberOfPages;
}
}
Okay, so what can we identify in this code that we are already familiar with? Well, we certainly see the
word public a lot sprinkled around here. To refresh your memory, the word public is a modifier that
allows for any Java Class to have access to the code within the scope of what its modifying. So, you see
that the first public keyword is placed on the Class name, which in this case is Book.
This means that our Book Class will be accessible by all other Classes in our project.
Note: You may have noticed I used the terms Class and Object to describe the same
thing. In actual fact, they are very similar, but the only difference is that the Class
can be considered the blueprint for an Object. An Object is what is physically
created when the Java program is running. So if I want to create a Book, lets say
a Harry Potter Book, I would instantiate (or create) a Book Object based on its
Class blueprint. Make sense?
Lets move on to the private modifier that you see on the first four variables (or attributes) of
our Book Class. This is kind of strange you might think. If a Book has attributes like a title, an author etc.;
then why are these marked as private? Wouldnt we want other Classes to have access to a Book title
for instance? Yes and no, for this approach used here is called encapsulation, and its one of
the fundamental principles in Object Oriented programming. Lets flip over to Wiki for a definition of
encapsulation:
In a programming language, encapsulation is used to refer to one of two related but distinct notions,
and sometimes to the combination thereof:
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
43
In our example, we are touching on the first part of this definition, which is restricting access. We dont
want just anyone to be able to come in and say, change the title of our Book Object. We want to be able
to screen or moderate what changes are allowed and which are not. So we accomplish this by
setting the attributes of our Book to be private and introduce public methods where youll be able to
retrieve and/or change the value of our Books attributes. So, if you want to know what a Books
particular title is, you would have to ask like this:
String aBooksTitle = book.getTitle();
And just the same, if you wanted to change a particular Books title, you would do this:
book.setTitle("Harry Potter Vol. 2");
If the reasoning behind why we are doing this doesnt seem to make sense at the moment, dont worry.
This approach is used over and over in Object Oriented programming languages, so you will become
familiar with it and it will make sense in time. The main take-away for this Java tutorial is to know
that Object Oriented programming just means that we can create programs in terms of real life
Objects, and those Objects have ways of interacting with each other! This is a piece of cake right?
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
44
Nested IF Statements
Heres a quick tutorial on the IF statement and some of its more complex uses.
The nested IF
At this point, you are all fairly comfortable with the if statement as its the most basic control structure
in the Java programming language (and other languages too), but were you aware that you could nest
these if statements inside of each other?
How about I first introduce a simple example to refresh your memory!
int age = 29;
if (age < 19)
{
System.out.println("You are not an adult.");
}
else
{
System.out.println("You are an adult.");
}
As you can see here we have a standard if..else structure. In this particular example Ive set
the age variable equal to the int value 29. So, since you are very keen with your Java knowledge, I bet
youd guess that the console output would read You are an adult. Nice! So lets get a little more
complicated shall we?
int age = 29;
if (age < 13)
{
System.out.println("You are but a wee child!");
}
else if (age < 19)
{
System.out.println("You are no longer a child, but a budding teenager.");
}
else
{
if (age < 65)
{
System.out.println("You are an adult!");
}
else
{
System.out.println("You are now a senior, enjoy the good life friends!");
}
System.out.println("Also, since you are over the age of 19, you deserve a drink!");
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
45
Alright! So, you see here how I made use of a nested if statement? Since my age variable is still set as
29, the code will flow to the first if and check to see if the age is less than 13. We all know that 29
is not less than 13, so we continue downward to the first else if. Now We check if age is less than 19,
its not, so we continue to the next else if. But heres where it gets interesting, there are no
more else if statements, all we have left is an else block. So, what happens?
Well, the same rules always apply to the flow of code in an if..else condition. If the none of the
conditions evaluate to true in all the if conditions, then the code will automatically choose
the else path if it exists. In our example, it does indeed exist. So the code will choose that path. And
what do you know, weve now encountered ..else block of code. So, as predictable as the sun will rise
and set, Java will follow the same set of rules for this new if..else block.
We will now evaluate if age is less than 65. And as luck would have it, our variable is set to 29. So, yes,
29 is less than 65, so well execute the code inside of this block and the console will output You are an
adult.
Now, heres where it might get tricky to some. Where does the code flow from here?!
You have to consider the fact that you are now inside of nested if statements and make note of where
the beginning and end of all of those curly braces {} are. Allow me to re-write the code block with some
comments that may help you visualize where the code will flow.
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
46
So, since the age is set to 29, the code will NOT execute the nested else condition. Because if it did, Java
would be violating its most basic if..else rules for code flow right? So instead it will skip over
the else block. And what do we see after the inner else block? Yet another console output line! So you
will see this output on your console too: Also, since you are over the age of 19, you deserve a drink!
This gets outputted because we know were inside that outer else block of code. Remember to follow
through those curly braces {} to know exactly where you are.
The code then exits the outer else code block and the program will terminate.
Summary
Nested if statements are a fairly straight-forward concept that allows you to have good control over
what code gets executed (and NOT executed) in certain scenarios. If you would like a good
understanding of how Java reads through line by line, Id recommend watching my video
on Constructors. I will show you how the code flows in the debugger, and if you dont know how to
debug yet, Id also recommend watching this video!
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
47
Java Arrays
Weve talked about the concept of Java Arrays back in Chapter 1, so if you like to
you brush up on what we talked about, feel free.
You can combine them all into one variables name like so:
List<String> contacts = new ArrayList<String>();
Now, this code is for an ArrayList, which for me, is used heavily in my day to day programming
endeavors, but this is in fact just a flavor of Java Arrays as its based on a Java List. Please allow me to
introduce you to the original Java Array.
String[] contacts = new String[10];
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
48
The reason why this fails is because you havent initialized the Array. So lets re-write this code with the
initialization part included:
String[] contacts;
contacts = new String[10];
System.out.println(contacts[1]);
This will now work, but, you wont see anything displayed in your console because although youve
initialized the Array, you havent yet actually populated it with anything. How about we populate it with
stuff? I want to keep this example simple, so Im going to use a loop to populate the Array:
String[] contacts = new String[10];
for (int i=0; i < contacts.length; i++)
{
contacts[i] = "person" + i;
System.out.println(contacts[i]);
}
What weve done here is initialized the Array with a size of 10 and weve created a for loop that
will iterate over each element in the Array and populate it with something. In our case, were iterating
over the for loop 10 times, as the for loop is based on the size of the Array (which is 10 elements in
length). And for each iteration, we are storing the String person followed by the index of the current
iteration of the for loop. It sounds complicated but heres the output:
person0
person1
person2
person3
person4
person5
person6
person7
person8
person9
The word person is followed by the current index of the Array 10 times. Why did the loop start with
person0 and not person1? Werent you expecting to see the numbers 1 through 10? Well, that
happened for two reasons. The main reason it starts at zero is because my for loop was coded to start
at 0 and run 10 times (i.e. 0 -> 9), but I did that for a reason. The reason I did it is because Java uses
a zero based numbering system for its Array. When you want to refer to the FIRST element in an
array, you use the number 0. The second element would be index 1. The third would be index 2 and so
on. Had I programmed my for loop to start from index 1 and go until index 10, we would have seen an
error when it tried to output the last element in the Array because element at index 10 doesnt exist!
Only elements 0 -> 9 exist. One neat thing Id like to point out about Arrays is that you can have
something called a multi-dimensional Array. Now, having seen these in real world coding scenarios, they
are a pain in the butt to understand and debug, so I wouldnt recommend using them unless you put
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
49
plenty of comments in your code describing its purpose. But for the sake of completion, Ill show you
how to use them. Lets say you wanted to create a crossword puzzle program.
Example:
A
Q
W
V
D
N
I
K
L
N
N
N
E
O
D
E
Here we have a 44 multi-dimensional Array. The code to create this crossword puzzle would look like:
String[][] crossword = new String[4][4];
crossword[0][0]
"E";
crossword[1][0]
"O";
crossword[2][0]
"D";
crossword[3][0]
"E";
Now, having explained what an Array is in Java, Id like to go back to what I mentioned before about
the ArrayList. I find that the ArrayList is more useful in most coding situations, it has built in methods
that allow you to do things like adding and removing elements without having to worry about the
size of the Array (as it will grow and shrink as necessary). But, it is however, important to know what
an Array is in Java and what the syntax looks like.
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
50
int aPrimitiveInteger;
double aPrimitiveDouble;
char[] aPrimitiveString;
What youll notice is that the primitive version of an Integer is int, the primitive version of a Double is
double and the primitive version of a String is an array of chars (note: if you dont remember what an
array is, click here).
Now that we know what these things look like, how do they work? Lets start by showing what the
differences are considering this code:
private static int anInt;
private static Integer anotherInt;
public static void main (String[] args)
{
System.out.println(anInt);
System.out.println(anotherInt);
}
This is the first big difference between a primitive data type and an Object. Primitives have default
values that are assigned to them as soon as they are declared (in all cases except when the primitives
are local variables). In other words, as soon as I write the code: private static int anInt, the
variable will have the value of 0. Now, I could have easily chosen to give it a value like this:
private static int aPrimitiveInteger = 32;
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
51
The point Im trying to get at is that you dont have to give the primitive an initial value, for itll have one
as soon as its created (again, in most cases). Primitive ints are NEVER null. Whereas, their Object
counterparts Integer always have a value of null if theyre not assigned a value.
Now lets say all you have is Integers to pass into this method. Youll need to first convert your Integer
into a String before Java will let you run your code, so youll need to do this:
You see? Weve converted our Integer to a String by using the toString() method of the Integer
Object. If we had used a primitive int, we would not be able to do this.
So theres clearly a trade-off of performance vs. convenience. If youre dealing with straight up numbers
and calculations, primitives are a solid choice; if you need to be manipulating your variables data then
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
52
using the Object equivalent makes more sense. In any case, you should now have a better
understanding of what primitive data types are in Java.
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
53
Strings
Strings in Java are a widely used data type (and in most programming languages),
they allow us to store anything and everything that has to do with words,
sentences, phone numbers, or even just regular numbers. But, as useful as they
are, youll need to know a few important things about Strings before you go wild
using them in your code.
made up of an array of char primitives. In other words, if you create the String Hello World like so:
String helloVar = "Hello World";
then if you were to look at the helloVar variable in your debugger, you will see the following:
You can see how the String is made up of an array with 11 elements (0 -> 10) where [0] = H, [1] =
e, [2] = l, [3] = l, [4] = 0 etc. Alright, so who really cares that its made up of an array of chars
then right!? Well, I just didnt want you to get confused when you saw your Strings in the debugger
So lets move onto another important fact about Strings in Java, they are immutable! What does that
mean? It means that once you create a String, it cannot be changed. So for the example above with
my helloVar, if I wanted to change that variables content, I would have to:
1.
2.
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
54
Okay, so you might be thinking re-assign into the existing variable wouldnt that mean changing it?
Which you just told me I couldnt do! Well, what happens behind the scenes is whats interesting, but it
will involve me talking about computer memory. Now this isnt the most exciting of all topics, but Ill
have to explain it for completion sake, otherwise the professional programmers (also known as geeks)
out there will start screaming for attention.
Memory
This topic is huge, and I could probably write a lot on this one topic, but to save you from that dull
reading, Ill give you a useful summary. You see, all variables in Java will be stored in memory on your
computer. The variables will be assigned a location that is identified by an address. Think of the address
in memory like your own home address. If you create a new String variable, it will be assigned an
address that is currently empty. This is just like if you were to move into a new home, youre obviously
not going to move into a home where someone is already living right? Same thing happens with
computer memory, Java will figure out where theres some empty memory space and have the new
variable move in or occupy that space. Now, since Strings are immutable, they cannot be changed,
and thus, you cannot go to the address where that variable exists and starts messing around with it. The
only way to change what currently exists at that address is to assign it a new address with its modified
value. The comparison to the real world would be if you were living in your house at your address with
your spouse and two children, but if you wanted to have a new child occupy space in your house, youll
have to move into a new house first! Its not the greatest example, but I feel like it works well enough.
What if you want to just replace a String variable that already exists with a new value, what will
happen then? Well, essentially Java will just demolish your house (clear your current variables memory)
and move you into the house next door (assign the same variable to the next available memory
location).
Phew, you see what I mean by a dull subject. All you really need to understand is that you cant change a
String in its memory address. Once its created, its there until it gets destroyed (also known as
Garbage Collected another huge topic that I wont cover right now). So, lets move onto something
more interesting
String Concatenation
One more fun thing you can do with Strings in Java is String concatenation. What does that mean? It just
means that you can put a bunch of Strings together to make one bigger String. Heres an example:
String str1 = "Hello ";
String str2 = "World";
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
55
You see those plus + signs between the three variables in the System.out.println? That is string
concatenation at work. What its saying is to append the second string to the first, and then append
the third string to the second. Whats the result?
Hello World!
The usefulness of this may not be apparent at the moment, but one real world example I can think of is
when you have your first and last names stored in two separate variables. Youve probably seen this
many times on the internet. Youll fill out a form of some sort to sign up for a mailing list perhaps then
youll receive an email later that has your full name printed. This is an example of String concatenation.
Example:
String firstName = "Trevor";
String lastName = "Page";
System.out.println("Hello there " + firstName + " " + lastName + ".");
This would output Hello there Trevor Page. You see how we not only put the plus + sign between
the variables, but we also threw in some Strings that werent assigned to variables? We can do this
because whenever you put letters/numbers between those double quotes , Java will interpret it as
a String and will allow you to concatenate it to your other String variables! Neat
The final thing I want to mention is that you can get yourself into some trouble when trying to compare
two Strings to each other. For now I will just say that you need to use the equals() method whenever
comparing two Strings. The reason for this is what I will be explaining in the next section, as it has to do
with Objects in general.
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
56
Packages
What is a Java package? Why is it useful? What does it look like in code? These are
the questions Ill answer!
Alrighty, so here we see that Spring STS has a Package Explorer view. If you dont see this in your
Spring IDE, then try clicking on the following menus:
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
57
Window -> Show View -> Package Explorer (or Other, then type in Package Explorer)
So, what you see above is essentially the equivalent of having the following directory structure in your
file system:
-> com
-> howtoprogramwithjava
-> business
-- Bus.java
-- Car.java
-- Vehicle.java
-> runnable
-- MyProgram.java
If that makes sense to you, then your next question would probably be Now that I understand WHAT a
package is, HOW do I create them in MY project? Piece of cake, all I did to create these packages was
right click on my src folder (or the root How To Program folder) and choose New -> Package. You just
need to type in your packages names separated by periods (.) like so:
By convention, package names should be entirely lowercase. They dont have to be, but its just how
everyone else does it, so you might as well be like the rest of the programming herd! Also, another
convention is that if youre developing a Java project for a website, you generally name your packages
after the website address in reverse order. My website is howtoprogramwithjava.com. In turn, the
packages I would create are com.howtoprogramwithjava.someotherpackage. Again, just a
convention, but it makes it easier for any new programmer to jump into your code and understand
everything with relative ease.
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
58
package needs to have the declaration of that package at the very top of the file. So, in the case of
my Vehicle Class file, the code will look like this:
package com.howtoprogramwithjava.business;
public class Vehicle
{
// code removed for the sake of learning about packages only!
}
Thats all there is to it, since the Vehicle Class file exists inside of the
com.howtoprogramwithjava.business package, it needs to have that declared at the very top. And
yes, it has to be at the top, otherwise your code wont compile properly. The first thing youll see in any
Java file is the package declaration, but whats tricky is that most Java tutorials online or in books leave
this declaration out (simply because they assume that you know what a package is). So now Ill be the
one to tell you that thats the case, I wont assume you know this
Have I beat this concept into your heads now? Will you always remember what a package is, and that
you should use them to keep things neat and organized? Do they seem straight-forward enough to you?
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
59
Imports
What are Java imports? How are imports used in Java code? Why do I need imports? Is there any easy
way to manage imports? These are the questions I hope to answer in order to give you a full
understanding of why these imports used.
Read the contents of a file / Create a file and populate it with contents
Compare dates with each other (i.e. see if one date is before or after another)
Send emails to anyone
Okay, thats great, so what does that have to do with imports? Well, all of these classes are nicely
organized in packages, and if you want to USE these classes, youll need to import them into your
project. So, this means that before you can play around with Dates, youll need to import
the Date object first!
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
60
If you have a keen eye, youll spot in the imports at the very beginning of this code segment. This code
means that in the package java.util there are Classes called Date and Calendar, and we want to
use them in our program! The reason we need to tell Java that we are going to use these Classes is for
the sake of brevity and specificity. A great example of this is the Date class. You may or may not know
this, but there are more than one Date classes in Java. There is a java.util.Date class and
a java.sql.Date class.
You can imagine how it would be impossible for Java to decide which Date class youre actually referring
to right, so you just need to specify which one youd like to use.
Notice the import statements at the top are gone and weve now prefixed every Date and Calendar
reference with java.util. This is the correct code and will compile just fine. But its a bit annoying to
have to write out the java.util every time you reference Date or Calendar. We have import
statements in Java because it makes life easier!
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
61
in and put in the import statement in code. The shortcut keys are Ctrl-Shift-O (thats Control-Shift-Oh,
not zero). Try it out yourself by copying/pasting the following code and youll see that there are errors
with all the Date and Calendar classes. Hitting Ctrl-Shift-O, Spring STS will ask you if you
want java.util.Date or java.sql.Date. Choose java.util.Date and voila the import code is
automatically added to the top of your Class file!
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
62
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
63
Alright ladies and gentlemen, its time to put your knowledge to the test!
Heres what were going to do, I will outline the requirements for a practice assignment, and I will
include an archive file with the contents of the assignment (at the top of this page). I will also include a
video which will explain how to import the assignment into your SpringSource Tool Suite IDE and set it
up so youll be good to go.
Sound good?
The Requirements
The assignment is to simulate the lottery. You will need to implement code that will generate 6 lottery
numbers between 1 and 49 (inclusive), you will then need to implement the code that will read in 6
numbers that you will type into the console yourself. Then the numbers you input will be compared
against the randomly generated lottery numbers and it will output which numbers match (if any).
Heres the catch, you will need to make sure there are no duplicate numbers (either when being
randomly generated or inputted in the console). Its just like a real lottery after-all!
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
64
Chapter 4
Building Blocks
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
65
One of the most important and fundamental aspects to Java is the Java Object.
Since this topic is central to the entire programming language, lets talk about the
things you SHOULD know about Objects!
Okay, so what should you know? Well, first I want to talk about why the Java Object is so fundamental
to the programming language.
Java Object
Weve already talked about many examples of Objects in Java. These are what I would define as a
noun in any sentence that would define a business problem. These nouns could include words
like, User, Library, Vehicle, but whats one Object we havent yet mentioned? The answer is easier than
you may think. Its Object! Did you know that you could set a variables type in Java to be Object? Well,
you can and its quite handy!
Everything is an Object
In Java, any object you create (User, Library, Vehicle) is actually of type Object. This concept is what is
so fundamental to understand. So lets say you create the object User, it could look like this:
public class User
{
private String username;
private String password;
public String getUsername()
{
return username;
}
public void setUsername(String username)
{
this.username = username;
}
public String getPassword()
{
return password;
}
public void setPassword(String password)
{
this.password = password;
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
66
}
}
Now, theres nothing in this code that would indicate that this User object is actually of type Object.
Usually, to determine if one particular object inherits properties of another object, you would look to
see if your object extends another object. But in the case of our User there is no extends code. What
the heck?! Well, since all Objects in Java inherit from the Object type, theres no need to explicitly show
this in our code. If you dont believe me, try creating a new Object with your STS IDE. Heres a
screenshot from when I made the User object above:
Notice that the super class of this User objects Im creating automatically defaults to Object? Well,
thats because all objects in Java inherit from Object!
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
67
The exceptions are primitive data types. Primitives do not inherit from the Object type in Java, but
thats the only exception to the rule. Everything else in Java either directly (or indirectly) inherits from
the Object type.
There are a few methods there that we didnt create, these include:
equals()
getClass()
hashCode()
notify()
notifyAll()
toString()
wait()
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
68
wait(long timeout)
wait(long timeout, int nanos)
And if you notice in the screenshot above, on the far right of all these methods, is the word Object. This
is because all of these methods belong to the Object type. Make sense? Its nice to know whats actually
going on here. The only other topic to cover is what all of these methods are used for, but I dont want
to dive into all of them in detail, so Ill get the ones I dont want to talk about out of the way right now.
Threading Methods
notify()
notifyAll()
wait()
wait(long timeout)
Why are we talking about a equals() method then? Well, remember when I said that primitive types
are the exception to the rule? That means that primitive types dont inherit from the Object type right?
If thats the case, then that means that primitive types dont have access to the methods that are
defined within Object, which includes equals()!
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
69
Very interesting, so then if we want to compare two objects, then we just use the equals method then
right? This is true but theres a bit of work that well need to do to ensure that when we do compare
two objects, we get the expected result. Consider the following:
User user1 = new User();
User user2 = new User();
user1.setUsername("Trevor Page");
user1.setPassword("aPassword");
user2.setUsername("Trevor Page");
user2.setPassword("aPassword");
System.out.println("Are users equal? " + user1.equals(user2));
What would you expect to see as the output here? We are instantiating two User objects, and we are
assigning the exact same username and password to both Users. Then we are just invoking
the equals() method to check if both Users are equal. We would assume that since both the username
and password are equal and that the result would be true. Heres the actual result:
Are users equal? false
Well what the heck! Why arent they equal? Well, this comes down to inheritance and the default
implementation of the equals() method.
Now pay attention because this is important!
If you do not override the default implementation of the equals() method, then Java will default to the
strictest implementation of an equals comparison. And that is the == operator!
What does the == operator do!
The == operator (spoken as equals operator) compares two objects by their physical memory
address.
So how does this apply to our example above with the two Users? Since we havent overridden
the equals() method, it will compare the two objects using the == operator, which will compare their
addresses in memory. Since I created two objects (via the new keyword), this means we have two
separate objects in two separate memory locations. Since they have two unique locations in memory,
the equals() comparison will return false.
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
70
Hopefully in any web application no two users would be allowed to have the same usernames. If we
have two User objects and they both have the same username, then we could consider them equal.
How do we accomplish this? We override the equals() method on the User object! So our
new User object would look like this:
Notice the last section of our User object has an @Override over the equals() method. Well, this is
how we override the equals() method of the super class (the Object class). This is the inheritance I
was talking about. In Java we are allowed to change the behavior of a method that we inherit from a
parent Class. In this case, the parent Class of our User object is Object. Because the Object Class has
an equals() method, then that means we can change its behavior in our child class (the User Class).
Since we didnt like how the Objects equals() method worked, we override its functionality in
our User Class! And this is the code you see above.
So! This is fairly complex stuff if youre new to programming, so allow me to keep explaining. Lets take a
look at the code where we actually compare the two Users together, as this may shed some light on this
subject
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
71
user1.equals(user2)
Remember that the User definition (with the @Override equals code) is a Class that represents the
blueprint for any User object. So when we instantiate a User object, each one will essentially have its
own version of the @Override equals method defined in the User Class.
This means that when we run that important code, we are saying:
Hey! user1! Run your equals() method, and pass in user2 as a parameter. So what we may actually see
if we were to debug this is the following (Ive commented out the actual code, and instead, replaced the
code with what would essentially be replaced at runtime when Java runs the code):
@Override
//public boolean equals(Object obj)
public boolean equals(User user2)
{
// return this.username.equals(((User)obj).getUsername());
return user1.username.equals(user2.getUsername());
}
So, what really ends up happening is that we pass in the user2 object as a parameter. Now, what
normally happens is the equals method takes an Object as a parameter, but since a User is an Object,
Java is okay with you doing this (inheritance). Then we say, this.username. Well this just refers to
whatever Object the Class represents. So in our case, since we invoked the equals() method of user1,
that means were inside of the user1 equals method, which means that when we say this we really
mean user1! But then we say this.username.equals(), doesnt that mean we just invoke the equals
method on user1 again, resulting in an endless loop? No! Were invoking equals on user1.username
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
72
and username is just a String. So thats perfectly legitimate, as String defines its
own equals()method. Then we just pass in user2 username into the equals() method for the String
comparison. Which we know that, if both Strings are the same, then it will return true!
Phew, thats some hardcore coding there! If you understand it, then thats amazing, and Ive done a
great job of explaining the concepts. If you dont understand it, then youre probably part of the large
portion of the new programmers on this planet. The topics that stem from Javas Object class are quite
complex as they require a solid understanding of Object Oriented Programming (more specifically
inheritance and polymorphism). So, if you dont get it, take some time to re-read this tutorial and maybe
try messing around with the coding examples Ive given.
Loose ends
I havent talked about the other methods that come from the Object class, such as hashCode() and to
String(). So let me touch on these quickly.
toString()
This method is used to return a String representation of our objects. The default implementation of
this (from the Object class) will just return a readable version of the physical memory address. So if I
were to do a System.out.println() on the user1 object, I would get the following:
com.howtoprogramwithjava.business.User@7d8a992f
This means nothing to us, and its not helpful, other than if you would like to check to see if two objects
reference the same memory location. So thats why we can override the toString() method to give
something more meaningful. Lets override it! Please add the following method to our User class
@Override
public String toString()
{
return "Username: " + this.username + ", password: " + this.password;
}
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
73
the equals method, its good practice to also override the hashCode()method. This is so that if your
objects are put into a Map, Java will be able to store them nicely inside of your HashMap. How do you
override hashCode()? Also slightly advanced, but for now try this In your STS, try right-clicking in
your User code then:
Source -> Override/Implement Methods -> Choose Hash Code -> OK
Summary
I encourage you to take a break, try to digest this information, and perhaps come BACK and re-read
everything so you have a good understanding of these concepts. As Ive said, these are more advanced
topics, but they are critical to understand if you want to get the hang of programming in Java.
In Object Oriented programming (i.e. the Java programming language), Inheritance is one of the key
principles that is beneficial to use in the design of any software application. Java inheritance allows for a
neat way to define relationships between your Objects (an in turn re-use your code so you dont have to
type the same stuff over and over again).
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
74
1.
2.
3.
Car
Bus
Motorcycle
Do you see how a Car is a Vehicle, how a Bus is a Vehicle, how a Motorcycle is a Vehicle etc.? This is
a relationship and is what Java Inheritance is all about. When you can verbally say that something is
a something else, then you have a relationship between those two Objects, and therefore you have
Inheritance.
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
75
Motorcycle. The super Class is essentially the Object that will hold all the attributes that are common,
so our Vehicle super Class would have the following attributes:
Wheels
Seats
From our inspection of all the types of Vehicles above, we identify that all types of Vehicles have
wheels and seats. But notice that I didnt put doors as part of the Vehicle object. This is because
Motorcycles dont have doors! Doors would only be attributes of Cars and Busses, so we will have a
door attribute on the Car and Bus Objects. Make sense?
Without further delay, lets look at some examples of an Interface and an abstract class.
Interface
public interface Vehicle
{
public Integer getNumberOfSeats();
public Integer getNumberOfWheels();
public String getVehicleType();
}
Here weve declared an Interface for our Vehicle and it has three
methods, getNumberOfSeats(),getNumberOfWheels() and getVehicleType(). As you can see, there
is no implementation of the code, weve just outlined some methods. So, now to make this interface
useful, we need to implement it somewhere! So lets see what that would look like:
public class Car implements Vehicle
{
@Override
public Integer getNumberOfSeats()
{
return 5;
}
@Override
public Integer getNumberOfWheels()
{
return 4;
}
@Override
public String getVehicleType()
{
return "Car";
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
76
}
public Integer getNumberOfDoors()
{
return 2;
}
}
This is what the Cars implementation of the Vehicle interface would look like! For this example, Ive
stated (in code) that a Car has 5 seats, 4 wheels and 2 doors. Lets see what a Bus would look like:
public class Bus implements Vehicle
{
@Override
public Integer getNumberOfSeats()
{
return 35;
}
@Override
public Integer getNumberOfWheels()
{
return 6;
}
@Override
public String getVehicleType()
{
return "Bus";
}
public Integer getNumberOfDoors()
{
return 4;
}
}
This is self-explanatory right? Well, except for those @Override lines. What do those mean? These are
called annotations and these were introduced in Java version 5 (we are currently on Java version 7). An
annotation is anything that you see with an @ (at) symbol before some text above a method declaration
or a class declaration. These particular @Override annotations are just saying that the method below it
is from a parent (or super) class, and we are implementing the desired behavior in this particular class.
In the case of an Interface, we have to override the methods, as its a requirement with Interfaces.
Take special note that we dont have an @Override annotation on our get Number Of
Doors() method. This is because it wasnt declared in our Interface. Remember why? It is because
a Motorcycle doesnt have doors, so it wouldnt make sense to put it in the Interface! Now, dont get me
wrong, in the world of programming there are always several ways to solve the same problem, so you
could have put something like has Doors() in the Vehicle Interface and had it return a Boolean value
of true or false (true in the case of Car and Bus, false in the case of Motorcycle). But, for the purpose of
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
77
illustrating that you can have your own non-overridden methods in your child classes, I chose to do it
the way I did it.
Abstract Class
Lets look at abstract classes now. Remember that abstract classes dont necessarily need their methods
overridden, and the methods can contain implementation if you want. If we were to create an abstract
class for the Vehicle object, it could look like this:
As you can see here, we have some real code implemented in our getNumberOfSeats() method. The
code relies on the vehicleType attribute. Lets take a look at how a child class would use
this Vehicle abstract class:
public class Car extends Vehicle
{
public Car ()
{
this.vehicleType = "Car";
}
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
78
The first noticeable difference between an interface and an abstract class is that you need to use the
keyword implements when you want a child class to use an Interface, and you need to use the
keyword extends when you want a child class to use an abstract class. Weve also done something
interesting with this code:
public Car ()
{
this.vehicleType = "Car";
}
This is called a constructor. The purpose of a constructor in Java is to outline a section of code that will
be executed when an Object is first instantiated. So, this just means that when someone creates an
instance of our Car Object, Java will automatically set the vehicleType to be Car.
So now, if we were to write some code get the number of seats that our Car has, we would see that it
has 5, because Java will see that the super class (Vehicle) has a method that defines the number of
seats (getNumberOfSeats()).
Okay, so now for those who want to go the extra mile, I challenge you to put together a Java program
that will allow you to use an abstract Vehicle class and properly output the following console lines:
My
My
My
My
Car
Car
Bus
Bus
has
has
has
has
2 seats.
4 wheels.
20 seats.
6 wheels.
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
79
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
80
My goal for this assignment is to get you familiar with inheritance and the importance of dealing with
the public methods available in the Java Object class. In practice assignment 2, youll learn how to use
both an interface and an abstract class.
Important Notes:
1. Ive included two library files (JAR files) in the source code of this assignment. You still need to
add them to the classpath when you extract this assignment and begin working on it. To do this,
just right click on the Project and select Properties, then Java Build Path, then Add JARs, and
navigate to the src/lib directory to add both JAR files.
2. As with the first assignment there are Tests available that must pass. Currently they should all
fail AND they will have compilation errors. The compilation errors are expected, as youll need
to implement the appropriate methods from the interface and abstract classes (and then some).
Once youve successfully coded the assignment, you wont have any compilation errors and all
the tests will pass. To run the tests, just right click on the Tests class name and select Run As>JUnit test.
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
81
Assignment Requirements
Okay so heres the breakdown of the requirements for this assignment. You will need to develop a
system that can track employee information for two Organizations (Google and Microsoft). The
Employee information you must track is as follows:
Name
Sex
Job Title
Organization they work for
Birthday
As for the Organization that the Employee works for, you must also track this information:
Organization Name
Number of Employees
The system must be able to properly compare any two employees against each other to determine if
they are the same Person. This means that if you compared two People with the same Name, Sex, Job
Title and Organization, the system should think that they are equals to one another. If any of these
properties are different, then the two People are not the same Person.
The same rules apply to comparing Organizations to one another. Organizations with the same
Organization name are to be thought of as equal, different names means different organizations.
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
82
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
83
We have just instantiated a Car Object based on the Vehicle super class. So what does this imply? Well,
we had to create two classes for this code, a Vehicle Class and a Car Class (a Car is a Vehicle).
Somewhere in the computers memory, a Car Object will exist. Whats critical to note here is that
BEFORE this Car was instantiated, there was nothing in the computers memory, there was just two
Class files (or blueprints) for a Car and a Vehicle. This is the critical difference between a Class and an
Object. One exists in memory where you can access it and change it (the Object), and the other exists in
part of the memory that you cant access as a code blueprint FOR an Object (a Class).
Okay, so now that Ive drilled that into your brains, I can talk about what the static keyword in Java
means. In Java, you can make variables and methods static. Static methods and variables can also be
called static methods and static variables. Why they are also called this? It is because a static method (or
variable) exists as part of the Class and not the instance of that Class (the Object). The implication of this
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
84
is that you dont need to instantiate an Object of that Class in order to access the static method/variable
that belongs to that Class. Does that make sense to you? Perhaps not entirely, so lets use some real
examples! Static methods are often used as helper methods. These helper methods are nice, because
you dont have to instantiate the Object in order to use them. Lets say theres a global speed limit of 80,
and you want to be able to check to see if youre over the speed limit at any given moment in time, your
code could look like this:
So when we run this program (from the MyProgram -> main method) well see the following output:
Go faster, you're only going 70
Slow down! You're over the limit by 75
So, this may not seem like weve done something different from any other examples Ive given you, but
theres one main difference. Weve called a static method on the Vehicle Class:
Vehicle.checkIfOverSpeedLimit(70);
Vehicle.checkIfOverSpeedLimit(155);
Notice how this is a little different from how we usually call methods. Theres no instantiation going on
here! Normally we would have to do this:
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
85
If you were to type this code into your MyProgram -> main method, youll see that it gets highlighted
with a yellow underline and you get the following warning:
The static method checkIfOverSpeedLimit(Integer) from the type Vehicle should be accessed in a
static way.
Your IDE is yelling at you because youre trying to invoke a static method (Class method) on the actual
instance of the Class (the Object). Now, mind you, this will compile and it will run properly, its just not a
recommended approach, as its static and should be used in the static way, which is to use the Classes
name followed by the static method (or variable). For example,
Vehicle.CheckIfOverSpeedLimit(Integer). Now, theres one little thing youll need to remember,
and thats the fact that you cannot use an instance variable (non-static variable) inside of a static
method. This is because youre trying to ask the blueprint (the Class) to perform some sort of operation
with a variable that may not even exist yet! Remember that instance variables (non-static variables) are
tied to the actual instance (or instantiated version) of their Class. So lets say you had 6 Car objects, 3
Bus Objects and a Motorcycle Object. If you use an instance variable in the static method, how the heck
is the program supposed to know what value to put into the variable? It cant know! A good way to think
of this is that when you declare a static variable on a Class, ALL the Objects that get instantiated from
that Class will share that variable. If youre familiar with programming already, this is like a global
variable, as all instances of that Class will be able to access the same variable
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
86
Constructors
So, what are Constructors? Why are they important? What do they look like in
Code? Lets find out!
So, what are they? A constructor is really the building blocks of an Object. Its the
first thing that Java will execute when a new Object is instantiated. If you were to instantiate a
new Object, Java will go to that Objects constructor code and execute whatever you had placed in that
code. Make sense? It is pretty straightforward.
HumanBeingProgram.java
package com.howtoprogramwithjava.constructors;
public class HumanBeingProgram extends Animal
{
public static void main (String[] args)
{
HumanBeing me = new HumanBeing();
output(me);
HumanBeing you = new HumanBeing ("blue", "female", "Jane Doe");
output(you);
}
private static void output(HumanBeing human)
{
System.out.println(human.getName() + "'s eyes are: " + human.getEyeColor());
System.out.println(human.getName() + " is " + human.getSex());
System.out.println("--------------");
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
87
}
}
HumanBeing.java
package com.howtoprogramwithjava.constructors;
public class HumanBeing extends Animal
{
String name;
public HumanBeing ()
{
super ();
this.name = "John Doe";
}
public HumanBeing (String eyeColor, String sex)
{
super(eyeColor, sex);
}
public HumanBeing (String eyeColor, String sex, String name)
{
super(eyeColor, sex);
this.name = name;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
}
Animal.java
package com.howtoprogramwithjava.constructors;
public abstract class Animal
{
String eyeColor;
String sex;
public Animal ()
{
this.eyeColor = "brown";
this.sex = "male";
}
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
88
As you can see here, a constructor looks like a method, but its missing one key part that defines a
method. The return type! A constructor looks just like a method with no return type, but the constructor
is named after the Class it belongs to. If we even change the case of a constructors name, well get an
error. For example, if we change the Animal Class constructor to say:
public Animal ()
{
this.eyeColor = "brown";
this.sex = "male";
}
Then Java will complain and say the return type is missing because it thinks youre trying to create a
method. Since were not creating a method, were creating a constructor, so it has to be exactly the
same name as the Class that defines it.
You can have multiple constructors in a Java class and this is accomplished by using different parameters
in your constructors.
Now, when you instantiate a Class, Java will execute the constructor that you specify which is
determined by the parameters that you pass in, so if you were to execute this code:
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
89
Java will execute the constructor for Human Being that does not have any parameters/arguments. So
this would execute the following code:
public HumanBeing ()
{
super();
this.name = "John Doe";
}
So, when we run this Java application, what is the output that we should expect to see? Well, heres the
output that this program creates:
John Does eyes are brown
John Doe is male
Does that make sense to you guys? Constructors are fairly straight-forward and this is pretty much as
complicated as I can think to throw at you with the super() keyword and having multiple constructors
with different parameters. Normally you just see constructors with no parameters that just initialize
some variables, but youll see a bunch of different examples of constructors as you go through your Java
training or career as a Java programmer!
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
90
This Keyword
You may have noticed a special this keyword being used, and Im sure you were wondering what it
meant. Well, to understand the this keyword, youll need to make sure you understand the difference
between a Class and an Object. We talked about the difference here.
Ill assume that you do understand the difference between a Class and an Object, so all I need to tell you
is that the this keyword is what an Object uses to refer back to itself. Some other programming
languages use the keyword self, when an Object is referring to itself. Java simply uses this.
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
91
}
}
As you can see, in the first constructor of the HumanBeing Class, we are calling the second constructor
with a default value for the name. We are able to do this by using the this keyword. You see,
constructors are only used when an Object is instantiated/brought to life. The this keyword is only
valid when youre dealing with an Object that has been instantiated, as it doesnt make sense to have a
non-instantiated Class be able to refer to itself right? If the Class hasnt been brought to life, then how
could it be pointing to itself technically it doesnt even exist!
So, since we do have an instance of a HumanBeing object, then it makes sense that it could refer to itself.
So lets say we instantiate a HumanBeing without a name. What would happen?
package com.howtoprogramwithjava.runnable;
import com.howtoprogramwithjava.constructors.HumanBeing;
public class MyProgram
{
public static void main(String[] args)
{
HumanBeing me = new HumanBeing("Brown", "Male");
System.out.println("My name is: " + me.getName());
}
}
Here you see that we just created a HumanBeing object with the variable name me. We instantiated it
using just two input parameters ("Brown", "Male"), this means that the code will flow into the first
constructor, and then invoke its own (second) constructor by passing in a third input parameter of
"John Doe". Neat right? Heres the output from the code:
My name is: John Doe
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
92
Theres a reason why we need to say this.name = name and thats because of scope of variables. You
see, when the code is flowing inside of this setter method, it has a reference to the variable name,
because its being passed in as an input parameter. So now, while the code is inside of this setter
method, if at any point you just type in the variable name name, Java will think you are referencing the
input parameter variable. So you could imagine that Java would be pretty confused if you wrote the
setter method like this:
public void setName(String name)
{
name = name;
}
Java would look at this and say something like This assignment has no effect. And if you think
about it, that makes sense, youre essentially saying Take whats in the name parameter, and put it
back into itself. Thus, it would have no effect.
Java isnt smart enough to realize that what you really want to do is: assign to the instance variable
called name (of the HumanBeing object) the value of the input parameter called name.
Some other programming languages (like C++) use a convention where they prefix the instance variables
with underscores (_). So a setter method using C++ convention would look like this:
public void setName(String name)
{
_name = name;
}
This would essentially negate the necessity of using the this keyword, as theres no longer a name
collision conflict. But I find that convention to be a little annoying when you get into heavy usage of the
instance variables. So thats why I say that the usage of the this keyword inside of setter methods is
mainly for keeping things looking neat and tidy, as you could always just use a different name for your
instance variables or your parameter variables to avoid the name collision. But thats entirely up to you.
I would suggest you lean towards using this, as it is a Java convention.
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
93
Access Modifiers
You have seen Java modifiers in code over and over again, but weve never really talked about them indepth. So what better time than now, right?
AccessModifiersProgram.java
package com.howtoprogramwithjava.runnable;
import com.howtoprogramwithjava.yourneighbourhood.YourHouse;
public class AccessModifiersProgram
{
public static void main (String[] args)
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
94
{
YourHouse yourHouse = new YourHouse();
yourHouse.knockOnDoor();
}
}
YourHouse.java
package com.howtoprogramwithjava.yourneighbourhood;
import com.howtoprogramwithjava.yourparentsneighbourhood.YourParentsHouse;
public class YourHouse extends YourParentsHouse
{
protected void enterYourHouse ()
{
System.out.println("Entering " + getClass().getSimpleName());
}
public void knockOnDoor ()
{
System.out.println("You knock on the door of " + getClass().getSimpleName());
double randomNumber = Math.random();
if (randomNumber >= 0.5)
{
System.out.println("You are greeted at " + getClass().getSimpleName());
enterYourHouse();
}
else
{
System.out.println("No one answers");
goToParentsHouse();
}
}
protected void goToParentsHouse ()
{
System.out.println("You are going to Your Parents House");
if (!this.enterYourParentsHouse())
{
YourNeighborsHouse yourNeighborsHouse = new YourNeighborsHouse();
yourNeighborsHouse.enterYourNeighborsHouse();
}
}
}
YourParentsHouse.java
package com.howtoprogramwithjava.yourparentsneighbourhood;
public class YourParentsHouse
{
protected boolean enterYourParentsHouse ()
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
95
{
if (Math.random() >= 0.5)
{
System.out.println("Entering Your Parents House");
return true;
}
else
{
System.out.println("No one is home at Your Parents House");
return false;
}
}
private void changeThermostat ()
{
System.out.println("Only your parents can change their thermostat!");
}
}
YourNeighboursHouse.java
package com.howtoprogramwithjava.yourneighbourhood;
class YourNeighborsHouse
{
void enterYourNeighborsHouse ()
{
System.out.println("Your neighbor is home, so you enter " +
getClass().getSimpleName());
}
}
Okay, so weve got a lot going on here. One piece of code you may not recognize is
the Math.random() static method. Whats that about? Its a really cool method that will randomly
generate a number between 0.0 and 1.0. Why is that helpful? Well, it means I can say that a certain
event will happen if the number is between 0.0 and 0.49, and if its bigger than 0.49, then do something
else. This is what Im doing in my example code above, so if you were to copy/paste the code into your
own project, youll see that the outcome in the console changes almost every time you run the code!
Neat!
Anyway, let me list out the important things you should observe in this code:
Alright, since YourHouse extends YourParentsHouse this means that YourHouse will have access to all
of the public and protected methods inside YourParentsHouse, as well as all of
the public, protected and private methods within its own code.
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
96
If a method is declared as public, then every Object or method that exists inside of any package in your
program will have access to that method. This is equivalent to you leaving the front door of your house
WIDE OPEN to the public. Youre inviting everyone and anyone in to snoop around
Note: Just because your Object is declared as public doesnt mean that every other Object or method has
access to every aspect of your Object, for we can still modify the access levels of
the methods within your Object.
If your method (within your Object) is declared as protected, this means that the only Objects/methods
that will have access to your method are those that extend your Object (or Objects that your Object
extends). In other words, any Objects in your Objects inheritance chain, will have access to your
Objects protected method.
This is seen when YourHouse calls the protected Boolean enterYourParentsHouse() method. This
method is protected, and it belongs to another Object (YourParentsHouse), but since YourHouse
extends YourParentsHouse, then were all good!
This modifier is not used very often as there arent many practical applications for it. But for the sake of
completion Ill talk about it. This modifier can be observed in the YourNeighborsHouse Object. Look at
the void enterYourNeighborsHouse() method. Youll notice that there is no modifier keyword
specified in front of the method declaration. This means that its a package level modifier. Thats right,
you dont actually put the keyword package into your code to specify that it should be a package level
modifier. Kind of strange, but thats how its implemented.
So when your method (within your Object) is declared as package, this means that only other Objects
that belong to your Objects package can see your method. Youll notice that
both YourHouse and YourNeighborsHouse belong to the package
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
97
method inside
of YourNeighborsHouse, then YourHouse would NOT be able to access this method! This is
because YourNeighborsHouse is NOT inside of the inheritance chain of YourHouse. Neat!
private (methods only)
Finally we arrive at the last modifier. When a method is declared as private, this means that ONLY the
Object that declares the method will have access to it. So this would mean that YourHouse will NOT
have access to the private void changeThermostat() method inside of YourParentsHouse (even
though theyre on the same inheritance chain).
Coding Exercise
So I want you to get a good understanding of what Im talking about when I say that certain Objects
have access to other methods. So I want you to copy/paste my code into your STS IDE program. I want
you to navigate to the AccessModifiersProgram.java file and at the end of the main method, I want
you to type in YourHouse., and youll see the code completion popup appear with a list of methods
that you can access FROM the AccessModifiersProgram.java file. Make note of what methods you
CAN see and what methods you CANNOT see. Now play around with the access modifiers for some of
the methods inside of YourHouse and make some public (be sure to save the code). Now go back any
type in YourHouse. in the main method again, and youll see something different.
Lets summarize
Now that you have an understanding of what Java modifiers are, Ill explain again why theyre
important. If you were to design an entire web application using Java, and you decided to make
everything public, youll quickly see bugs start to emerge as you have other developers work on your
code. Using Java modifiers is a good thing and allows for a truly Object Oriented approach to your
coding. So remember to design your applications with the real world in mind. If an Object has a method
that just wouldnt make sense for any other Object to mess around with, then make it private! This is
good programming practice, as Ive mentioned before, its called encapsulation which sounds cool, so
it must be good then right?
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
98
So, this above code will get the job done, but theres something that can be improved. Can you guess
how?
We should be using a constant! Look how many times we use the double value 3.14159, this value
represents pi (). We should create a constant that will assign the value of to a variable name. Heres
how we do it with some new code:
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
99
14.
15.
16.
17.
18.
19.
20.
21. }
So now, we have a variable named PI declared in the instance variable declaration space. Weve done
this because we need to use this new constant value throughout our AreasAndVolumes class. This
constant will function just like any other instance variable with one main exception weve made the
value final.
You would get a compilation error, and your IDE would tell you that a new value cannot be assigned
because the variable has been declared final.
Does that make sense? A constant is a constant for a reason, it shouldnt ever change! Now, heres a
quick note on conventions in Java. When you name a constant, you should use
UPPER_CASE_LETTERS_WITH_UNDERSCORES_INDICATING_SPACES. Again, its not mandatory to use
upper case letters with underscores to indicate spaces, but its a convention that programmers use and
are familiar with in Java. So why fight it?
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
100
Important Note: You may find examples on the internet of people declaring ALL of their constants in
ONE file and that file is declared as an interface. I DO NOT recommend this approach, as it is a dated
approach to handling constants. Since those times, Java has implemented something called a static
import which will negate the usefulness of storing constants in an interface. So lets see an example
of a public constant being used with a static import shall we?
Images.java file:
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
import java.io.File;
public class Images
{
public static final String THUMBNAILS_DIRECTORY = "C:\\images\\thumbnails";
public void doSomethingWithThumbnails ()
{
File thumbnailFile = new File(THUMBNAILS_DIRECTORY);
// do something with thumbnailFile.....
}
}
AnotherClass.java
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
import java.io.File;
import static com.howtoprogramwithjava.test.Images.THUMBNAILS_DIRECTORY;
public class AnotherClass
{
public void doSomethingElseWithThumbnails ()
{
File thumbnailFile = new File(THUMBNAILS_DIRECTORY);
// do something else with thumbnailFile.....
}
}
One thing to note here is that weve chosen to declare the THUMBNAILS_DIRECTORY in the Images Class,
but we made the constant public this allows us to reference that same value in another Class file,
which is what you see in AnotherClass where we use THUMBNAILS_DIRECTORY when creating a File.
This was possible because of the static import, like so:
import static com.howtoprogramwithjava.test.Images.THUMBNAILS_DIRECTORY;
We are importing the constant from the Images into AnotherClass file so that it can be used just like
we declared it inside of AnotherClass. Neat stuff!
One other small thing to note here, is the use of the double backslashes when listing the actual
thumbnails directory. Youll see that I declared the constant with this
value: "C:\\images\\thumbnails" this is a bit confusing, because why in the heck am I using two
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
101
backslashes (\\) between directories? Well, this is because in Java, the backslash (\) is a special character
known as an escape character. Its used when you want to insert a particular character somewhere
without having that character interfere with your code (not a very good explanation, but heres a great
example):
String aSentence = "Here's a great quote \"Behind every great man, is a woman rolling
her eyes - Jim Carrey\".";
Notice how I wanted to put the quote () symbols inside of my String variable, but I wouldnt normally
be able to do this, because the quote () symbol is used to denote the start and end of a String. Well, I
get around this by using the backslash (\) escape character.
So, in summary, if you want to actually have Java output a backslash (\) character, you need to escape
the escape character (yes I know, it sounds strange). This is done by using two backslashes (\\). In short:
Input: \\
Output: \
Input: \\\\
Output: \\
Make sense?
Good, great, grand!
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
102
Chapter 5
Fundamental Concepts
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
103
Exceptions
What are Exceptions in Java?
What do they look like in Java code?
When should I choose to use them?
I know at this point you must be yearning to create a fully functional and practical Java program by now.
Without further delay, heres the content!
FileIO.java
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
104
package com.howtoprogramwithjava.fileio;
import
import
import
import
java.io.BufferedReader;
java.io.FileNotFoundException;
java.io.FileReader;
java.io.IOException;
Wow! So thats a lot of code. Now, if you were to copy/paste this code into a project that you create
(remember to name the files appropriately, and place them into the correct packages), youll notice that
you get the following output when you try to run the program:
There was an exception! The file was not found!
This is because we specified a filename in the constructor of our FileIO class and you likely dont have
this file on your computer, so when the code tried to find it and it couldnt, it threw an exception!
Now lets try adding this file to your computer, so please create an aFile.txt file on your C:\ drive and
put the following content in it:
This is line 1 of the file
This is line 2
Once youve done this correctly and you re-run this Java program, you should see the following output:
Reading line: This is line 1 of the file
Reading line: This is line 2
If you are able to see that in your console, then youve done it!
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
105
This is called a try/catch block. Its designed so that if you put code between the curly braces {} of
the try block, then any exceptions that occur will make the code flow jump into the catch block. If no
exceptions occur, then the code will flow through the entire try block and skip the catch block of code.
This concept of code flow is critical to understand, if you want to grasp what exception handling is in
Java.
package com.howtoprogramwithjava.runnable;
import java.io.IOException;
import com.howtoprogramwithjava.fileio.FileIO;
public class MyProgram
{
public static void main(String[] args) throws IOException
throws declaration here
{
FileIO fileIO = new FileIO("C:\\aFile.txt");
}
}
// we need to add a
package com.howtoprogramwithjava.fileio;
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
106
import
import
import
import
java.io.BufferedReader;
java.io.FileNotFoundException;
java.io.FileReader;
java.io.IOException;
What you should notice with the modified code above is that we added throw e; inside of the catch
blocks. So, lets say that we get a FileNotFoundException thrown inside of our try block of code. This
will cause the code to flow into the first catch block and this is because weve specified that the
first catch block is supposed to handle FileNotFoundExceptions.
Note: Youll also notice that we assigned the FileNotFoundException to the variable name e. This is just
a coding convention in Java, so you can name your exceptions whatever you like!
Anyway, like I said, the code will flow into the first catch block of code, it will then output our console
message stating the file was not found; then it will re-throw the FileNotFoundException. Since there is
no additional catch block to handle the re-thrown exception, we will get a nasty console error and it will
look like this:
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
107
at com.howtoprogramwithjava.runnable.MyProgram.main(MyProgram.java:11)
This output is called a stack trace. It is Javas way to let the programmer know that theres been an
exception that was not handled, and thus the execution is stopped. This output will help the
programmer figure out where the exception occurred, thus giving a clue as to how it can be
fixed/addressed.
Because Java has included those throws clauses, we are now forced to handle those exceptions. If
we do not use a try/catch block (or specify a throws clause on our methods that use this I/O code),
well get an error in our IDE telling us we need to do something! This error would like something like
this:
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
108
Now there are other times when its not mandatory that you use exception handling in Java, but it may
be beneficial. Examples of this are if you are designing a software application that needs to follow
certain business rules. In order to enforce those business rules, you could create your OWN exception
class (by creating a new Class and extending the Exception Class) and throw THAT exception if a certain
condition is met. Lets say, for instance, you are creating a webpage that has a user login feature. When
the user tries to login with a password that is incorrect, perhaps you would like to throw an Invalid User
Login Exception? The design of the system will be up to you or the architect of the system, but this is an
option that Ive seen used before.
Bonus material
Theres one other aspect to the try/catch block that I didnt mention, and thats the finally block. It
looks like this:
try
{
// insert code to execute here that may throw an exception
}
catch (Exception e)
{
// and exception WAS thrown, do something about it here!
}
finally
{
// When the code flows out of the try or catch blocks, it
// will come here and execute everything in the finally block!
}
What!? Seriously, theres another aspect to this exception stuff! I know, but its the last crucial concept
youll need to understand before you can say you understand exceptions in Java. As the code comments
state, the final block will be executed after the code has either finished executing in the try block or in
the catch block.
So, whats the purpose of the finally block? Well, normally its used to clean up after you. An
example of this is trying to have your code talk to a database (like MySQL/Oracle/MS SQL Server).
Talking to a database is no simple task and it involves steps. The first step is to open a connection to
the database (very similar to opening a file like we did in this example). Well, what if something goes
wrong after weve opened the connection to the database? We need to make sure we close the
connection to the database or otherwise well run into problems (which I wont example here as its
currently not in our scope of learning). The finally block allows us to do this closing part. Since we
can be confident that the code will ALWAYS flow into the finally block after its gone through either the
try or the catch, then we can throw in our code to close the database connection in
the finally block. Does that make sense?
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
109
Note: For the sake of being complete, Ill mention that the finally block doesnt necessarily execute
immediately after the code flows past the try/catch block, but it will eventually execute the code in
the finally block so I wouldnt put any code in the finally block that has any dependency on
time/point of execution.
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
110
String Manipulation
With this How to Program with Java, we will talk about more advanced aspects of String manipulation.
With every programming project I have worked on in my career, Ive needed to use different strategies
related to manipulating Strings. So this topic is critical to learning Java and being a solid programmer (in
any language really).
Now, lets say we want to isolate two parts of each of these websites, the root URL and the pages
within. So, for example, we want to break each one into two parts like so:
1.
2.
3.
4.
"howtoprogramwithjava.com", "reviews"
"howtoprogramwithjava.com", "programming-101-the-5-basic-concepts-of-any-programminglanguage"
"howtoprogramwithjava.com" ,"consulting", "web-application-development"
"google.com"
How would we go about accomplishing this? Well, we would need to use a method called split().
What this method does is allow you to separate one String into an Array of Strings based on a
character of your choosing. In our examples, youll notice that the forward slash (/) is used to separate
the base URL with the individual pages. So this forward slash (/) character would be perfect for splitting
up our Strings. So, what would that look like?
for (String website: websites) // iterate through each website in the ArrayList
{
System.out.println("website: " + website);
String[] stringArray = website.split("//");
System.out.println("Splitting String by // = " + Arrays.toString(stringArray));
System.out.println("Splitting String further by / ->" +
Arrays.toString(stringArray[1].split("/")));
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
111
This code will split the Strings twice. Once with the double forward slash (//) to isolate the http://
section from the rest. Then it will split the resulting String array once again by a single forward slash (/),
which will separate all the individual sections of the URL. The output will look like this:
The split() method is very powerful and it allows you to use something called Regex to identify the
parts of the String to split up. Now, Regex is a fairly advanced topic, but if you feel like learning more
about it right now you can check out this Introduction to Regex.
Searching Strings
Perhaps youll find yourself in a scenario where youll need to find out if a particular String exists
INSIDE of another String. This will require you to search through your String. Lets say we have the
sentence The quick brown Fox jumps over the lazy Dog, and we want to see if that sentence has the
word Fox in it. Well, then you would use the contains() method. Example:
String sentence = "The quick brown Fox jumps over the lazy Dog.";
boolean sentenceContainsFox = sentence.contains("Fox");
System.out.println("Does the sentence contain 'Fox': " + sentenceContainsFox);
One interesting thing to note though is if we made one minor change to the code. What if we change
the contains method to look for the String fox (with a lowercase F). What do you think Java will
output?
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
112
String sentence = "The quick brown Fox jumps over the lazy Dog.";
Boolean sentenceContainsFox = sentence.contains("fox");
System.out.println("Does the sentence contain 'fox': " + sentenceContainsFox);
Very interesting! This happens because Java is case sensitive when it deals with Strings. This means
that uppercase and lowercase are not treated as equal, just like when you use variables names when
coding!
The common way to ignore the case of your String is to send the whole String to lowercase, like so:
String sentence = "The quick brown Fox jumps over the lazy Dog.";
sentence = sentence.toLowerCase();
Boolean sentenceContainsFox = sentence.contains("fox");
System.out.println("Does the sentence contain 'fox': " + sentenceContainsFox);
Matching Strings
Now sometimes we dont need to worry about converting the entire String into lowercase to do
checks. If you are checking to see if a particular String is equivalent to another String you could use
the following methods:
equals()
This allows you to check if two Strings are exactly equal.
String s1 = "fox";
String s2 = "Fox";
s1.equals(s2); // will return false
equalsIgnoreCase()
This allows you to check if two Strings are equal to each other while ignoring the case sensitivity.
String s1 = "fox";
String s2 = "Fox";
s1.equalsIgnoreCase(s2); // will return true
An example of what the equals() method comes in handy, is when you need to validate a users
password when they login. You need to ensure that the case matches exactly with the password.
Whereas with the username, you dont care as much with respect to case, so you would use
the equalsIgnoreCase() when validating their username.
Note: Just remember never to compare two Strings using the == operator, as this compares the
memory address of the actual String instead of comparing the actual contents of the String.
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
113
Substring
Another useful method is the substring() method. This allows you to deconstruct a piece of
a String based on an index. What the heck does that mean!? Heres an example to make things clearer:
String aString = "This is a sentence that will be deconstructed with the substring
method";
String aNewString = null;
// substring takes two parameters, a beginning index and an ending index
// it will construct a new String based on these indices
aNewString = aString.substring(8, 45);
System.out.println(aNewString);
You see what happened there? The aNewString String is made up of the 8th character all the way to
the 45th character of the old String (aString).
Try it Yourself
Open your STS IDE and create a String. Then type in the variable name that you assigned to
your String and hit DOT (.), youll see the list of methods that you can call popup in the auto-complete
popup box. In this list youll see things like startsWith() and replace(). Read up on what they do and
test them out for yourself, its the best way to learn what you can do with String manipulation.
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
114
Casting
This is a quick Java tutorial about casting variables. This topic isnt very interesting,
but its definitely something that you should be familiar with if you want to be a
programmer (in any language).
You see what weve done here? Since the type Object is a very broad type for a variable, we are down
casting the variable to be a String type. Now, the question is, is this legal? Well, you can see that the
value stored in the aSentenceObject is just a plain old String, so this cast is perfectly legal. Lets look at
the reverse scenario, an up cast:
Here we are taking a variable with a more specific type ( String) and casting it to a variable type thats
more generic (Object). This is also legal, and really, it is always legal to up cast.
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
115
This Map is a candidate for casting, and heres how we would deal with the casting:
String name = (String)model.get("name");
String email = (String)model.get("email");
Date birthday = (Date)model.get("birthday");
You see how we did three separate casts there? Since all the objects stored in the map are of type Object,
this means that they are very generic and could most likely be down casted. Since we know that the
name is a String, and the email is a String, and the birthday is a Date, we can do these three down
casts safely.
This would then give us more flexibility with those three variables, because now we have an actual
birthday Date object, so we have access to methods like getTime() instead of just the
default Object methods.
This is quite a valuable approach to storing Objects in a Map, because if we had created the Map with
something more specific than Object as the value, then we would be constrained to only
storing Objects of that specific type (and its sub-classes).
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
116
Summary
To sum up, casting is a very useful mechanism that allows you to write more generic code that will allow
you to handle many coding situations. But this mechanism can introduce some risk if youre not careful
with what you will be casting.
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
117
Loops
I think its time for us to have an in-depth conversation about Java loops. So, this Java tutorial will be
structured around these useful control structures. This topic is yet another one of those that I would
classify as fundamental when trying to learn how to program with Java.
Ive touched on this topic briefly back in my Java tutorial about control structures, so now its time to dig
deeper!
For Loops
While Loops
Do...While Loops
For Loops
In my opinion, the For Loop is the most common of all three types of loops. It is structured around a
finite set of repetitions of code. So if you have a particular block of code that you would want to have
run over and over again a specific number of times the For Loop is your friend. A common use of this
loop is when you have a List of items that you need to iterate over for processing. Lets say you have
a List of Contacts in your address book, and you want to send an email to all of them. You could
iterate over your List of Contacts and extract each e-mail address, like so:
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
118
Contact("[email protected]"));
Contact("[email protected]"));
Contact("[email protected]"));
Contact("[email protected]"));
Contact("[email protected]"));
}
private static class Contact
{
private String emailAddress;
public String getEmailAddress() {
return emailAddress;
}
public Contact (String email)
{
this.emailAddress = email;
}
}
}
If you were to run this code, you would see the following output:
[email protected], [email protected], [email protected], [email protected], [email protected]
As you can see here, we now have a List of (fake) email addresses that we could copy/paste into an
email program in the To: field, fill in a subject/body and fire off an email. A similar approach is used in
the real world to parse a List of email addresses that are stored in a database. All of this made easy by
using the For Loop!
While Loop
Another looping strategy is known as the While Loop. The While Loop is good when you dont want to
repeat your code a specific number of times, rather, you want to keep looping through your code until
a certain condition is met (or rather, keep looping while a certain condition is true).
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
119
So you see here that weve used a while loop, and although its not entirely apparent, we will be
iterating over this loop until the end of the file that weve read in (with the BufferedReader).
For simplicity sake, let me show you a more basic version of the while loop now you wouldnt
normally use this particular implementation of the while loop, as it would just keep running and never
end but this is just an example:
while (true)
{
// do something
}
So as you can see above, the structure of the while loop is pretty simple. Theres the
keyword while followed by a condition inside round braces (/*condition*/). The code flow will be as
follows:
1.
2.
3.
Check the while loop condition, if false, dont execute any code inside while block
if condition is true, execute code inside while block
repeat step 1
So, given this workflow, can you see how the second While Loop example will run forever? If you
happen to try and test this out, youll see that your computer will start to slow down and perhaps youll
hear the CPU fan fire up and make some noise! Dont worry, you can just click the red stop button in
your console window to stop your infinite loop or just close your Spring Source Tool Suite (STS). The
key thing to note is that using While Loops is slightly dangerous for your code, as you can get stuck in an
infinite loop if you dont give the right condition statement. I actually brought an entire QA environment
to its knees once when I was a junior programmer, so dont worry if you do the same, everyone needs to
learn somehow right?
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
120
1.
2.
3.
You see the difference? The Do..While Loop will always execute the code in your block at least once.
Whereas, the while loop could skip the whole block of code if the condition is false the first time
around. So like I mentioned already, the Do..While Loop isnt used too often, and Im sure there are
situations where it would make sense to use one, but I havent hit that situation just yet in my coding
adventures
Bonus Content
Now that youve seen the different types of loops that exist in Java, how about we get a little fancy with
our code? Lets say we have a requirement that says you need to write some code that will tell us if a
particular Contacts email address exists in a List of Contacts. Sure we could write a For Loop or a
While Loop that would iterate through a list to find an email address, but wouldnt it be silly if we found
the particular email address we were looking for, and then just kept on looking through the rest of
the List? What happens if the List of email addresses had a million Contacts, and we had our answer
on the 2nd Contact! That would be quite the waste of time right? Right! So heres a neat trick:
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
121
So you see in the code above that if weve found the email address, we break out of the loop and return
the result of our Boolean variable. So now, if we find the email address were looking for the second
time around the For Loop, we dont waste any time! Neat!
But wait, theres more!
Summary
Great! Now youve been exposed to three types of loops (although, only the For Loop and While Loop
are commonly used). You also have an idea of which one to use in certain situations For Loops should
be used when you know exactly how many iterations youll need, and While Loops should be used when
you dont know how many iterations youll need. And finally, you know how to optimize your loops with
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
122
the break and continue keywords! All thats left is for you to play around with them yourself, so by all
means, go nuts!
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
123
Java UI
One aspect that I havent touched on yet is Java UI (User Interface). I left this topic out of all the
previous tutorials on purpose, because I think its one of Javas weak points.
I realize these two reasons arent the most compelling reasons for disliking all things Java UI, but it was
compelling enough for me and every one of my University computer science friends to use something
else! Plus when it comes down to it, most applications you use on a daily basis are NOT using Java UI
thats because theyre either web applications (like Facebook or Kijiji) or just built on some other
products (like Visual Studio).
If you would like to see a sample of what this Java UI is all about, heres a tutorial that covers one of the
methods for creating a UI. This framework is known as Swing:
http://cs.nyu.edu/~yap/classes/visual/03s/lect/l7/
Another UI tool is called AWT or Abstract Window Toolkit and Sun has a pretty comprehensive tutorial:
http://java.sun.com/developer/onlineTraining/awt/contents.html
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
124
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
125
Operators
So far weve only looked at some fairly simple control structure conditions, by this I mean weve seen
things like:
if (age < 13)
{
System.out.println("You are a child.");
}
else if (age < 20)
{
System.out.println("You are a teenager.");
}
else
{
System.out.println("You are an adult.");
}
This works well if you dont have a very complicated system to work with, but if youre building a real
application, then chances are youll need to make use of more advanced Java Operators!
Description
==
Equal to
!=
Not equal to
>
Greater than
>=
<
Less than
<=
These should seem fairly straight forward to you, so Ill skip right into the conditional Java operator
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
126
Conditional Operators
Operator
Description
&&
Conditional-AND
||
Conditional-OR
?:
Now these conditional operators are more interesting, as they allow you to put many operators
together heres an example of how theyd be used:
if ((age > 0 && age < 13) || (age > 19))
{
System.out.println("You are not a teenager");
}
else
{
System.out.println("You are a teenager");
}
Here I used three different relational operators (less than and greater than) and sprinkled in two
conditional operators (&& and ||) all in one control structure (if statement). Now heres a curve ball,
you can also throw in the use of the NOT (!) operator. This will reverse the Boolean logic of any
statement. If we were to apply a NOT to our example above, we would have to change the System.out
statements like so:
You see how I added that NOT (!) symbol in the IF statement? I added yet another bracket that
surrounds the ENTIRE if condition. The way you would read this is to determine what would happen
without the NOT logic first, THEN just reverse your output. So if the age variable was 14, I would say, Is
14 > 0 and is 14 < 13" , "OR is 14 > 19? In this case I would say NO, none of these statements are true,
BUT we then need to switch the outcome because we have a NOT (!) operator that wraps our entire
logic, so our NO turns into a YES (or true), so the output would be You are a teenager which is true, if
youre 14 then youre a teenager.
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
127
Be careful when using the NOT (!) operator, as it can sometimes make figuring out the logic quite
complicated. Heres a good example of over-use of the NOT (!) operator to over complicate
an if statement:
Believe it or not, this logic is still valid (I know, because I tested it!). But its so confusing to read, so
please, for the sake of all developers out there, avoid using the NOT operator if you can.
Now, there was one more conditional operator in that chart above that I havent talked about yet, and
thats the ternary operator!
This code can be re-written using the ternary operator like so:
Boolean isTeenager = ((age > 0 && age < 13) || (age > 19)) ? true: false;
Now this looks pretty busy, so let me show you a basic version of what this ternary operator looks like:
Boolean isAnAdult = (age > 19) ? true : false;
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
128
So all this ternary operator does is evaluate the condition before the question mark, and if the condition
evaluates to true then it will assign the value to the left of the colon to our Boolean variable. If the
condition evaluates to false, then itll assign the value to the right of the colon to our Boolean variable.
So in our more basic version, we evaluate the condition before the question mark (age > 19). So lets
say age = 20. It would say, is 20 > 19?, yes, then assign the value on the left of the colon to our
variable. So whats to the left of the colon? The Boolean value true, so this would be assigned to
our isAnAdult variable. In the reverse case, if age = 13, then we evaluate the condition is 13 >
19? nope, so then we assign the value to the right of the colon, which in this case is false.
Again, this is just a shortcut way to write code, as the isAnAdult code could just be written as:
Boolean isAnAdult;
if (age > 19)
{
isAnAdult = true;
}
else
{
isAnAdult = false;
}
So, 9 lines of code versus 1 line of code. Some would say that using ternary is better because you write
less code, but, I would say that you should only use the ternary operator if your code is easily readable.
If it isnt, then I would favor MORE lines of code to be clearer.
Arithmetic Operators
Operator
Description
&&
Conditional-AND
Subtraction operator
Multiplication operator
Division operator
Remainder operator
These arithmetic Java operators are also pretty straight-forward. Youve seen that the + operator can be
used to add two numbers together OR to concatenate two Strings together (in the Strings Java
tutorial). Subtraction, division and multiplication are all self-explanatory; these are used for
mathematical operations (just like using a calculator!). But, one thing you havent seen is the remainder
operator. So whats that all about?
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
129
Remainder Operator
This is used to determine what the remainder is in a division operation. For example, whats 15 divided
by 7? Well, its 2 with a remainder of 1. Whats 7 divided by 8? Its 0 with a remainder of 7! This is what
the remainder operator (%) tells you, just the remainder of a division operation. So what does it look like
when used in code?
Integer remainder = 833 % 28;
System.out.println("remainder is: " + remainder);
This would output 21. This is pretty easy right? 833 / 28 = 29 with a remainder of 21. So
the remainder variable gets the value of 21, and we output it!
Now the question is whats a real world scenario for the use of the remainder operator? Well, Ive really
only seen it used for displaying rows of a report in a nice way. What I mean by that is youll have a
report printing on the screen and each row of the report will alternate their background colors (between
white and grey). This is accomplished by using the remainder operator, sort of like this:
Integer numberOfRows = report.getNumberOfRows();
for (int i=0; i<numberOfRows; i++)
{
String bgColor = (i % 2 == 0) ? "white" : "grey";
// then we would use this bgColor for the reports output
}
So in this example we used the remainder operator inside a ternary operator. What will happen here is
that as we go through each of the rows, the variable i will increment. Heres what each iteration will
look like:
i (i % 2 == 0)? bgColor
0 true
white
1 false
grey
2 true
white
3 false
grey
4 true
white
So you see what happens as a result? You will get alternating white and grey background colors, which
makes reading reports much easier, as it lines up each of the rows for you
Kind of nifty right? Okay
not really, but still, its a great example for the use of the remainder operator!
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
130
Unary Operators
Operator
Description
++
--
Youve seen me use these before in my for loops. This is yet another shortcut way of writing code, and
this is best explained with a code example:
int i = 0;
i = i + 1;
// what does i equal
// well since i = 0,
// so now i equals 1
i = i + 1;
// what does i equal
// well now, since i
// so now i equals 2
i++;
// what does i equal
// well now, since i
// so now i equals 3
now?
it's saying i = 0 + 1
now?
= 1, it's saying i = 1 + 1
now?
= 2, it's saying i = 2 + 1
int i = 0;
i += 238;
// now i = 238, because this is the same thing as saying
i = i + 238;
So, all of these shortcuts are the same for subtraction, division and multiplication as they are for
addition (with the exception of ** and //. ** doesnt mean anything, and // is used to write in
comments as youve seen already. But i *= 10 is valid, it just means i = i * 10. Or i /= 15 which is
the same as i = i / 15. You get the idea.
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
131
These shortcuts are ones that I would always recommend using, as they dont make the code less
readable in my opinion. Ive never had a problem understanding what anyone meant when they were
used.
Summary
Wow, thats a lot of operators and shortcuts! These Java operators are (for the most part) very
commonly used in the Java programming language and I think youll become very comfortable with
them as you program with Java. Its also a very universal topic, so youll be able to carry this knowledge
around in other programming languages if you choose to learn another one. So its definitely worth
learning
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
132
Enums
Enums is a neat topic that applies to most programming languages (not just Java)!
What is an Enum?
Its short for Enumerated Type, which just means that Java allows you to define your own special
variable type. This becomes helpful when you would like to express something in more human readable
terms. For example, lets say you would like to make an application that allows you to play a card game,
like poker. Wouldnt it be nice if you could assign numeric values to all of the cards? Like so:
2 -> 10 = 2 -> 10
Jack = 11
Queen = 12
King = 13
Ace = 14
Well, enums make this a piece of cake. Lets create a Card enum!
package com.howtoprogramwithjava.business;
public enum CardValue
{
TWO(2),
THREE(3),
FOUR(4),
FIVE(5),
SIX(6),
SEVEN(7),
EIGHT(8),
NINE(9),
TEN(10),
JACK(11),
QUEEN(12),
KING(13),
ACE(14);
private int cardValue;
private CardValue (int value)
{
this.cardValue = value;
}
public int getCardValue() {
return cardValue;
}
}
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
133
Voila! Weve now outlined what a CardValue enum could look like, so now lets define what the
Cards Suit could look like:
package com.howtoprogramwithjava.business;
public enum Suit
{
HEARTS,
SPADES,
CLUBS,
DIAMONDS;
}
Alrighty, so we have now defined what a Suit and CardValue looks like as Enums in Java. Things that
you should note are that Enums need to have a package or private scoped constructor, if you try to
specify anything else, Java will fail the compilation of your code. You can also get away with not defining
a constructor at all (like I did with the Suit Enum). This is because you arent meant to instantiate
Enums, youre supposed to reference the values in a static way, as they are meant to be constant values.
If you dont quite understand what I mean when I say the values should be referred to in a static way,
just hang in there, for Ill have an example soon. First, lets put the CardValue and Suit together into
a Card object to pull everything together.
package com.howtoprogramwithjava.business;
public class Card
{
private Suit suit;
private CardValue cardValue;
public Card (CardValue cardValue, Suit suit)
{
this.cardValue = cardValue;
this.suit = suit;
}
public Suit getSuit()
{
return suit;
}
public void setSuit(Suit suit)
{
this.suit = suit;
}
public CardValue getCardValue()
{
return cardValue;
}
public void setCardValue(CardValue cardValue)
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
134
{
this.cardValue = cardValue;
}
}
Okay nothing new going on in that code and its a standard Object that defines some private
(encapsulated) variables that are made publicly visible via getter and setter methods, but you can see
how this makes sense right? A Card is simply made up of a CardValue and a Suit! Just like real life!
Dont you just love Object Oriented Programming?
Okay, so lets talk a bit more about what I meant when I said that the Enums have to have a package or
private level constructor. I said that this is because you shouldnt be able to instantiate the class, for the
contained values should be referenced in a static fashion. Lets see what I mean with an example:
package com.howtoprogramwithjava.business;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
public class Deck
{
private ArrayList<Card> deck;
public Deck ()
{
this.deck = new ArrayList<Card>();
for (int i=0; i<13; i++)
{
CardValue value = CardValue.values()[i];
for (int j=0; j<4; j++)
{
Card card = new Card(value, Suit.values()[j]);
this.deck.add(card);
}
}
Collections.shuffle(deck);
Iterator<Card> cardIterator = deck.iterator();
while (cardIterator.hasNext())
{
Card aCard = cardIterator.next();
System.out.println(aCard.getCardValue() + " of " + aCard.getSuit());
}
}
}
Wow! There is a lot going on here. The basic concept of this code is that we want to properly represent
a Deck of Cards. So, we all know that there are 52 Cards in a Deck right? This means that we should
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
135
iterate through all of our CardValues and Suits in order to match them up with each other. We do this
by referring to the Enums in a static way like so:
CardValue.values();
// and
Suit.values();
If you hover your mouse over the values() part of the code in your IDE, youll see that when you invoke
the values() method, youll get an Array that represents every value inside the Enum. So if I were to
invoke Suit.values(), I would get an array of values back like so:
[HEARTS, SPADES, CLUBS, DIAMONDS]
It is in that exact order. Its important to mention that its in that exact order because thats the order in
which they are defined in the Suit object. Java is very particular about the way it does things. It doesnt
like to give you back an Array in any random order.
So, when you keep that in mind, it helps to understand what Im doing in this Deck code. As you scan
through the Deck code youll notice that I have two for loops and one is nested inside the other. The
outer for loop is running from 0 to 12 and the inner loop is running from 0 to 3. So, this means that well
ensure that we get every single combination of CardValue and Suit.
Note: I said 0 to 12 even though the for loop says i=0; i<13; i++, but I'll leave it to you to think things
through and try to understand why this is.
So, at this point we'll just have a Deck of Cards that are neatly in order. So, like any good Deck of cards,
we want to mix them up so they're random right? Well, lucky for us, we used an ArrayList Collection to
represent our Deck of Cards, and inside the Collection class, we have a helper method called shuffle.
This method is used to randomize ANY List Collection. Neat
So, after we've shuffled our Deck let's just output what the Deck or Cards looks like!
THREE of SPADES
FIVE of SPADES
SIX of DIAMONDS
QUEEN of SPADES
FIVE of DIAMONDS
THREE of DIAMONDS
SEVEN of CLUBS
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
136
SIX of SPADES
QUEEN of HEARTS
KING of CLUBS
KING of SPADES
SEVEN of SPADES
KING of HEARTS
THREE of HEARTS
JACK of CLUBS
FOUR of DIAMONDS
TEN of DIAMONDS
TWO of CLUBS
EIGHT of SPADES
FOUR of CLUBS
EIGHT of CLUBS
TEN of SPADES
JACK of SPADES
THREE of CLUBS
NINE of CLUBS
SEVEN of HEARTS
NINE of DIAMONDS
ACE of CLUBS
SEVEN of DIAMONDS
FIVE of CLUBS
TWO of SPADES
TWO of HEARTS
KING of DIAMONDS
EIGHT of DIAMONDS
NINE of SPADES
QUEEN of DIAMONDS
EIGHT of HEARTS
JACK of DIAMONDS
TEN of HEARTS
JACK of HEARTS
TEN of CLUBS
ACE of SPADES
FIVE of HEARTS
ACE of DIAMONDS
TWO of DIAMONDS
FOUR of SPADES
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
137
SIX of CLUBS
SIX of HEARTS
FOUR of HEARTS
NINE of HEARTS
ACE of HEARTS
QUEEN of CLUBS
And there you go, a nice neat shuffled Deck. Don't you just love Object Oriented programming? You see
how I was able to explain a real world scenario of a Deck of Cards by using the names of the actual types
in Java? It makes your code so much more readable and understandable.
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
138
For your viewing pleasure, heres the video walk-through for assignment 2 as well:
Click Here for Video
This is one of my favorite types of assignments, its an algorithm assignment. This type of assignment is
design to test your skills at creating an algorithm that will solve the presented problem. Remember that
there are MANY ways to solve this problem; your goal should be to create code that is as efficient as
possible. Your task for Java practice assignment #4 is to code an anagram solver. First of all, well define
the term anagram for this assignment:
An anagram is considered to be a pair of words that are made up of the exact same letters. Think of it
like taking one word, then just scrambling the letters around until you can spell another word. For the
purposes of this assignment well only be dealing with single word anagrams, as there are certainly
anagrams that can be formed by multiple words (but lets not worry about those ones). Here are some
examples of valid anagrams:
care -> race
tool -> loot
cloud -> could
An example of words that a NOT anagrams:
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
139
tool -> toll (doesnt have the exact same number of letters)
cloud -> clouds (one word is longer than the other)
So, your task will be to create a method that will return true or false (anagram or NOT an anagram)
based on the two Strings that will be passed in. Be sure to follow the instructions included in the
assignment files!
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
140
Chapter 6
Advanced Topics
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
141
Java Multithreading
What is it?
In Java, a Thread is essentially the Object that represents one piece of work. When you start your
application and it starts to run, Java has spawned (created) a Thread and this Thread is what will carry
out the work that your application is meant to do. Whats interesting to note, is that one Thread can
only do one particular task at a time. So that would mean its a bit of a bottleneck if your entire
application just works off of one Thread right? Right!
Java multithreading allows you to do multiple tasks at the same time. This is possible because
modern day computers have multiple CPUs (CPUs are the brain of your computer, and it has a bunch!).
One CPU can work on one Thread at a time (unless your CPUs have hyper-threading, in which case it can
handle two at a time). So this means that if your computer has 4 CPUs with hyper-threading
technologies, your code could potentially handle 8 Threads at the same time. Neat!
The implications of this are that you can take your code and make it perform MUCH better by
introducing the use of multithreading. That is of course, if your program would benefit from the use of
multithreading, some applications are fairly simple and things would just get over-complicated by
adding in Thread logic.
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
142
So you can see here that there are two different Threads running here. Now in this example, theres
really no need to be using two different Threads because the flow of this code is linear. The trick here
would be to introduce the need for multiple Workers to be running at the same time, and to have a lot
of work for these Workers to carry out. We can easily create lots of Workers, Ill just use a for loop to
create a handful. But how could we simulate lots of work? Well, we could use
the Thread.sleep() method; this method pauses the thread for a custom defined period of time.
When we pause a Thread, this would simulate that Thread being busy doing some sort of actual work!
Sweet, so lets see what that would look like:
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class Worker implements Runnable
{
public boolean running = false;
public Worker ()
{
Thread thread = new Thread(this);
thread.start();
}
public static void main (String[] args) throws InterruptedException
{
List<worker> workers = new ArrayList<worker>();
System.out.println("This is currently running on the main thread, " +
"the id is: " + Thread.currentThread().getId());
Date start = new Date();
// start 5 workers
for (int i=0; i<5; i++)
{
workers.add(new Worker());
}
// We must force the main thread to wait for all the workers
// to finish their work before we check to see how long it
// took to complete
for (Worker worker : workers)
{
while (worker.running)
{
Thread.sleep(100);
}
}
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
143
40.
41.
Date end = new Date();
42.
43.
long difference = end.getTime() - start.getTime();
44.
45.
System.out.println ("This whole process took: " + difference/1000 + " seconds.");
46.
}
47.
48.
@Override
49.
public void run()
50.
{
51.
this.running = true;
52.
System.out.println("This is currently running on a separate thread, " +
53.
"the id is: " + Thread.currentThread().getId());
54.
55.
try
56.
{
57.
// this will pause this spawned thread for 5 seconds
58.
// (5000 is the number of milliseconds to pause)
59.
// Also, the Thread.sleep() method throws an InterruptedException
60.
// so we must "handle" this possible exception, that's why I've
61.
// wrapped the sleep() method with a try/catch block
62.
Thread.sleep(5000);
63.
}
64.
catch (InterruptedException e)
65.
{
66.
// As user Bernd points out in the comments section below, you should
67.
// never swallow an InterruptedException.
68.
Thread.currentThread().interrupt();
69.
}
70.
this.running = false;
71.
}
72. }
73. </worker></worker>
So what's the output of the code above? Here's what it says on my computer:
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
144
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
145
In software engineering, the singleton pattern is a design pattern that restricts the instantiation
of a class to one object. This is useful when exactly one object is needed to coordinate actions
across the system. The concept is sometimes generalized to systems that operate more efficiently
when only one object exists, or that restrict the instantiation to a certain number of objects. The
term comes from the mathematical concept of a singleton.
Not bad, a decent definition. If I were to put it in terms of the Highlander film, I would say There can be
only one! So this means that literally only one instantiation of an Object will be allowed, you simply
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
146
should not be able to have two separate instances in your application. Okay, fair enough, seems like a
simple enough concept but, how is that useful to us?
Well the most popular use of the singleton design pattern are for Objects that deal with things like
database connections or controllers in the MVC pattern. I havent really talked much about databases or
MVC, but the reason these things use the singleton design pattern is because it would be a waste of
system resources to create more than one instance of those Objects. When youre dealing with an
Object that talks to a database, its fairly expensive to create a connection to a database. When the
object gets created, one of the first things it will do is create a connection to the database, but once the
connection is open you can use it over and over again. So since theres this cost of creating the Object,
wouldnt it be nice if we had some way of ensuring we would only create it once? Well yes it would be
nice, so lets make it a singleton!
Show me an example!
Okay, lets take a look at what a singleton would look like in Java:
1. public class SingletonObject
2. {
3.
private static SingletonObject INSTANCE;
4.
5.
private SingletonObject()
6.
{
7.
}
8.
9.
public static SingletonObject getInstance()
10.
{
11.
if (INSTANCE == null)
12.
INSTANCE = new SingletonObject();
13.
return INSTANCE;
14.
}
15. }
So, there are a few important elements to this code. The first element is that we have declared the
constructor as private. If this is your first time seeing a singleton, you likely glazed over that fact (I
know I did the first time seeing it). But this is a very important piece of code. The fact that were making
the constructor private, means that we dont want any other code being able to access the constructor
this means of course, that no one will be able to instantiate this Object (they would get a compilation
error). That is after-all, our goal here, to only ever have at most one instance. So when you take away
access to the constructor, you take away the ability for a random rogue coder to accidentally instantiate
the object.
The second important thing to note is that we have a static reference to an INSTANCE variable. This is
how we will be able to actually work with the Object. If you think about it, how else would you use an
Object that youre not allowed to instantiate? So if I cant write the following:
1.
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
147
then how can I use this stupid Object!? Well, when you have a static INSTANCE variable and a static
getter for that INSTANCE, you can access it like this:
1.
SingletonObject.getInstance();
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
148
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
149
Tire 2 seconds
Seats 3 seconds
Engine 7 seconds
Frame 5 seconds
With these times, you must implement the code that will simulate the construction of each of these
components individually, and then once all the necessary components are built you must put them
together to make a car. To build a car, youll need 4 tires, 5 seats, 1 engine and 1 frame. Heres the
catch, the assembly line can only and should only be capable of building 3 Components at any given
time. Youll need to implement this in your code.
Once youve completed the assignment and all unit tests are passing, try and fiddle with the order of
which the Components are assembled on the line. Is there a particular order that provides the fastest
building time for a Car?
Download
Click here to download the source files
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
150
Remember
This assignment deals with multithreading and the singleton design pattern. Be sure to read up on these
two articles before you try to complete the assignment:
Multithreading
Singleton Design Pattern
If you encounter strange issues, just think in terms of the fact that you have multiple threads running at
the SAME TIME doing their thing. Most problems can be solved by realizing this, and understanding
exactly whats going on in the code. I would recommend the use of plenty
of System.out.println() statements to be used as logging so you can get a picture of what exactly is
happening at any given moment.
Hint: if you are struggling to make the very last unit test pass, do some research on
the synchronized keyword.
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
151
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
152
Java Recursion
Id like to preface this by saying that the need to use Java recursion programming does not come up
often. I think in my entire professional career Ive used one recursive algorithm, though your mileage
may vary of course.
So what is Java recursion? In computer programming its the process of having a method continually call
itself until a defined point of termination.
Lets consider the following recursive code:
1.
2.
3.
4.
Warning: Dont actually try to execute this code, as it will never stop.
What sort of conclusions could you draw from this code snippet?
Well the first thing you should take note of is the name of the method: myRecursiveMethod. This is just
a random name that I chose to use for this methodnothing special going on there But, take a look at
what were doing inside the method: were calling a method named myRecursiveMethod. Notice
anything special there? Yes, thats the same method name!
So what happens?
Recursion!
The method will call itself, and it will execute the code inside, which is to call itself, so it will execute the
code inside of that method, which is to call itself, so it will execute that code, which is to call itself You
see what Im getting at here?
This code is missing a terminating condition, this is why it will run forever. So how about we include a
terminating condition?
1.
2.
3.
4.
5.
6.
7.
8.
Now with this method, weve introduced a terminating condition. Can you spot it?
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
153
When our int variable holds the value 0, then this method will not call itself and instead it will simply
exit out of the flow. This can be seen from the return 0 statement.
So now were in a position where this method will continually call itself with a decrementing value
of aVariable. So once aVariable hits zero, our recursive method is done!
Can you guess what the output would be if we called this method like so:
myRecursiveMethod (10)
Think about it, try and follow through the code line by line and see what conclusions you can come to
once youve made a guess, go ahead and create a Class file with a main method and
throw myRecursiveMethod in the mix and call it (youll need to make the method static).
Once youve run the program, if you have NO clue whats going on behind the scenes, then Id suggest
debugging by throwing a breakpoint in where the method begins. Step through the code line by line and
see what happens (it will clear things up).
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
154
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
155
10. {
11.
System.out.println("n2="+n2);
12. }
That seems pretty good as a start, but theres no recursion going on here remember we need to call
the fibonacciSequence method inside of itself to start Java recursion. The only problem is, if we do this
now, it will run forever. Remember the two rules, first we need a clear progression towards an end (F n =
Fn-1 + Fn-2) and two we need an end!
So whats our ending going to be? Well, earlier I arbitrarily chose to go to the 40th index of the equation,
so lets stick with that.
If we are going to be keeping track of which index were currently at then lets store it as an instance
variable. You could also just pass this into the fibonacciSequence method, but I dont like passing
parameters around unless its completely necessary. Oh, and we also need to keep track of our ending
point, so lets store that as an instance variable as well.
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
Okay, so now weve established the starting point, the ending point, but not the recursion. So lets put
that in as well:
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
156
17.
18.
19.
20.
21.
22.
23.
24.
25.
26. }
// doesn't go on forever.
if (index == stoppingPoint)
return;
// make sure we increment our index so we make progress
// toward the end.
index++;
fibonacciSequence(n2, n1+n2);
And Voila! We have our working algorithm for the Fibonacci sequence.
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
157
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
158
There will be many ways to solve this assignment, and Im not saying that my solution is the best
solution, but if you were having trouble getting your assignment to work, then mine might help you out.
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
159
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
160
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
161
For those of you who are experienced with Java already, you may be asking yourself this question. We
already have the means to search through a String for another matching String. Its called
the indexOf method, and it seems to be easier to use than regex. Heres your answer: regular
expressions will search through the entire String and doesnt stop when it finds the first occurrence, it
will keep searching and tell you about every single match that occurs (including the start and ending
indexes).
Also, mastering regular expressions means you will have to learn about all of the advanced searching
features that exist with regex in Java. So how about we start talking about those topics?
This will find matches for the letters: a, b or c. So if you were given the sentence Hello World!, it would
match precisely ZERO occurrences because the letters a, b or c dont exist in that String. If you had the
String How are you today? and you applied the [abc] regular expression, you WOULD get a match.
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
162
Two matches to be exact, this is because in the sentence How are you today?, there are two
occurrences of the letter a. How exciting!
Now if you want to get fancier with this stuff, we could move onto using a more complex regular
expression. Try this one on for size:
[bch]at
Any guesses on what matches you would get from this regex? It may not be obvious at first, but this will
actually make three matches, and those words are: bat, cat and hat. You see why? The first three letters
are encased in those square brackets, so they form a character class where Java matches either the
letter: b, c or h. Then it will append the search for a String literal at. So what do you get when you
combine the letters b, c or h with the String at? You get: bat, cat or hat.
Just gripping stuff, really! How about this regex:
[^bch]at
Any guesses on what this would match? If youre mastering regular expressions, then you might be able
to guess. The only difference with this regex than the one before is one symbol, the carrot (^). This is
actually just a negating symbol, which means it works just like the exclamation mark in Java conditional
statements. You would read this regex as saying: any letters other than b, c or h that have the String at
attached to them. One example of a matching String here would be the word rat. This meets the
requirements because the r at the beginning of the word rat is NOT a b, c or h, and it has the String
at attached to it. Make sense?
Lets expand a little bit on this concept.
Regex Ranges
A range in regular expressions is defined by using the hyphen (-). The best way for me to
demonstrate this is with an example, consider this regex:
[b-d]at
The introduction of the hyphen (-) between the b and d characters insinuates a range. This means
that all letters between b and d in the alphabet will be matches (ranges are inclusive of their
beginning and ending characters). So this particular regex will match the following words: bat, cat,
dat.
Ranges can also be used with numbers, or even with numbers in combination with letters. Lets say
youre interested in searching through some file names, and you want to see if there are any that have
the words file1, file2, file3 or files1, files2, files3. What would the regex be to match those
names?
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
163
file[1-3]|files[1-3]
Here you see that weve made use of the hyphen to define a range of numbers from 1 to 3 and weve
also used the OR operator (|) to choose between either the word file or the word files.
This will search your String to see if there are any occurrences of a word character. If this returns
anything, then we can say without doubt that your String is not strictly numeric. But look at all those
characters you had to type out to convey this desire just staggering really, 8 whole characters what a
waste of precious finger dexterity. Now lets use a shortcut:
\D
There you have it, you just saved yourself from typing out an additional 6 characters. Dont your fingers
feel rested? Now, my sarcasm here may be well founded, but when you really get to mastering regular
expressions, youll see that these shortcuts do save you a lot of time and effort. There are six different
predefined character classes, \d for detecting digits, \s for detecting whitespace and \w for detecting
word characters, then you just capitalize each one of those to look for the OPPOSITE. In other words,
since \d looks for digits, \D looks for non-digits. Since \s looks for whitespace character, \S looks for nonwhitespace characters, and then that goes without saying that since \w looks for word characters, then
\W looks for non-word characters.
Marvelous.
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
164
Can you create a regular expression that will properly verify if a given SIN is in the proper format? To be
explicit, the proper format is:
any 3 digits followed by a hyphen, followed by any three digits, followed by a hyphen, followed by any
three digits and then NO MORE characters at all. Give it a shot and youll be on your way to mastering
regular expressions!
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
165
Comparator/Comparable Interfaces
Enter the Comparator and Comparable interfaces these are what we use to accomplish the sorting
of Collections andArrays in a customizable way. You might ask Why are there two different
interfaces used for sorting?. Thats a great question, and Ill answer it soon.
So lets start off with a simple example so that you have a clear understanding of what Im talking about.
Lets assume youre presented with the following ArrayList:
[I, , L, O, V, E, , J, A, V, A, , P, R, O, G, R, A, M, S]
With this ArrayList, lets say youre given the requirements to sort all of the letters in a unique way.
1. You first need to show all of the vowels first (in alphabetical order)
2. Then then you need to list all the consonants after the vowels (also in alphabetical order)
The resulting ArrayList should look like this:
[A, A, A, E, I, O, O, , , , G, J, L, M, P, R, R, S, V, V]
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
166
Well, just keep in mind that they both do the same thing in the end. They will both allow you to define a
custom sorting algorithm for your Objects.
Comparator
Use this interface if you want to custom sort on an Object type that you didnt create
(i.e. Character, Integer,String)
It uses the compare(Object object1, Object object2) method to perform its magic
Comparable
Use this interface if you want to custom sort an Object that you have created
(i.e. Users, HumanBeing, Vehicle, Caretc.)
This interface is used to compare the current instance of your Object to another one (i.e.
Compare this instance of HumanBeing to another HumanBeing)
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
167
11.
theArrayList.add("J");theArrayList.add("A");theArrayList.add("V");theArrayList.add(
"A");theArrayList.add(" ");
12.
theArrayList.add("P");theArrayList.add("R");theArrayList.add("O");theArrayList.add(
"G");
13.
theArrayList.add("R");theArrayList.add("A");theArrayList.add("M");theArrayList.add(
"S");
14.
15.
Collections.sort(theArrayList);
16.
}
17. }
18. </string></string>
So you see here that were populating an ArrayList with our test sentence and then we invoke
theCollections.sort() method. The resulting ArrayList would look like this:
[ , , , A, A, A, E, G, I, J, L, M, O, O, P, R, R, S, V, V]
As you can see, thats not what were looking for; we want all the vowels to appear first. So lets get on
with the good code where we make use of our Comparator. If you study
the Collections.sort() methods, youll see that theres one that takes two parameters, a List and
a Comparator, so this is the method were interested in using.
Im going to be making use of something called an Anonymous Inner Type. Its kind of like creating a
whole class that can be used within an existing method. It has a special notation, so if you dont quite
get it, no worries:
1. Collections.sort(theArrayList, new Comparator<string>()
2. {
3.
@Override
4.
public int compare(String o1, String o2)
5.
{
6.
if (isVowel(o1) && !isVowel(o2))
7.
{
8.
return -1;
9.
}
10.
else if (!isVowel(o1) && isVowel(o2))
11.
{
12.
return 1;
13.
}
14.
15.
return o1.toLowerCase().compareTo(o2.toLowerCase());
16.
}
17.
18.
/**
19.
* This method determine if the String being passed in is a vowel or not.
20.
* @param o1 the String that may or may not be a vowel
21.
* @return true if the letter is a vowel, false otherwise
22.
*/
23.
private boolean isVowel(String o1)
24.
{
25.
return o1.equalsIgnoreCase("a") || o1.equalsIgnoreCase("e") || o1.equalsIgnoreCase(
"i")
26.
|| o1.equalsIgnoreCase("o") || o1.equalsIgnoreCase("u");
27.
}
28. });
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
168
29. </string>
Alright, so you see here that we are using a Comparator inside of the Collections.sort() method.
But were doing something neat, were declaring an anonymous inner type for this Comparator. What
Im doing here is Im avoiding having to create a whole new Object, then have that Object implement
the Comparator interface, then @Override the appropriate compare(String o1, String
o2) method, then instantiate that Object and pass it into the Collections.sort() method.
I have avoided all of this pain and suffering by using this little anonymous inner type trick. Youll notice
that when I instantiate a new Comparator via new Comparator() I also immediately insert an open
curly brace ({). This tells Java that Im creating an anonymous inner type. If you stop to think about it,
youre not allowed to instantiate an interface right? Right! But you can use this trick to get around all
that pain I described above.
So! Having explained that, lets talk about that compare() method.
Okay, so that about wraps up this post as always, if you really enjoy my teaching style and want to get
on the fast track for learning Java, head over to Java Video Tutorials and read up about my fantastic
video course. The students currently enrolled in the course have had nothing but great things to say
about it, and Im so excited to be making a real difference in their journey to become programmers.
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
169
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
170
Having said that, you will also need to create Players, these players will have one Hand of cards. Each
hand will consist of two distinct cards from the deck.
Not only do you need to deal cards to players, but you also need to deal the community cards. For this
iteration of the assignment, lets just deal five community cards right away. I dont want to put the
betting aspect into this assignment just yet.
Once you have dealt all players their hands (two cards each), and you have dealt the five community
cards, then youll need to figure out which player has the best hand. To do this, youll need to know
which type of hand beats another, so heres the list:
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
171
Youll need to output each players hand in the console window, as well as the community cards. Once
you determine which player is the winner, you should output which player won and with what hand. In
the event that there is a tie (i.e. two players hold the same winning hand), youll need to determine
which of the winning hands has the higher value cards. So if both players have three of a kind, then the
player with the three higher value cards wins (i.e. Player 1 has three jacks, but Player 2 has three aces
aces > jacks therefore Player 2 wins).
A draw will occur only if the values of the winning hands are exactly the same (i.e. two players have
three of a kind with kings and identical non-winning cards) In the event that two players each have
the same winning cards, but different non-winning cards (i.e. Player1 has three aces a king and a jack,
Player2 has three aces, a jack and a four), then the player with the higher kicker card wins (i.e. Player1
wins because their king kicker beats Player2s jack kicker).
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
172
Note: This assignment is more difficult than most other assignments I have posted on this blog. It took
me roughly 12 hours of coding to complete this assignment. The good news for you is that I have
included a good chunk of the coding in the assignment source files that you can download below.
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
173
Chapter 7
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
174
Java Serialization
The topic of Java Serialization is an interesting one, and can almost be thought of as a stepping stone for
learning the concepts of a database.
Picture this
Without Serialization
1.
2.
You start your Java application in your IDE (via right-click -> Run As ->Java Application)
You create a User Object
3.
4.
What happens to that User Object you so tediously created and populated with values? Well, its GONE!
Once your Java application ends, it frees up all the memory that was in use and POOF that includes
your User. Well, that sucks. You probably wanted to keep that User information
With Serialization
1.
You start your Java application in your IDE (via right-click -> Run As ->Java Application)
2.
3.
4.
5.
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
175
What happens to that User Object now? Well, its not in memory, because Java has cleaned that up
when the application ended. BUT! It now exists inside of a file that is stored on your actual computers
hard drive! Holy crap! Thats neat! Now if you write a little more code, you can actually read that file
and re-create that User Object when you fire up your Java application again.
Okay, so weve seen this kind of code before, except for two things. Weve
implemented Serializable (which is an import from java.io.Serializable), okay that seems pretty
straight forward. But you may also see that theres a line that says:
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
176
Whats that all about!? Well, this is used for version control purposes. First of all, if youre using an IDE,
then you will most likely be able to have the IDE generate this line of code for you. Seriously, you wont
even have to do anything more than hover over the name of the class (in this case User) and click on the
Add Generated serial version ID or something to that effect. Okay great, but what does it mean!?
Well like I said its used for version control. Heres an example that will help shed some light. Consider
this:
1.
2.
3.
4.
5.
Change the User Object code, and remove the password property and instead add a first and
last name
6.
When you make a change to the contents of an Object, you need to re-generate your
serialVersionUID, so delete the existing one, and re-generate the code using your IDE
7.
8.
9.
You get this error because the serialVersionUID of the Object that was stored in the file is
now different from the one youre trying to read it into. Remember, you removed the password and
added first/last name to your new User Object. So the Object stored in the file had a password, this new
Object doesnt. Since this is the case, Java will automatically throw
the InvalidClassException exception, and youll need to decide what to do to handle the situation.
This topic of version control/safety is a fairly complex one that has to do with databases and storage
mechanisms, so I wont go into any more detail.
Full Example
Alright, now that you know how to enable the User Object to be stored (serialized), lets see how we
actually store this thing!
package com.howtoprogramwithjava.runnable;
import
import
import
import
java.io.File;
java.io.FileOutputStream;
java.io.IOException;
java.io.ObjectOutput;
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
177
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import com.howtoprogramwithjava.business.User;
public class MyProgram
{
public static void main(String[] args) throws IOException
{
User user = new User();
user.setUsername("tpage");
user.setPassword("password123");
File file = new File("C:\\testFile.txt");
OutputStream fileOutputStream = new FileOutputStream(file);
ObjectOutput outputStream = new ObjectOutputStream(fileOutputStream);
outputStream.writeObject(user);
System.out.println("I've stored the User object into the file: " +
file.getName());
}
}
Voila, now I can look on my hard drive and see that a file has been created at C:\testFile.txt!
Note: I had to use two backslashes (\\) when listing my file location, because the backslash (\) is used as
something called an escape character. Its most commonly used when you want to put an actual quote
() symbol in a String. For more info on the backslash escape character see this explanation.
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
178
Connecting to a Database
So, storing and loading things from files (using Serialization) is great, but what if you want to use
something more robust? This is when youll need to put things into full throttle and use a real database!
Now this topic can seem scary to those of you who have never dealt with a database before, but when
you break the topic down into its fundamental concepts, it is a lot easier to follow along. Lets first try to
go over these fundamental concepts before we jump into any sort of coding.
What is a Database?
As I mentioned in the Serialization tutorial, Java applications have a certain lifespan. They only live as
long as they are running. Once the application is shut down, all of the Objects that existed in their
particular state go away. These Objects were all stored in the scope of the Java applications memory,
so when the application stops, all is lost.
This would essentially be catastrophic in the case of todays web applications. Can you imagine if you
had to re-create your profile and re-import all your pictures on Facebook every time they rebooted their
servers!?
This is why databases exist. A databases purpose is to take all of that state, all of the information
thats stored inside of your Objects and variables, and put them in a Database thats (hopefully) neatly
organized. So this will mean that as soon as you do upload a picture or post a comment on Facebook, it
will immediately get stored in a database so that if they do reboot their application, you wont lose
everything!
All a database really does is store data in a particular location (and a particular way) so that the data can
be retrieved later in a (hopefully) easy and efficient manner.
Now, I dont want to start talking about all the different kinds of databases that exist, because that
would take up way too many pages and it would probably bore you to death. If you really want to learn
everything there is to know about the history of the database and why we use them, Ill let you do some
self-guided research on the subject. However, if you do have any specific questions, I invite you to email
me at [email protected].
So, now that you understand that a database is used to store information for later retrieval, you may be
wondering how it stores the information. I keep saying that the information is stored neatly and
efficiently, but what do I mean when I say that? Well, thats the job of the database management
system.
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
179
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
180
Before I dive into the code, I want to give you a high level overview of what you can do with a database.
Now, as Ive said before, a databases main purpose is to store data for later retrieval, so this probably
means we should be able to both store, and retrieve, right? Right.
Insert
This is the operation that will allow you to put/store something into the database. When you insert
something into the database, you are creating something new inside of the database.
Select
This is the operation that you will use to retrieve data from the database. You can select certain
pieces (or all pieces) of data to be loaded into your application.
Update
This is the operation you would use if you wanted to change some existing data in the database. So lets
say a User updates their address, you wouldnt want to delete everything and start from scratch, you
just want to update the existing data.
Delete
This is the operation you would use when you want to actually permanently remove data from the
database. You can target it to delete just one piece of data, or ALL data.
When this eBook was published, the MySQL Connector version 5.1.22 was available, so
just choose to download the ZIP version.
When I clicked to download the file, it asked me to login, but theres a link that says No
thanks, just start my download!, this will get the file into your hands ASAP.
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
181
Once youve downloaded the ZIP file, open it up (I use 7-Zip) extract the JAR file to a directory of your
choosing (I prefer to keep it with my actual Java application files, but its up to you). For the record, the
JAR file you should be looking for should look something like this: mysql-connector-java-5.1.22bin.jar.
Okay, were nearly there, we HAVE the file we need, now we just need to tell our Java application where
to find it. This will mean we need to add this JAR file to the applications classpath. To do that, you
must:
Go to your STS (or Eclipse), right-click on the project that youve been working in (in the
screenshot below, its the HowToProgram folder). Heres what my project structure looks
like:
Choose properties
On the left hand side of the window that appears, click Java Build Path.
In the Libraries tab, click Add External JARs.
Choose the JAR file that you downloaded and extracted.
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
182
Excellent, if youve made it this far, then youre in great shape. That was the annoying setup part thats
associated with databases, you should really only have to do that whole process once.
Step 2: Download and Install the MySQL RDBMS
This process is a little more involved than just grabbing a file and unzipping it. So Ive created a video
tutorial that will help you through this step of the process. Just follow this link:
http://youtu.be/DQUlyZAuJww
java.sql.Connection;
java.sql.DriverManager;
java.sql.ResultSet;
java.sql.SQLException;
java.sql.Statement;
java.util.ArrayList;
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
183
import java.util.List;
import com.howtoprogramwithjava.business.User;
public class UserDao
{
// this is the URL that is needed to connect to your
// database. Here we're using MYSQL, a free RDBMS.
// The database name I've used is 'test'
String url = "jdbc:mysql://localhost:3306/test";
Connection con = null;
public UserDao ()
{
try
{
// this is the driver for the MySQL RDBMS,
// each database system has a different class
// that is used to connect to the DBMS.
Class.forName("com.mysql.jdbc.Driver");
}
catch( Exception e )
{
System.out.println("Failed to load MySQL driver.");
e.printStackTrace();
return;
}
try
{
this.con = DriverManager.getConnection(url, "database_username", "database_password");
System.out.println("Created a database connection.");
}
catch( Exception e )
{
e.printStackTrace();
}
}
public List<User> getUsers()
{
Statement select = null;
ResultSet result = null;
List<User> users = new ArrayList<User>();
try
{
select = this.con.createStatement();
result = select.executeQuery("SELECT username, password FROM users");
while(result.next())
{
// process results one row at a time
// by mapping the data from the database to
// the a User object
String username = result.getString(1);
String password = result.getString(2);
users.add(new User(username, password));
}
}
catch (SQLException e)
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
184
{
e.printStackTrace();
}
finally
{
closeQueryConnection(select);
}
return users;
}
private void closeQueryConnection(Statement select)
{
try
{
if (select != null)
{
select.close();
}
}
catch (SQLException e)
{
e.printStackTrace();
}
}
public void closeDatabaseConnection()
{
try
{
if (this.con != null)
{
this.con.close();
System.out.println("Database connection is now safely closed.");
}
} catch (SQLException e)
{
e.printStackTrace();
}
}
}
Okay, yes I know, I know, its a lot of code and its probably quite confusing and maybe even frightening.
But thats why Im here, so lets take the mystery out of this mess shall we?
The first thing you may notice is the (almost ridiculous) use of try/catch blocks of code. This is because
dealing with databases is sometimes sensitive business. Sometimes things can go wrong with your
database operations, and you need to handle these exceptions appropriately. Consider what would
happen if you were updating a bunch of values in your database because one of your Users changed
their address, but halfway through the update, the database connection was dropped. Now your
database is left in a state where only half the information was updated for your Users address. Uh oh!
So, when Java was designing their code, they made the decision to force developers to handle these
exceptions (theyre actually called checked exceptions, as opposed to unchecked exceptions).
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
185
In any case, this example code above is littered with try/catch blocks because of these checked
exceptions. Its also worth mentioning that as your skills develop, you will likely be switching to a
framework that will handle all of these complexities so you dont have to. Frameworks like Spring (with
their Spring JDBC code) will make dealing with databases much easier!
Okay, so what else is going on here? Well, essentially whats happening is that when we instantiate our
UserDao object, we create a connection to our database. This connection is what allows us to talk to our
database, as we want to tell it to do things like fetch me some data or store this data for me. This is
made possible with the this.con variable.
The next thing thats happening is inside the public List<User> getUsers() method. This method is
what will use the this.con to query our database, and when I say query our database, I just mean that
it will ask the database to show what data its storing (we want to retrieve the data). So, we retrieve
the data (via our select statement) and then we iterate through all the results and store the
information from the database into some new User objects.
Thats really all the magic thats happening inside of all this code.
1. Open a connection to the database
2. Query the database
3. Store the results in Java Objects
This is really all that ever happens inside of database code in the majority of cases, we always have to
make sure we have a connection, then we perform our operation on the database, and then we do
something with the results from the operation.
The only real annoying part I find is that you cant just read data from the database and just immediately
have it available as a Java Object. Theres always a mapping that has to be done for each piece of data
thats read, from the database to the Java Object. In any case, its not too complex to implement this
mapping, as youve already seen in the code example above (inside the while loop).
Step 4: Test the code
Like any good developer, you shouldnt just take my word for it, you should test this code and make sure
it works right? So lets create a unit test!
package com.howtoprogramwithjava.test;
import java.util.List;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.howtoprogramwithjava.business.User;
import com.howtoprogramwithjava.dao.UserDao;
public class UserDaoTest
{
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
186
UserDao sut;
@Before
public void beforeEachUnitTest ()
{
sut = new UserDao();
}
@After
public void afterEachUnitTest ()
{
sut.closeDatabaseConnection();
}
@Test
public void testDatabase ()
{
List<User> users = sut.getUsers();
for (User user : users)
{
System.out.println(user.toString());
}
}
}
Okay, so this isnt exactly the greatest unit test, because were not using the Triple A approach here.
Were only Arranging and Acting, were not Asserting. I did this on purpose because your situation will
vary with the data thats available in your database, so doing an assert at the end would likely fail when
you run it. All I want to see here is that this code executes without any exceptions. Heres an example
of the output when it does run successfully:
Created a database connection.
username: testUser, password: testPassword
Database connection is now safely closed.
So, for my example, I had one row in my database with a User who had the username testUser and a
password testPassword.
program failed when it was setting the driver details. If the String you have that describes your driver is
correct (in our case its "com.mysql.jdbc.Driver") then its possible that you didnt put the drivers JAR
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
187
file on the classpath correctly, have you completed Step 1? If yes, then try copy pasting the error into
Google to see if other people have had the same problem as you.
java.sql.SQLException: Access denied for user 'database_username'@'localhost' (using
password: NO) This means that youre not putting in the correct credentials to connect to your
database. Remember back in Step 2 when I showed you how to setup your MySQL database? You setup
a username and password for your database here, be sure to put those details into your code on this
line:
this.con = DriverManager.getConnection(url, "database_username", "database_password");
You need to replace the "database_username" and "database_password" with the username and
password you setup in Step 2.
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'testDatabase.users'
doesn't exist This probably means that you havent created a database table yet, or if you did, you
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
188
Chapter 8
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
189
2.
All the other readers of this site will benefit from seeing the answer to your question, as they
likely have the SAME question too!
3.
Gives me ideas on other topics that I can cover if I notice the same questions coming in.
Stackoverflow.com
Whenever I have been REALLY stuck on a complex programming problem, I have turned to this site with
great success. You just ask your question, and there are literally TONS of programmers at your disposal
who will try to help you get to the bottom of your problem. Many times Ive had developers solve my
problems by making me realize that the overall design of my solution needs to be tweaked. To me, this
is the best solution to any problem, because if I had just tried to hack in a solution to a poor design, I
would have WAY more problems in the future. Better to solve the root of the problem instead of the
symptoms right?
So, overall, this website is extremely helpful as it can crowdsource the proper solution.
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
190
Google
This seems like a no-brainer, and for the most part it is. But heres a few tricks that I use whenever Im
trying to solve a problem. I typically solve run-time errors in this fashion:
1. Isolate the exception in your logs/console
2. In your logs/console, find out if you can see the words Caused By:
3. Copy/paste the line of words after Caused By: into Google and search
This tactic is good for finding related articles on people who have had the same problems as you, and
seeing how they went about solving them.
Note that if you dont any search results, its very likely that you have some information in the line that
you copy/pasted thats specific to YOUR program. See if you can isolate any words that are specific to
your program and remove just those words, then do the search again.
What if you dont see Caused By:
Well, no worries, the trick I do here is I can the exception until I can see a Class that I recognize. Lets
take a look at the following example stack
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
191
trace:
This is a problem I recently had with one of the websites I created, and heres how I went about
solving it.
1. If you look at the stacktrace error as a whole, it seems very intimidating, so I like to simplify it by
just looking at the blue underlined text.
2. I scan them one by one from top to bottom until I find a Class name that I recognize
a. Note: The first blue underlined text says org.hibernate.HibernateException so this
means that the problem has to do with the Hibernate framework good to know
3. SpringSessionContext.java Means nothing to me, so I keep looking
4. SessionFactoryImpl.java Nope
5. UsersDao.java Aha! I recognize that class, as I created it to save the information for
the Users that belong to my program.
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
192
6. Now I look at the actual error: No Hibernate Session bound to thread, and
configuration does not allow creation of non-transactional one here
7. So I take that error and copy/paste it into Google armed with the knowledge that it has to do
with the Hibernate framework and that its happening in my UsersDao class, which I use to save
user information
8. The first result is a question from stackoverflow click here if you want to see it. And what do
you know, I scroll down in the stackoverflow question until I see an answer that was given by a
user and it has a green checkmark to the left of it. This denotes that the users problem was
solved by this answer. The person answering the question says that you likely need to include
the @Transactional annotation on your class.
9. I put the @Transactional annotation on my UsersDao class to test and see if this fixes my
problem and what do you know, my problem is SOLVED!!!
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
193
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
194
Unit Testing
Im very excited to start sharing with all of you, my five best tips to being a better programmer. These
tips are ones that I used on my journey to becoming a senior level programmer as quickly as I did. For
those of you who are interested, here in Canada, the absolute minimum amount of time it takes a
programmer to progress to a senior level is five years. I was able to attain my title in five years through
hard work, and smart work. I know youre all hard workers, but its time to arm you with some killer
knowledge to help give you a strong start!
My first tip revolves around ensuring you have quality code. When creating applications, its of
paramount importance that you keep the number of bugs as close to zero as possible. Now, I say
as close to zero as you can, because I realize that once your application grows in size, its very difficult to
have absolutely no bugs. But with this tip, you will certainly be on your way to producing top notch
code.
Lets go
back to our example of creating an application that will allow users to login if they enter the proper
credentials. The first thing I would do when considering the fact that I wish to unit test a piece of code, is
to think about all of the test cases for a particular part of the application.
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
195
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
196
}
return userList;
}
}
Okay, so here we have a Class called Login that defines three methods:
isValidUsername
isValidUsernameAndPassword
getUsersStoredInSystem
These three methods will be used to satisfy our requirements. Remember, we must check to see IF a
username exists, as well as check to see if a combination of username and password is valid. So, given
the code above, how certain are you that this code will work?
Well, the common approach is to test this code by manually typing in some usernames and passwords
until something doesnt work right? Well, what if you have 6 different tests that you perform, and on
the 4th test, something doesnt work. You would probably find out why it didnt work and then test
again right? Well, are you going to re-test every one of the scenarios you already tested before you hit
the test case that didnt work? You might, but what happens if the number of total test cases isnt 6, its
600!
Imagine attempting to take almost 600 test cases manually and then finding a bug on test #385. You
could easily fix the bug, but now youll have to go back and test 384 cases before youre confident you
didnt break anything else!
In the real world, this kind of testing just doesnt happen and this is why some applications youve used
had bugs in them. It can happen people, and its not always pretty! Now, wouldnt it be nice if you could
just push a button, and all 600 tests could be performed automatically? Of course it would be great!
This isnt a dream, its reality. Its called unit testing. So lets see how you could go about pulling it off!
JUnit
JUnit is a framework that allows you to create automated test cases that can be run at the push of a
button. Now isnt that fancy! Great, youre sold right? Of course you are, so lets see what some unit test
code looks like. The first thing we need to figure out, is what our test case should be. Lets take a look
back at our requirements:
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
197
1) A User will be allowed to login to the system when they provide a valid username and password
combination.
Okay, so if a User should be allowed into the system with a valid username/password combination, then
thats a great test case to start with. What is a possible combination of username/password
that should allow us into our system? Well, since we have a list of 10 valid users (as per our applications
code) we should use one of those Ill randomly choose to test:
username: user3
password: howtoprogramwithjava
Lets see what the code looks like to test this scenario:
package com.howtoprogramwithjava.test;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import com.howtoprogramwithjava.business.Login;
public class LoginTest
{
// the variable name 'sut' stands for
// system under test. This is just a
// coding convention and it refers to
// the Object we will be testing.
Login sut = new Login();
@Test
public void testValidUsernameAndPasswordCombination ()
{
boolean result = sut.isValidUsernameAndPassword("user3", "howtoprogramwithjava");
assertTrue(result);
}
}
Okay, so this doesnt look too different from what were used to. Some interesting things to note are the
use of the code @Test and assertTrue(). So lets talk about this stuff!
@Test
This is called an annotation, and its used to mark the method with some extra functionality. When we
add this @Test annotation to our test method, it will tell JUnit to run our method (kind of like a public
static void main()method). The big difference here, is that your test class ( LoginTest) can
have many test methods with the @Test annotation. This means that we can run several methods one
after the other in rapid succession! Nice!
assert True()
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
198
One other important aspect to unit tests is that we need to tell Java what it is that we expect to happen
once the test is done. So in the case of our test method above, were testing the case that a valid
username and password is given. We would expect that when we invoke
the isValidUsernameAndPassword() method with a valid username/password combination, we would
get a result of true right? So since we are expecting this method to return true we just insert the
code assertTrue(result) to say that we want to check and make sure that the result is actually true.
So, this would imply that if the result was false, we would get some kind of error right? Right! Thats
exactly what would happen and JUnit likes to represent this whole correct test results vs. incorrect
test results with green vs. red colors!
So, without further delay, lets actually RUN our test!
If all goes well, you will see a green bar appear that looks something like this:
So, like I said, it will be a green bar if all your tests were successful, and it will turn red if any werent
successful. Also, if there were any that didnt work, it will output the reason why it didnt work. So, lets
expand on our test Class and add more test cases based on our requirements:
2) If a username is entered that does not exist in the system, and error message must be shown that will
alert the user that the username entered could not be found.
So, the test case we should create here is to pass in an invalid username into
our isValidUsername() method:
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
199
package com.howtoprogramwithjava.test;
import
import
import
import
static org.junit.Assert.assertFalse;
static org.junit.Assert.assertTrue;
org.junit.Test;
com.howtoprogramwithjava.business.Login;
So, as you can see, we have just added a second unit test to our LoginTest Class. This one invokes the
isValidUsername() method and passes in an invalid username (in this case I randomly chose
user2834). This time we use the assertFalse piece of code to say that we are expecting this method
to return a value of false. We are expecting this because we are passing in a username that does NOT
exist!
When the test cases are run, you should still see a green bar! So far so good?
Negative Tests
One other important aspect to unit testing is to always test both the positive and negative scenarios. So
since we currently have two test cases:
1) Test isValidUsernameAndPassword() method with a valid username/password
2) Test isValidUsername() method with an invalid username
We should also automatically test the opposite of these two outcomes, so we should have tests for:
3) Test isValidUsernameAndPassword() method with an invalid username/password
4) Test isValidUsername() method with a valid username
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
200
Make sense? I wont include these tests in here, as theyll just take up extra space, and plus it may be
more fun for YOU to write those tests yourself
Now, you might be thinking that this code is pretty solid right? Weve written a few tests and everything
is green and good. What if we introduce this test?:
@Test
public void testAnotherValidUsernameAndPassword()
{
boolean result = sut.isValidUsernameAndPassword("User2", "how to program with
java");
assertTrue(result);
}
This test (as is stated in the name of the test method), should be testing another valid username and
password combination. But, this time the test FAILS! What the heck happened? Heres a screenshot of
the failure.
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
201
So, in this case Ill just say that the password needs to be case sensitive and the username
should not be case sensitive.
Lets go back and change our application code with these new requirements:
public class Login
{
public Boolean isValidUsername(String username)
{
//... content removed for brevity
// here we use equalsIgnoreCase() instead of just equals()
if (username.equalsIgnoreCase(aUser.getUsername()))
{
return true;
}
//...
}
public Boolean isValidUsernameAndPassword (String username, String password)
{
//... content removed for brevity
// here we use equalsIgnoreCase() instead of just equals() on the username
// but we leave the equals() comparison for the password!
if (username.equalsIgnoreCase(aUser.getUsername()) &&
password.equals(aUser.getPassword()))
{
return true;
}
//...
}
// ...
}
So, now that weve identified a real bug and weve changed our applications code to fix the bug. Lets
go back and re-run our tests!
If all goes well, youll see a green bar and breathe a sigh of relief.
Now, Im sure there are a bunch of other test cases that you could think up. I know its always useful to
test with null values to ensure your code wont throw any unwanted exceptions. Why dont you try to
write some tests that use null for the values of username and password? I think youll see some
interesting results.
Summary
Automated testing (via JUnit or any other testing framework) is the wave of the future. All applications
should be built on a solid foundation of unit tests to ensure that everything is still working the way its
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
202
expected to work as the product evolves. Its the difference between happy customers and angry
customers. So, its absolutely worth the effort to create unit tests to avoid these headaches.
Dont Be Clever
In my years as a programmer, Ive come across some really really smart people who could create some
very fancy code that (at the time) seemed to be the greatest stuff since sliced bread. But let me tell you,
now that they have moved on in their careers and have left the company at which I currently work, I
look at this code that I now have to support, and I shake my head.
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
203
What in the heck is this piece of code doing!? You could probably sit around for 10 minutes trying to
figure it out, but, if I just add some comments before the for loop, I could save you a lot of grief:
// count to 49
for( i = 0, j = 100; i < j; i++, j--)
System.out.println(i);
Oh, I see! They are just counting all the way up to 49 and outputting each number in the console. Fair
enough. This is effective, but what if someone were to change the code inside that for loop and not
update the comment to reflect what it is theyve change? This is the downfall of relying on comments,
they arent always correct, and sometimes that can be more damaging to your debugging efforts than if
they just hadnt commented the code at all.
But in any case, for the most part this tactic is useful and should be followed by developers. But, Ive got
one more neat way to ensure that your code is simple and easy to follow and you may be surprised to
hear it.
Unit Testing!
Believe it or not, I find that when Im writing code and creating unit tests at the same time, this helps to
keep the code simple. Why is that you ask? Well, I find that when Im writing unit tests, the code has to
be simple in order for it to be unit testable in the first place. The longer and more coupled a piece of
code is, the harder it is to unit test. So if you write your code while unit testing it at the same time, a
beautiful thing happens. Your code becomes less coupled, each method tends to keep to a reasonable
size AND youve got a whole bunch of unit tests that help describe what your code does (through
utilization of descriptive unit test methods, and expected results with your assert methods).
Descriptive Variable Names
I cannot overstate the importance of being explicit with the names of your variables. Let me tell you the
pain and eye gouging that goes on when I see a block of code that looks like this:
Date date1 = new Date();
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
204
Seriously!? What the hell is going on here! It drives me mad when I see people naming
their Date variables date1 ordate2, just name your variable after what it truly is! If I was assigned to
debug this code, I wouldnt have a clue what the expected behaviour should be but had the developers
used more descriptive variable names, like effectiveDateOfPurchase instead
of date2 and currentDate instead of date1 and lastDayOfMonth instead of y, I may have had a better
idea of whats going on here.
Note: This particular block of code doesnt do anything, I literally just made it up on the spot to get
my point across.
So, the point Im trying to make here, is that you shouldnt be afraid of using a long variable name. Java
wont get mad at you for having a variable name thats 20 characters in length. Plus, modern IDEs make
it easy to track variables and rename them if they really do get too out of hand. But I am a firm believer
that no seasoned developer would get upset with you if you were to use a descriptive name for your
variables, because it really does help people understand what the code really does!
Summary
So, the most important thing you should take away from this discussion, is that you should KISS Keep it
simple stupid. Comment your code when you think people may get confused as to what its doing. Unit
test your code so theres less chance of your methods becoming unwieldy. And please, PLEASE, be
descriptive when naming variables/methods. The world will literally be a better place if all developers
followed these simple tips.
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
205
Refactoring Tools
This tip is something I only learned about in the last year or so of my programming career. But since
learning it, I find that its something I just cant live without and am constantly sharing with other
developers.
What is Refactoring?
Lets take a look at Wikis definition of refactoring:
Code refactoring is a disciplined technique for restructuring an existing body of
code, altering its internal structure without changing its external behavior,
undertaken in order to improve some of the nonfunctional attributes of the
software. Typically, this is done by applying a series of refactorings, each of
which is a (usually) tiny change in a computer programs source code that does
not modify its conformance to functional requirements. Advantages include
improved code readability and reduced complexity to improve the maintainability
of the source code, as well as a more expressive internal architecture or object
model to improve extensibility.
Now normally Im not a fan of these definitions because theyre a little too technical and attempt to be
as complete an answer as possible to please everyone. But in this case, I think this is a great definition!
Refactoring is the process of taking existing code and changing it in some way to make it more readable
and perhaps less complex. The key thing to note, is that when the code is changed, is does NOT affect
the underlying functionality of the code itself. So the changes youre making are literally just to make
the code easier to follow by your fellow developers.
Okay, so now that you know what refactoring is all about, how can you go about refactoring the code
you already have?
Refactoring Tools
The SpringSource Tool Suite (and Eclipse) provide some great refactoring tools that are easy to use. So,
lets take a look at an example of some code that could use some refactoring shall we:
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
206
import org.junit.Test;
import com.howtoprogramwithjava.business.Card;
import com.howtoprogramwithjava.business.Dealer;
import com.howtoprogramwithjava.business.Deck;
public class DealTest
{
@Test
public void testDealingOfCards ()
{
Deck deck = new Deck();
Dealer.deal(deck.getDeck(), deck.getPlayers());
for (int i=0; i<deck.getPlayers().size(); i++)
{
assertThat(deck.getPlayers().get(i).getCardsInHand().size(), is(5));
System.out.println(deck.getPlayers().get(i).getName() + " has the following cards:");
for (Card aCard : deck.getPlayers().get(i).getCardsInHand())
{
System.out.println(aCard.toString());
}
System.out.println();
}
assertThat(deck.getDeck().size(), is(32));
}
}
This code was used to unit test the dealing of cards to four players. We are ensuring that every player
has 5 cards after the deal, and that there are only 32 cards left in the deck (after 20 cards were dealt out
to four players). We also list out what cards are in each players hand.
Now, as I stated in the beginning, refactoring code isnt about changing its functionality, but to make the
code a little bit more readable. So to do this, the first rectoring I want to do is to extract local variables.
2.
3.
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
207
Note: All references to the exact ways of using the refactoring tools is only applicable for Eclipse
and STS, any other IDE will have a different set of menus to run the same refactoring techniques
Also Note: You can use the shortcut key sequence Alt-Shift-L to extract a local variable
Okay, so now youre presented with a screen that asks you what youd like to call your new local
variable, I just leave it as the default players name and hit enter.
Now lets take a look at our new code:
@Test
public void testDealingOfCards ()
{
Deck deck = new Deck();
// here's our new local variable
List<Player> players = deck.getPlayers();
Dealer.deal(deck.getDeck(), players);
for (int i=0; i<players.size(); i++)
{
assertThat(players.get(i).getCardsInHand().size(), is(5));
System.out.println(players.get(i).getName() + " has the following cards:");
for (Card aCard : players.get(i).getCardsInHand())
{
System.out.println(aCard.toString());
}
System.out.println();
}
assertThat(deck.getDeck().size(), is(32));
}
Look at that! Now all of the places in the code where it used to say deck.getPlayers() now points to
the players local variable, and its automatically assigned deck.getPlayers() to this players local
variable.
That was pretty painless right? Now, what else can we do to clean things up? I see two references to
players.get(i).getCardsInHand(), so lets apply the same technique again to create a local variable
called cardsInHand.
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
208
I see that theres a chunk of code thats just dedicated to outputting details to the console and this
could be thought of as just noise in the testing method, so how about we extract it into another
method
This is a very similar process to extracting a local variable, all you must do is:
1.
2.
3.
Note: This can also be done by selecting the code and hitting Alt-Shift-M
Now youll be presented with an extract method screen that asks you to name the method youre
about to create. Well, since this is just a block of code that outputs the cards to the console, lets name
the method outputCardDetailsToConsole(). So type that in and hit Enter.
Lets take a look at what weve done now:
@Test
public void testDealingOfCards ()
{
Deck deck = new Deck();
List<Player> players = deck.getPlayers();
Dealer.deal(deck.getDeck(), players);
for (int i=0; i<players.size(); i++)
{
List<Card> cardsInHand = players.get(i).getCardsInHand();
assertThat(cardsInHand.size(), is(5));
outputCardDetailsToConsole(players, i, cardsInHand);
}
assertThat(deck.getDeck().size(), is(32));
}
private void outputCardDetailsToConsole(List<Player> players, int i, List<Card> cardsInHand)
{
System.out.println(players.get(i).getName() + " has the following cards:");
for (Card aCard : cardsInHand)
{
System.out.println(aCard.toString());
}
System.out.println();
}
Would you look at that, now in our test method, all those noisy lines of console output code have been
reduced to one line of code that says outputCardDetailsToConsole(players, i, cardsInHand);.
The IDE has automatically figured out what parameters need to be passed into the new method that
was created and passed in those variables for you. Absolutely painless right? Now the code is much
more readable!
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
209
Rename Variables
Now theres one shortfall of the extract method refactoring tool, and its that it will often choose nondescriptive variables names for the parameters in the methods signature. So how about we change one
of the variable names using our refactoring tools!
I dont like the fact that it has used the variable name i for the player number, so in order to change it,
we just:
1.
2.
3.
choose rename
Youll see that the variable gets outlined in blue and theres a little dialogue that appears that states
enter new name, press Enter to refactor. So thats exactly what well do! Type in playerNumber
and hit Enter.
Voila, weve now renamed the variable in the methods signature as well as every occurrence of that
variable in the method itself. PAINLESS people!
Note: You can rename a variable using the Alt-Shift-R shortcut sequence.
For all of those shortcut key maniacs out there (like myself), youll notice that all of your refactoring
tools are available via the Alt-Shift-(something) sequence. So just always remember that Alt-Shift is
your refactoring friend
3.
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
210
Now, we want to pass in the Deck object, so in the Change Method Signature dialogue that appears:
1.
2.
3.
4.
Note: The Name column represents the name of the variable as it appears in the method youre
changing. The default value column represents what variable name it should put in for where this
method is being called, in this case its being called from our test method, and we know that the test
method has a deck variable, so its safe for us to use this default value, if youre unsure what value
to use, you could put in null and then go back and change all the references where needed.
Heres a screenshot of what the Change Method Signature should look like after youve entered your
details:
Finally, heres what your code will look like after we make use of this added deck variable:
@Test
public void testDealingOfCards ()
{
Deck deck = new Deck();
List<Player> players = deck.getPlayers();
Dealer.deal(deck.getDeck(), players);
for (int i=0; i<players.size(); i++)
{
List<Card> cardsInHand = players.get(i).getCardsInHand();
assertThat(cardsInHand.size(), is(5));
outputCardDetailsToConsole(players, i, cardsInHand, deck);
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
211
}
assertThat(deck.getDeck().size(), is(32));
}
private void outputCardDetailsToConsole(List<Player> players, int playerNumber,
List<Card> cardsInHand, Deck deck)
{
System.out.println(players.get(playerNumber).getName() + " has the following cards:");
for (Card aCard : cardsInHand)
{
System.out.println(aCard.toString());
}
System.out.println("The deck has " + deck.getDeck().size() + " cards in it.");
System.out.println();
}
Summary
I use the refactoring tools on a daily basis at my job and I find that it saves me tons of time. Every time
Im pair programming with someone and they happen to see me use one of these tricks, they always
stop me and ask me what it was I just did. Then they end up thanking me for saving them so much
time I should seriously start charging for all these tips and tricks
So, use these tricks and remember that the Alt-Shift keys are your refactoring friend! I look forward to
seeing some more readable code out there everyone
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
212
Challenge Yourself
When I first started working at my current job, I was just barely out of the gates as a programmer. I had
about a years worth of experience under my belt, and was being thrown into a new workplace as an
intermediate level developer. I managed to do well enough in the interview to fool the company into
thinking I was an intermediate developer, when I was definitely a junior level.
So, in the hopes to rectify this situation, I took note of what frameworks the company was using for their
web application product and set out to learn them.
Continuous Education
It wasnt mandatory for me to learn the framework the way I did, but I knew that the best way to learn
something is to throw yourself into it head first.
So my tip for you today is all about learning something new by choosing to learn it in a way that
youll have to dedicate yourself to learning it. My example of this is something called the Spring
framework (its created by the same people that made the SpringSource Tool Suite IDE that you may be
using). The Spring framework is used to help you when building a web application, its uses are a plenty,
but thats not what I want to talk about in this article.
The point here is that there was a particular piece of technology that I needed to learn, and at the same
time there was a project that I wanted to startup with my business partner. This project I wanted to
start was a web application that would help people in the ecological land classification industry. So I
figured, what better way to kill two birds with one stone than to use this Spring framework for my new
project? This would force me to learn the technology while I created this web application on the side,
and it would benefit my professional career as well!
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
213
any case, I think its important to have someone that will hold you accountable for your learning. Now, if
you dont have any ideas for any projects that you would like to actually release and start selling, try and
think up a project that you will want to complete. For some programmers its the challenge of creating
a game, or a fun website (like a blog). What matters is that it should be something that you will enjoy
working on.
Another good example of this concept of challenging yourself to learn, was when I decided I wanted to
learn a new programming language. I looked at the languages out there that had some momentum
behind them, and decided I wanted to learn Objective C. This language is what is used to create iPhone
apps on the iPhone/iTouch/iPad. There seemed to be a lot of hype around creating mobile apps, so I
figured Id think up an app I could actually use myself.
I realized that there was a need in the iPhone market for an app that would automatically text message
my girlfriend and let her know that I was almost home (or that I had left work). I was tired of sending
text messages while trying to drive, so wouldnt it be neat if there was an app that just automatically
monitored your location and sent a text message to a person of your choosing between x/y oclock?
So once again, I was in a win/win situation here. I would be creating an app that I wanted to use, I could
then sell the app, and the worst case scenario was that I would learn how to program in Objective C
(which is a great skill to have). I had my girlfriend hold me accountable for the creation of the app by
monitoring my progress (she was very supportive), and within a few months I had completed the app!
Its quite fun to be able to show my friends that I had an app in iTunes!
Serendipity
It was interesting to me how much I actually learned about Java when I was learning about the Objective
C language. This was mostly because both languages share roots in Object Oriented programming.
Nevertheless I hadnt intended on expanding my knowledge in Java when I set out to learn Objective C,
but thats exactly what ended up happening. This fact presented itself in the form of understanding the
bigger picture and the foundations of any programming language. When you learn multiple
programming languages (or even spoken languages), you cant help but identify similarities between
them and in turn understand the foundations on which theyre built.
Ive turned this concept into overdrive when I started this How to Program with Java blog. Ill be the
first to say that you learn an incredible amount of things when you try to teach a subject. This is mostly
because I want to try and find the best way to explain a particular topic, and in order to do so, I need to
understand all the inner workings of my subject. Thankfully, I find this adventure to be very fun and
rewarding! Helping people is a business everyone should love
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
214
Summary
So overall, Ive found that Ive been able to level-up my skills over and over again by following this one
simple tip.Challenge yourself! But do so in a manner that makes it hard for you to give up. Find someone
to hold you accountable. I hope that YOU will be holding ME accountable for the content that I
provide to you.
When you are continually learning, you will find yourself surpassing most of your peers at (what I
considered) alarming speed!
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
215
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
216
since I was the one who worked on it, the complaint landed on my desk. I reviewed the customer's
complaint and said "Wait a second, this customer is complaining about a bug that's NOT a bug, that's
just how we designed the code to work". I quickly pulled up the unit tests that were written to review
whether or not I was correct, and sure it enough, that's how we designed it to work! So I:
1.
2.
3.
4.
5.
After this was done, a wonderful thing happened. Since I had such a large volume of unit tests around
this particular piece of the application (due to my TDD approach), I was extremely confident in my code
change. So I checked in the code change, assigned it to the QA team, and sure enough... no bugs!
I find that having the unit tests created first (as part of TDD) ensures that all your code will be
documented against the requirements, so things (like a mistake in requirements) are easily addressed.
And then if a change needs to be made to the code, it can be made with a high level of confidence that
you didn't break anything else.
REQUIREMENTS
Our customer needs an application built that will count the number of words in a paragraph. There
should be a count of the total number of words in the paragraph as well as a count of the number of
times an individual word is used in the paragraph (they want to see what words are most commonly
used).
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
217
IMPLEMENTATION
Ok, so let's start with our Test Driven Development. The first thing we need to do is write a failing test.
Our first test could probably just count the number of words in a sentence (by counting the number of
spaces in a sentence).
WordCountTest.java
import static org.junit.Assert.*;
import org.junit.Test;
public class WordCountTest
{
WordCount wordCount = new WordCount();
@Test
public void countTheNumberOfWordsInASentence ()
{
String sentanceWithFourWords = "How are you today?";
Integer countFromString = wordCount.getWordCountFromString(sentanceWithFourWords);
assertTrue(countFromString == 4);
}
}
WordCount.java
public class WordCount
{
public Integer getWordCountFromString(String sentence)
{
return 0;
}
}
Okay, so when we create the WordCountTest.java we create a test method with an appropriately
descriptive name (ie. countTheNumberOfWordsInASentence), then the contents of this method will
invoke our system under test. The system under test in this case is a new Class we had to create called
WordCount.java. I then created a very simple method inside of the WordCount.java file that just
returns the value of zero for the time being. We then make sure that the returned result is what we
would expect it to be, given our inputs. So, since our input was a four word sentence, we should expect
the System Under Test to return the value of 4! But, since we havent implemented the code inside of
our system under test, we get a failing test. Missing accomplished. (If you dont remember how to run
a unit test, just click here)
Note: The key to setting up a good unit test is to follow the Triple A rule:
Arrange This is where you will be setting up all of the variables in your test case
Act This is where you will be performing the actual call to the System Under Test (SUT)
Assert This is where you will test to make sure everything is as expected
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
218
Now that weve implemented the first step of our three step process for Test Driven Development
(write a failing test), we move on to step 2 Write the minimum amount of code to make the test pass.
So lets try and implement some real code to make our test pass! Well just change the method in our
WordCount class
public class WordCount
{
public Integer getWordCountFromString(String sentence)
{
String[] stringArray = sentence.split(" ");
return stringArray.length;
}
}
With this code change above, we now have a passing test. All we needed to do was use the split()
method, which will split up a single String into an Array of Strings based on a specified character. So
all I had to do was supply a blank space ( ) as the character to split up the String. This then created
an array of Strings and stored it into the stringArray variable. We then return the length of our new
stringArray variable, and voila, we have the length of 4!
So, now weve completed step 2, now all thats left is to refactor our code. But in this case, the code is
already pretty simple and easy to read. We could maybe add a check to make sure that the sentence
variable is not null, but perhaps we could just add that as a test instead. So for now well skip step 3 and
instead repeat the cycle.
Lets go back to step 1 and add another failing test. Keeping in mind out Triple A rule, we should follow
the structure of Arrange, Act and Assert, like so:
import static org.junit.Assert.*;
import org.junit.Test;
public class WordCountTest
{
WordCount wordCount = new WordCount();
@Test
public void countTheNumberOfWordsInASentence ()
{
String sentenceWithFourWords = "How are you today?";
Integer countFromString = wordCount.getWordCountFromString(sentenceWithFourWords);
assertTrue(countFromString == 4);
}
@Test
public void testThatNullValueForSentenceReturnsZero ()
{
// Arrange
String sentence = null;
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
219
// Act
Integer countFromString = wordCount.getWordCountFromString(sentence);
// Assert
assertTrue(countFromString == 0);
}
}
This time when we run our two tests, the first one still passes, but the second one fails. This is what we
were hoping for, as our goal was to write a failing test. So when we take a look at why our test failed,
we see that its a NullPointerException:
This is happening because when we pass in null as an input to our method, it will try to invoke
sentence.split( ), but sentence is null, so we get a NullPointerException. The key thing to
remember here, is that when you try to invoke null (dot) anything, you get a NullPointerException.
So now we repeat step 2, which is to write the minimum amount of code to get our tests to pass, like so:
public class WordCount
{
public Integer getWordCountFromString(String sentence)
{
if (sentence == null || sentence.length() == 0)
return 0;
String[] stringArray = sentence.split(" ");
return stringArray.length;
}
}
With this new code, the tests will pass! Now we can perform step 3, refactoring! By the looks of it we
have a validation step at the beginning of our method that will make sure to handle some special
situations (like when the sentence is null or empty). I think that looks a little ugly and we can probably
use our refactoring tools to extract a method from this. So lets do that!
public class WordCount
{
public Integer getWordCountFromString(String sentence)
{
if (isInvalidString(sentence))
return 0;
String[] stringArray = sentence.split(" ");
return stringArray.length;
}
private boolean isInvalidString(String sentence)
{
return sentence == null || sentence.length() == 0;
}
}
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
220
As you can see above, weve extracted the validation stuff out into a method called isInvalidString()
which will return true or false. If its true, then we return a 0 Integer, otherwise we allow our
processing to continue. And upon running of the tests again, we see that we still have a green bar (all
our tests pass). Excellent, lets repeat our TDD steps.
Our next requirement is to count the number of times a particular word appears in a sentence. This
sounds like a great time to use some Collections, perhaps a Map will suite our needs. Lets first write a
failing test for this situation:
WordCountTest.java - snippet
@Test
public void shouldReturnACountOf3ForWordIn ()
{
// Arrange
String sentence = "This sentence is designed to have a few repeating words in it, "+
"like the words is, as well as in, and the word words. As you can see I have also "+
"included a fair number of spaces in here as well, so we should make sure we don't "+
"include the space as part of a word that repeats!";
// Act
Integer countFromString = wordCount.countNumberOfTimesAnIndividualWordAppears(sentence,
"in");
// Assert
assertTrue(countFromString == 3);
}
WordCount.java - snippet
public Integer countNumberOfTimesAnIndividualWordAppears(String sentence, String wordToCount)
{
return 0;
}
Now, as you can see, this test has a nice lengthy sentence to test. Our test just calls a new method that
passes in our sentence as well as the word we wish to count. This test will fail, as we expect to see three
occurrences of the word in, and the default implementation weve created just returns 0.
Lets move onto step 2 and make sure our tests pass:
public Integer countNumberOfTimesAnIndividualWordAppears(String sentence, String wordToCount)
{
if (isInvalidString(sentence))
return 0;
sentence = stripAllNonAlphaCharacters(sentence);
int count = 0;
int position = 0;
wordToCount = " " + wordToCount + " ";
while (sentence.indexOf(wordToCount, position) != -1)
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
221
{
position = sentence.indexOf(wordToCount, position) + 1;
count++;
}
return count;
}
private String stripAllNonAlphaCharacters(String sentence)
{
return sentence.replaceAll("[^a-zA-Z ]", "");
}
This new code will now enable our tests to pass. You may look at this code and scratch your head
wondering what this stripAllNonAlphaCharacters method does. Rightfully so, this method is using
the replaceAll() method which makes use of regular expressions. What this does is essentially look at
all the characters in our sentence, and if the character is not the letters a through z, or capital A through
Z (or a space character) then it will replace that character with a blank space. I did this so that I could
remove all the commas, periods and any other punctuation in the sentence. This is needed in order to
properly match whether or not we have found an instance of our wordToCount (which in this case is
in).
I also make use of the indexOf() method, which will search a String and return the numeric position of
the String that youre searching for. If you like, try to debug this code and follow how the position
variable changes each time it iterates through the while loop.
And finally what must we do now? Im sure youve guessed it, we do step number 3, which is
refactoring. Im sure by now you get the idea here. So congratulations, youve read through and
(hopefully) understood the concepts behind this thing we call Test Driven Development. Its something
that I simply love doing, because it gives me absolute confidence in my code and allows it to be
modified with confidence as well! Very powerful stuff in the real world
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
222
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
223
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
224
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
225
Spring Framework
Hibernate
MySQL
HTML
Javascript
Now, all of these technologies could have a book written about them individually, so the scope of this
eBook will be to show you how they are actually used in practice and to teach what you need to know to
get the job done. Having said that, heres a quick breakdown on each technology so you are not
completely lost!
Spring Framework
This is used as a means to make our lives easier when we create web applications. The Spring
Framework is not required to build web applications, but it helps make the code neater and
automatically enforces the use of design patterns.
Note: If you dont already know, think of a design pattern as a best practice. Over the course of
programming, certain best practices have shown themselves as being advantageous to follow; these best
practices have been formed into whats now called design patterns.
The main purpose of the Spring Framework is to reduce coupling of your objects and make use of the
MVC (model-view-controller) design pattern.
Whats Coupling?
When two objects are tightly coupled, it means that one is dependent on the other (or worse, theyre
both dependent on each-other). An example of this can be seen when one Object is instantiated inside
of another Object:
public class User
{
private String username;
private String password;
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
226
Here we see that the UserAddress object is instantiated inside of the User object. Also, the User has a
method that returns its address. Now lets imagine that a developer decides that they want to change
the implementation of UserAddress, and they dont want to have a getAddress() method anymore.
This will now break the User class. This is what coupling is all about, and its not a good thing! If we
change one Class, we dont want to run the risk of breaking a bunch of others without realizing it.
The Spring Framework provides a clever solution to ensure that the coupling between Objects is
reduced considerably.
Whats the MVC design pattern?
As mentioned earlier, the Spring Framework makes use of design patterns (best practices). One such
pattern is the MVC (model/view/controller) design pattern. This design pattern (best practice) is all
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
227
about separating your concerns. Its considered good practice to separate the actual user interface code
(presentation layer) from the other aspects of your coding (business layer / data layer). When you keep
the presentation layer separate from your business layer and data layer, it allows you to swap out
your presentation layer framework code with another framework (if you so choose). The same goes for
keeping your data layer code separate from the other layers, it allows you to more easily swap out the
back-end of your application if the need arises. I have personally had to do both of these swaps
before, so I can attest to this layering approach being a good practice.
In the Spring Framework, you will see the use of Controllers, these are part of the presentation layer and
act as the middle-man between the view and the model.
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
228
Hibernate
Hibernate is a framework technology that takes (most of) the need to know SQL out of the equation. It
allows you to design your entire data layer in terms of Java objects with the use of annotations. Though
its not the easiest framework to use, the internet is bursting with tutorials on the subject of Hibernate.
Here is one that I used when I learned this framework:
http://docs.jboss.org/hibernate/annotations/3.5/reference/en/html_single/
Learning the ins and outs of Hibernate is not required, but it will help you in the long run if you wish to
create web applications as part of your career! The examples you see in this eBook with hibernate will
be well documented, so no worries!
MySQL
This is the Relational Database Management System (RDBMS) that we will use as our database. Its a
free RDBMS and its very popular, which also means its well supported and documented on the
internet, just like Hibernate. Refer to Chapter 6 of the How to Program with Java eBook to see details
on how to install this on your computer.
HTML
HTML stands for HyperText Markup Language and this is the standard by which webpages are created.
One thing you should remember is that HTML is not actually a programming language by any means; its
simply a syntactical structure of text that browsers read and then spit out a webpage. HTML is nice in
the sense that its easy to learn and doesnt require an IDE, you can create a website using just Notepad
if you so desire. Heres a quick example of an HTML page:
<html>
<head>
<title>This is the title - it appears in your browser's tab</title>
</head>
<body>
This is the actual content of the website. This text will just appear as standard black
text on a white background.
</body>
</html>
Thats it ladies and gentlemen. You just copy/paste that code into any file (so long as its a .html file)
and youll be able to open it with a web browser. Simple right?
JavaScript
JavaScript can be thought of the spice that is used in HTML to give it some flavor. JavaScript (a.k.a. JS) is
what is used to make HTML websites more interactive. JS can be used to show alert boxes to users on
webpages, it can be used to change the content of a webpage dynamically. Lets say for instance we
want to display a greeting to a user when they navigate to our website. We can use JavaScript to
prompt the user for their name, and then change the webpages title to say Hello <your name>, where
<your name> is replaced with the actual name that they type in.
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
229
JavaScript is often used as the first line of defense when validating common user inputs, such as filling
out a registration form for a website (ie. First name, last name, email address etc.). JavaScript can check
and make sure everything is in order before we actually send all that information off to our database!
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
230
The Software
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
231
Getting Started
Now that youve got some idea of what components make up a web application, lets make sure youve
got all the tools you will need to actually create your first web application!
When this eBook was published, the MySQL Connector version 5.1.22 was available, so
just choose to download the ZIP version.
When I clicked to download the file, it asked me to login, but theres a link that says No
thanks, just start my download!, this will get the file into your hands ASAP.
Once youve downloaded the ZIP file, open it up (I use 7-Zip) extract the JAR file to a directory of your
choosing (I prefer to keep it with my actual Java application files, but its up to you). For the record, the
JAR file you should be looking for should look something like this: mysql-connector-java-5.1.22bin.jar.
Okay, were nearly there, we HAVE the file we need, now we just need to tell our Java application where
to find it. This will mean we need to add this JAR file to the applications classpath. To do that, you
must:
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
232
Go to your Springsource ToolSuite (STS), right-click on the project that youve been working in
(in the screenshot below, its the HowToProgram folder). Heres what my project structure
looks like:
Choose properties
On the left hand side of the window that appears, click Java Build Path.
In the Libraries tab, click Add External JARs.
Choose the JAR file that you downloaded and extracted.
Now you should see something like this:
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
233
Excellent, if youve made it this far, then youre in great shape. That was the annoying setup part thats
associated with databases, you should really only have to do that whole process once.
Step 2: Download and Install the MySQL RDBMS
This process is a little more involved than just grabbing a file and unzipping it. So Ive created a video
tutorial that will help you through this step of the process. Just follow this link:
http://youtu.be/DQUlyZAuJww
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
234
Spring ROO
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
235
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
236
Appendix
Java Tests
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
237
Test #1 - Variables
1. Write code below that would declare an int variable called myInteger and initialize it with the
value 500 in one line.
2-2
null
0
java.lang.NullPointerException
3. If you were going to instantiate an integer variable with the name 'i' and assign a value of 19, what
code would you use?
int i = 19
integer i = 19;
i int = 19;
int i = 19;
4. If you were going to instantiate a String variable with the name 'myName' and assign a value of
Trevor Page, what code would you use?
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
238
""
0
null
1
2-2
null
0
java.lang.NullPointerException
-1
0
1
null
8. If you need to store this data: -498.09813 what variable type would you use?
String
double
int
string
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
239
9. If you need to store this data: Trevor Page what variable type would you use?
String
int
double
string
10. Given that you want to store the value 382.28, write the code below to declare a variable called
myValue and assign the given value to the variable (in one line)
12. Given that there's a String declared as message, write the code that will output this variable to
the console.
13. If you need to store this data: 58 what variable type would you use?
String
double
int
float
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
240
14. Given that you want to store the value "This is a message", write the code below to declare
a variable called message and assign the given value to the variable (in one line)
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
241
Never
3. How do you combine conditions in a control structure? (i.e. age is less than 20 and greater than 12)
4. Write the code to create a for loop that will iterate 10 times with the int i variable, starting at 3
and incrementing by 2 with every step.
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
242
system.out.println();
System.out.print()
printBlankLine();
System.out.println();
if ()
when ()
for ()
while ()
8. Create a while loop that will keep looping while age is greater than 13 and age is less than 20.
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
243
10. Write the code for a while loop that keeps looping so long as age > 19
Never
if (age = 20)
if (age == 20)
if (age equals(20))
13. What variable type would I use to store this data: "My birthday is January 1st"
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
244
int
double
char
String
From bottom to top and (for the most part) from left to right
From top to bottom and (for the most part) from left to right
15. Write code below that would ask if age is greater than 19.
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
245
18
28
504
3. Create a nested for loop. The outer loop should iterate from 0 to 9 (10 iterations) using varible i.
The inner loop should iterate from 0 to 14 (15 iterations) using variable j
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
246
4. Given this code: while (true) {} - Choose which statement is the most correct:
This code is syntactically correct and is the foundation for the while loop
5. Instatiate a Calendar variable named cal and assign/set its date to March 3rd, 2013
6. How many times would this code execute the System.out.println() statement in this for
loop?
551
28
504
18
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
247
8. Create an outer while loop that will iterate while age is less than 20, and create an inner for loop
that will iterate 5 times with variable int i from 0 to 4
The while loop keeps looping until the condition is evaluated to true
The while loop keeps looping until the condition is evaluated to false
The while loop only iterates a certain number of times, then it stops
10. What is the correct order of the three expressions in a for loop?
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
248
13. What is the resulting value of the date variable? Date date = new Date();
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
249
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
250
integerArrayList[1];
integerArrayList[0];
integerArrayList.get(1);
integerArrayList.get(0);
2. Given that you have an instantiated ArrayList called myList that stores Strings, how would
you put a new String with value "My String" into myList?
3. What code is used to instantiate a HashMap with a String as the Key and a List of Strings as
the value?
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
251
4. Write an if statement that will evaluate to true if an ArrayList called myList has data in it.
5. Which statement is most correct with respect to the difference between Arrays and ArrayLists?
6. Write the code to retrieve the first element from an ArrayList called myList
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
252
Storing Lists
Storing Arrays
9. Given the fully populated Array intArray with 10 items, what would happen if you executed this
code: intArray[10]?
10. Write the code to instantiate an ArrayList called myList that will store Integers.
11. Write the code to instantiate a HashMap called myMap that will store an Integer as its key and a
String as its value.
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
253
12. If I wanted to declare an Array of ints, what would that look like?
[5]int array;
int[] array;
int array[5];
int[5] array;
13. Given you have the ArrayList integerArrayList, how do you insert new objects into this
ArrayList?
integerArrayList.add(1);
integerArrayList[1];
integerArrayList.put(1);
integerArrayList(put);
14. Given that we've declared an Array (int[] intArray), but haven't instantiated it, what code
would we need to write before we could use the Array?
intArray[3];
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
254
15. Given the fully populated Array intArray with 10 items, how would you retrieve the 4th item in
the Array?
intArray[3]
intArray[4]
intArray.get(3)
intArray.get(4)
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
255
Test #5 - Primitives
1. How could the number 239 be assigned to an int
0.0
0L
0i
0.0d
int
float
Boolean
double
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
256
4. Write the code to declare a primitive BOOLEAN called myBoolean with the value false
0.0d
0.0f
0L
6. Write the code to declare a primitive DOUBLE called myDouble with the value 1.0
7. Write the code to declare a primitive INTEGER called myInteger with the value -50
8. If you do not initialize an Integer data type, what is the default value assigned to it?
null
nil
0i
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
257
10. Given that you have a non-primitive INTEGER named myInteger, and you need to assign its value
to a String called myString, how would you accomplish this in one line of code?
Integer.parseInt(myString);
myString.getInteger(myInteger);
myInteger.toString();
Integer.getString(myInteger);
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
258
13. Which of the following data types would not allowed to be used in an ArrayList?
Integer
double
Double
String
14. Write the code to declare a primitive FLOAT called myFloat with the value 549.54
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
259
Test #6 - Methods
1. Given the following code, how would make use of the boolean return value?
isUserTpage == isValidUsername("tpage");
boolean isValidUsername("tpage");
3. Create a public setter method (with an empty body) named setUsername which takes one
String argument (username) and returns nothing.
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
260
4. Create a public method (with an empty body) that returns a boolean called isValidData that
takes two arguments (String username, Integer count)
It is best to keep all of the programming code within one method for readability
Using methods allows us to re-use code, thus allowing for robust code
6. Write the code for the Java main method (the method that flags the starting point of a program in
Java).
7. How would you create a method that takes NO parameters, returns NOTHING, with the name
myMethod
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
261
8. When using the keyword private to create a method, what is the visibility of that method?
The method is visible to any class other than the one it was created in
10. When looking at the declaration of the main method, what do you now know about it?
11. Create a public method (with an empty body) named getUsername which takes no arguments
and returns a String
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
262
12. How would you create a method that takes a String parameter, returns a boolean, with the
name myMethod
13. How would you declare a public method that takes a String and an Integer as parameters?
14. When using the keyword public to create a method, what is the visibility of that method?
The method is visible to any class other than the one it was created in
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
263
2. Write the code to create the class User (assuming you don't need imports, package declaration or
body)
A variable defined in a class for which each Object has a separate copy
A variable defined in a class for which each Object has the same copy
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
264
Allows for insertion of validation when retrieving and modifying values of variables
Allows us to inject some flexibility into retrieving and modifying values of variables
6. When we declared the User Object, why are we able to access methods that we didn't create (like
the toString() method)?
7. How would you create a static String instance variable named myString?
Everything
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
265
9. Write the code (according to Java conventions) needed to create the setter method for the instance
variable: private String username
11. Given that you had the Class User and the static variable securityLevel, how would you
reference the variable from another Object?
new User().securityLevel;
User().securityLevel;
User.securityLevel;
securityLevel();
12. Write the code (according to Java conventions) needed to create the getter method for the instance
variable: private String username
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
266
A variable defined in a class for which each Object has a separate copy
A variable defined in a class for which each Object has the same copy
14. When reading requirements and deciding what Objects to create, what should you look at?
Verbs
Nouns
Pro-Nouns
Adjectives
java.lang.Integer
java.lang.String
java.lang.Objects
java.lang.Object
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
267
Test #8 - Inheritance
1. What main benefit does the abstract class have over the interface?
There is no benefit
2. Write the code to define a Vehicle interface that doesn't define any methods. (Assuming no need
for imports or package definition)
3. What main benefit does the interface have over the abstract class?
There is no benefit
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
268
5. Write the code to define the class SportsCar which is a sub-class of the Car class. (No need for
imports, package declaration or body)
6. When you use an abstract class, which of the following statements is true?
7. When you override the equals method, it's recommended that you also override which method?
toString()
wait()
notify()
hashCode()
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
269
You can implement as many interfaces as you wish, but you can only extend one class
You can extend any number of classes you wish, but can only implement one interface
10. Which annotation do you use when you wish to implement a method in a child Object that is
defined in a parent Object?
@Overload
@Overthere
@Override
@Overunder
11. If a super class defines a method, and a child class overrides this method but wishes to also use the
parent class's functionality, what keyword would you use?
parent
super
child
class
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
270
12. In order to ensure that Java doesn't just compare memory locations when comparing two objects,
which method should you implement?
hashCode()
override()
overload()
equals()
13. Write the code which defines the class Person that is a sub-class of the User abstract class.
(No need for imports, package declaration or body)
14. Write the code to create the Car class, which contracts the use of the Vehicle interface. (No
need for imports, package declaration or body)
15. How would you create an abstract User class? (Assuming you don't need any imports, package
declarations or body)
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
271
Test #9 - Exceptions
1. When you place code in the finally block, the code should not be time sensitive, why is this?
It is not guaranteed that the finally block will execute exactly when the try block has executed
It is not guaranteed that the finally block will execute at all when the try block has executed
This can hog system resources and adversely affect the code outside the try/catch block
This statement is false, you can and should place time sensitive code in the finally block
3. If there is NO error thrown in a try/catch block, how does the code flow?
Into the catch block only (if one exists) and then continue outside the try/catch
Into the finally block only (if one exists) and then continue outside the try/catch
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
272
4. There are two keywords that have to do with handling Exceptions, what are they?
try, fail
throw, catch
lob, catch
fail, throw
6. Create a standard try/catch block that will catch Exception e. (no code needed in the body of
the try or catch blocks)
7. If you wanted to handle two types of exceptions in one try/catch block, how would you go about
doing this?
You cannot handle two separate types of exceptions in one try/catch block
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
273
Checked
Unchecked
Compile
Failed
Checked
Unchecked
Compile
Failed
10. How would you define a public method named validatePassword which throws the generic
Exception type? (Given that the method returns nothing and takes a String password
argument)
11. Why is it recommended to declare your variables outside the try/catch block?
Your variables won't otherwise be accessible in the catch and finally blocks
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
274
12. Exceptions can be broken down into two categories, what are they?
13. If there is an error thrown in a try/catch block, how does the code flow?
Into the finally block only, the code will skip the catch since there was an exception
Into the catch block only, the code will skip the finally since there was an exception
Into the finally block if one exists, then into the catch block that matches the thrown exception
Into the catch block that matches the thrown exception, then into a finally block if one exists
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
275
"This is a st sentence."
"This is a st sennce."
removeString()
truncate()
substring()
parseString()
3. Given the String "This is a test sentence.", when using indexOf("test") what is
the resulting value?
10
11
-1
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
276
4. Given two strings (String myString, String mySecondString) write the code that would
concatenate these two strings together and assign the result to another variable called result (don't
forget to define the result variable)
5. Write the code that would output a message to the console stating "Your name is " and then
concatenate the variable name to this message.
6. How do you remove whitespace (leading and trailing white space) from a String?
trim()
replace()
removeWhitespace()
shrink()
7. Given the String "This is a test sentence.", when using indexOf("tests") what
is the resulting value?
10
11
-1
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
277
string1.equals(string2);
string1 == string2
string1 = string2
"string1" == string2
9. Write the code to fabricate an if statement that will check if the myString variable contains the
word "fox". (no code needed in the body of the if statement)
\\t
\\n
\t
\n
11. If we needed to change all occurrences of a particular String within another String, what
method would we use?
replace()
searchReplace()
findReplace()
restore()
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
278
12. If you have a User object defined and wish to print the contents to the console in a human readable
way, what must you do?
System.out.println("User")
String manipulation
String overriding
String concetenation
String overloading
14. Write the code to assign the following String literal to a String variable called myString:
"This is a sentence
with a line break inside of it!"
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
279
@Overload
@override
@Override
@Overide
2. Let's say you're given an int, but your code requires a double, what must you do to appropriately
convert your value?
convert
deploy
cast
transform
3. Overriding can only happen when you have a ______ and ______ class
parent, super
super, child
super, private
private, public
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
280
4. When is it always legal to cast? ie. when you are guaranteed not to get a ClassCastException
rightcast
downcast
leftcast
upcast
Overriding has implications for Inheritence, Overloading has implications for Polymorphism
Overriding is part of Java 1.5, but Overloading was introduced in Java 1.1
Overriding allows you to change behaviour at compile time, Overloading is done at runtime
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
281
7. Given the variable Object myString, how would you define a String anotherString
variable and assign myString to it?
8. Given the method boolean isAnAnagram(String word1, String word2), how would
you overload this method?
9. Overloading allows us to define two or more methods within the same ______ that share the same
______
Class, name
method, name
package, name
package, Class
10. The compiler does not consider _________ when differentiating methods
arguments
return types
method names
method signatures
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
282
11. When overriding a method, both the ______ and the ______ have to match
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
283
insert()
add()
pop()
put()
2. Write the code that is needed to instantiate an ArrayList called myArrayList which stores
Strings (remember to program to an interface)
interface, implementation
implementation, interface
object, counterpart
collection, counterpart
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
284
remove()
pull()
delete()
destroy()
7. With respect to multi-threading, the ArrayList is _______ and the LinkedList is _______.
synchronized, synchronized
9. What is the main reason why inserting elements into the middle of a LinkedList is faster than
with an ArrayList?
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
285
counter
index
hashmap
counter
index
hashmap
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
286
12. Write the code that is needed to instantiate a LinkedList called myLinkedList which stores
Integers (remember to program to an interface)
13. What's the main difference(s) between the List and Set collections?
14. How do you write a "for each" loop to iterate through an ArrayList of Strings called
myArrayList (assigning each element to the variable item)
15. Given you have a LinkedList called myLinkedList, how would you insert the String "An
element" into it?
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
287
sorted
Strings
unique
numeric
3. Write the code to declare and instantiate a TreeSet called myTreeSet that stores Strings.
(Remember to program to an interface)
4. Write the code to declare and instantiate a HashMap called myHashMap that stores an Integer
for a key and a String for a value. (Remember to program to an interface)
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
288
5. Write the code to declare and instantiate a HashSet called myHashSet that stores Integers.
(Remember to program to an interface)
6. Write the code to retrieve the value from myHashMap given key 100.
HashSet
LinkedHashSet
TreeSet
HashTableSet
The Set ignores the duplicate value and the add method returns false
The Set replaces the existing value with the new value and returns true
The Set allows the duplicate to be inserted, but the add method returns false
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
289
10. Just like the ArrayList and LinkedList, the default implementation of Sets and HashMap
we looked at ________________.
11. What happens when you insert a duplicate key into a HashMap?
the HashMap will ignore the newly added key/value pair and leave the existing entry
the HashMap replaces the existing key/value pair with the newly added key/value
12. If you would like to insert an Object into a Set, which method would you use?
add
put
insert
place
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
290
HashSet
LinkedHashSet
TreeSet
HashTableSet
14. If you would like to insert an entry into a HashMap, which method would you use?
add
insert
place
put
15. What are the main differences between a Set and a List?
HashSets use the 'put' method whereas Lists use the 'add' method
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
291
j = j + 1;
j++;
j+=;
j=+
2. If you have the variable myVariable that could potentially be null, how would you safely invoke
its equals method?
if (myVarible.equals("something"))
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
292
5. Write an if statement that checks to see if two ints (int1, int2) are not equal.
true
false
k--;
k = k - 32;
k-=32;
k-32;
8. How do you compare if the values of two ints are equal to each other?
a == b;
a = b;
a.equals(b);
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
293
true
false
10. Write the shortcut code for incrementing the int i by 10.
11. How would you ask if two int values are NOT equal to each other?
a <> b
a not b
!a.equals(b)
a != b
12. Write the code to create an if statement checking two ints (int1 and int2) for equality.
13. Write the code to create an if statement checking two Integers (integer1 and integer2)
for equality.
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
294
14. How do we properly check if someone is a teenager (assuming the values will always be positive int
values)?
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
295
2. Given the Class HumanBeing, what is the proper way to execute a constructor from inside another
constructor?
this.HumanBeing();
HumanBeing();
this();
3. Create the setter method (using standard Java conventions) for the instance variable private
String username
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
296
true
false
6. What happens when you don't qualify one of the variables inside of a typical setter method?
Nothing happens
7. Can you use the this keyword to get a reference to a static Object?
Yes
No
8. What's the reason we use the this keyword in a typical setter method?
It's actually not a good practice to use the 'this' keyword in a setter
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
297
9. Create a private two-argument constructor for the User class that takes String username,
String password (with nothing in the body)
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
298
Test #1 Answers
1.
int myInteger=500;
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
System.out.println(message);
13.
14.
Test #2 - Answers
1.
2.
3.
4.
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
299
5.
6.
7.
8.
while (age > 13 && age < 20){} OR while (age >= 14 &&
age <= 19){}
9.
10.
11.
12.
13.
14.
15.
if(age>19){} OR if(age>=20){}
Test #3 Answers
1.
2.
3.
for (int i=0; i<10; i++) { for (int j=0; j<15; j++) {
}} OR for (int i=0; i<=9; i++) { for (int j=0; j<=14;
j++) { }}
4.
5.
6.
7.
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
300
8.
9.
10.
11.
12.
13.
14.
Test #4 Answers
1.
2.
myList.add(My String);
3.
4.
5.
6.
myList.get(0);
7.
8.
9.
10.
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
301
11.
12.
13.
14.
15.
Test #5 Answers
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
myString = myInteger.toString();
11.
12.
13.
14.
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
302
Test #6 Answers
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
Test #7 Answers
1.
User.validateUser();
2.
3.
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
303
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
Test #8 Answers
1.
2.
3.
4.
5.
6.
7.
8.
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
304
9.
10.
11.
12.
13.
14.
15.
Test #9 Answers
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
305
13.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
306
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
2.
3.
4.
5.
myArrayList.remove(1);
6.
7.
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
307
8.
9.
10.
11.
12.
13.
14.
15.
myLinkedList.add(An element);
2.
3.
4.
5.
6.
myHashMap.get(100);
7.
8.
9.
10.
11.
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
308
12.
13.
14.
15.
2.
3.
4.
i++;
5.
if (int1 != int2) {}
6.
7.
8.
9.
10.
i += 10;
11.
12.
13.
if (integer1.equals(integer2)) {} OR if
(integer2.equals(integer1)) {}
14.
15.
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
309
public User () {}
2.
3.
4.
5.
6.
7.
8.
9.
http://javavideotutorials.net
Prepared exclusively for Shaban Rahman ([email protected]) Transaction: 0004950535
310