Vous êtes sur la page 1sur 80

Pluralsight

Dashboard
Browse
Learn By Doing
Recently Viewed

Java Fundamentals, Part 1


R Programming Fundamentals
Introduction to the Bash Shell on Mac OS and Linux

Account
Bookmarks
Playlists
Transcript

Mobile Apps
Support & Feedback
Business Plans
Authors
Teach
Learning Paths
Blog
Contact

Terms of Use
Privacy Policy

Sign Out

sw Swathi.Patibandla@misys.com
Java Fundamentals, Part 1

by John Sonmez

This course is designed to teach you Java whether you are an experienced
programmer or just getting started.
Resume Course

Table of contents
Description
Transcript
Exercise files
Discussion
Learning Check
Recommended

Introduction to Java
Course Overview

Hi. This is John Sonmez from Pluralsight, and welcome to the course on Java
Fundamentals. This is part one of the Java Fundamentals course and in this
course, we are going to be learning about that programming language called
Java. So let's go over what we're going to cover in this course. Well, this
course is basically meant to be an introduction to Java. And by introduction,
what I mean is that it is both applicable to a beginning programmer -- so
someone who's really never programmed before. I'm going to teach you from

the beginning some of these core programming concepts, but teach you
them in Java, or just someone who's new to Java. And some of the concepts
are going to similar to what you've seen in other programming languages,
but I'm going to show you how to do the things that you may already know
how to do in Java. So really, either one of these categories is going to be able
to benefit from this course. We're not going to go too much into the details or
advanced Java. So even someone who is somewhat experienced with Java
would probably be able to benefit in filling in some gaps and some
understanding of the Java language, because Java is fairly big. Also this is at
two-part course, so this is the first part, and in this part, we're going to really
cover more of the basics. And then in the second part, we're going to get into
some of the more of the advanced stuff here. And really, what we're going to
cover in this course is the language. We're going to cover a little bit of some
of the class libraries that are out there for doing mainly things like File I/O and
a couple of the other areas where it's important to know just to be able to
function in Java. But the basic goal of this course is to make it so that you
would be able to program in Java and be productive using the Java language.
Now, to really be a Java developer or to really succeed as a Java developer,
you'll have to learn a little bit more of the platform and some of the
technologies. But by the end of this course, you should definitely be able to
write some Java code and understand, really, the depth of the entire
language. We're going to cover, within the two parts, really the whole Java
language. And, you know, Java is huge. We're not going to cover every single
bit and every part of Java and because Java is more than just a language -it's all these libraries. It's a lot of technologies and this entire platform, we
won't be able to cover that entire thing. But like I said, at the end of this
course, you should be able to program in Java and really have a good grasp of
the language. So here are some of the topics that we're going to cover in this
course. The first thing that we're going to do is talk about Java in general. Just
a brief introduction to what Java is, just some "Hello World" programming to
get us started and to really break the ice with Java. Then we're also going to
talk about variables and operators. How to use the variables, declare
variables, types and what kind of operators are available in the Java
programming language. We're going to go into classes. I'm going to show you
how to construct some classes and objects and how to use them and how
that is done inside Java. Then we're going to go into control statements.
These are going to be "if" statements, loops, all these contracts that allow
you to have conditional logic inside of your code. Then we're going to go into
a little bit more of a complex topic of inheritance and composition. I'm going
to show you how to do inheritance in Java and how it works. And then how to
also do composition. And it's okay if you don't understand what these terms
are now. We're going to cover these in these modules. And then finally, we're
going to go into generics, which is basically a way in Java for you to be able
to reuse a lot of your code, to make it applicable to different types. And so

this is really what we're going to cover in the first part, like I said. The second
part of the course, the second course, we'll actually cover some more
advanced topics and we'll get into things like doing File I/O and threading and
things that are a little bit more advanced.
Introduction

So in this module, we are going to be introducing Java. We're going to talk a


lot about what Java is and how it works, and we're going to go through some
things to get you just familiarized with Java in general and some of the
tooling that we'll use in order to develop a Java application. So let's go over
what we are going to cover in this module. The first thing that we're going to
do is talk a little bit about Java. What is Java? How does it work? A little bit of
the background and history of Java. Then we're going to introduce a really
important concept in Java, which is the JVM, the Java Virtual Machine. I'm
going to talk a little bit about virtual machines in general and how they work,
so you can understand what's going on here. And then specifically, how the
JVM works or what the JVM does and what benefit it gives you as a Java
Programmer. Then we're going to go ahead and we are going to write up a
"Hello World" program. We're going to write this program. We're going to
compile it. We're going to talk a little bit about the parts of it and how it
works, so you can understand what the basic, simplest program that you can
write in Java is. Then we're actually going to start to look at some IDEs. And
the main IDE that we're going to use in this course is Eclipse. So I'm going to
show you where you can get Eclipse and download it and install it and some
basic features of Eclipse. We're not going to go very in depth into all the
features of Eclipse, but I'm going to show you what you're going to need to
know in order to participate in this course. And then I'm going to show you
IntelliJ. And we're not going to use IntelliJ in this course. We're going to use
Eclipse. Both of these are really good products. Either one of them is fine for
doing Java development. I'm just choosing Eclipse because there's a little bit
of a bigger audience out there for Eclipse. There's a little bit more usage of
Eclipse, I think, in general. And IntelliJ is a little bit more advanced. I think a
lot of beginning Java developers are first going to be drawn towards Eclipse.
And so I'm going to show you that. But I'm not giving a personal preference of
one or the other. And then we're going to look at packages, which is a very
important concept in Java for separating things out and to be able to put your
content into different areas so that you can organize your code. And then,
finally, we're going to talk a little bit about the Java class libraries. I said
Java's big, and in this section, you'll see just how big Java is as we start
talking about all the things that exist in the Java platform.
About Java

So let's talk about Java. What is this Java programming language? It was
initially based off of C and C++. If you start to look at the syntax and the Java
source code, you'll notice that Java looks a lot like C or C++. It's very similar
in a lot of the constructs, a lot of the way that you program it is very similar.
It's basically designed to be written once and run anywhere. What that means
is that you should be able to write your source code in one place and, in fact,
compile it, and that compiled code should be able to run on any operating
system that has a Java Virtual Machine. And that's kind of been one of the
design goals of Java. And it's also one thing that makes it really unique as a
programming language. It runs on a virtual machine. If you're familiar with
C# and .NET, Dot also runs on a type of virtual machine. The Java Virtual
Machine is designed to be cross-platform, but Java is basically a language
designed to run inside a virtual machine. As I said, it's similar to C#. It's going
to be -- a lot of the language constructs, you're going to see an exact mirror
in C#, if you're familiar with C# and vice versa. So a lot of what you can do in
Java is what you can do in C#. C#'s probably a little bit bigger, as a language,
in terms of what you can do in Java, so Java's got a little bit of catching up to
do. But Java is a very robust language. Java is object-oriented. That means
that the main focus of the development is to classify things, to organize them
into classes and objects. And Java is statically typed. It is not a dynamic
language. It is almost a dynamic language in the fact that it is compiled on
the byte code and that byte code is interpreted, so it is technically an
interpreted language, but it is statically typed. It's statically compiled. The
compiler looks at the types and the types are defined in the source code
when it's compiled. And really, one important thing to know about Java is that
it's a platform. It's not just a language. So when you're talking about Java and
you're talking about the features and you're comparing Java, really, it's all of
the things that Java encompasses, from databases to security to File I/O to
network and all the platforms involved. So Java is really just a huge platform
of technologies, where the language is kind of the central part of that
technology. So let's go through some history of Java. It's a language that was
developed by James Gosling at Sun Microsystems. So that's where it was
born, essentially. It was released in 1995 and it was a drastic change. There
wasn't really a language like this before: a language designed to run on
multiple machines that runs inside a virtual machine. It was actually targeted
initially for interactive television sets, which was way beyond this time, in
1995, and then they got retargeted for the web, which seemed to be a pretty
good fit, especially with Netscape coming out and Netscape supporting Java
running inside of it through the use of applets, which we don't really see that
much today. If you look at the release schedule, you can see that there's
been a lot of releases of Java, and it's kind of been renamed and rebranded a
few times here. The big thing that happened was with the Java 5.0 release,

there was a lot of actual language changes. Before the Java 5.0 release, a lot
of the other releases really expanded the platform, added more features, but
the language changed in 5.0, so if you're working in some legacy Java code,
from 4.0 to 5.0 is where you'll see a lot of different changes. And in Java 7.0,
we've added a few more language changes, but nothing too drastic. And then
Oracle actually acquired Sun, which of course, was the originator of Java, and
so Oracle really is kind of the steward to Java nowadays.
The JVM

So let's talk about virtual machines. And one thing that you're going to want
to know is how a virtual machine works and what is a virtual machine. That's
really going to help you, in programming Java, to understand the concepts
that are involved in running your Java source code, running your Java
programs. If you look at this diagram here, you can see that I'm showing
several different operating systems and this could be -- you could have
Windows, Linux, Mac. You can think of those operating system blocks as those
operating systems or really any operating system. The top of them is a virtual
machine. This would be your Java Virtual Machine for Java and you can see
that each operating system has its own virtual machine. But if you look at the
top there, you have your Java source code. It gets compiled by a Java
compiler, and that compiled Java code can run on any one of those machines.
So basically, what's happening here is you're writing your source code once.
You're not doing any differences for the different platforms. And there's, of
course, some exceptions to this rule, but the design of this is intended to be
such that you write your source code once. In fact, you not only write it once
but you compile it once. This compiled Java code is actually interpreted. It's
like an assembly language for these virtual machines and the virtual
machines are acting to make the same thing work in the different ways that
operating systems handle things like files and networking. And so, really,
you're writing your code against these common Java libraries using the Java
language and the virtual machines are handling the differences, to produce,
basically, the same output on each operating system. That's the basic idea of
a virtual machine, is that it's virtualizing the operating system. It's virtualizing
your application so that it can run on any operating system and it doesn't
have to be written specifically for that operating system. And that's kind of
really the key advantage of Java. So a little bit more about the JVM. It's
basically an abstraction layer. We talked about how the virtual machine or
how our virtual machine basically lets you abstract away or run your
applications on multiple operating systems and have them run the same way
without having to create a different source code or do "ifs" inside your source
code, based on the operating system. You could just write your code in one
way and target against the Java framework and that the virtual machines

would handle doing that thing or rendering that view or rendering File I/O or
network operation for you, in that operating system. So it's an abstraction
layer, so that when you're programming in Java, when you're thinking in Java,
you're thinking about the Java framework and you're not thinking about what
operating system to target. The other important thing about the JVM is that it
doesn't run Java source code. It doesn't compile it. The Java source code is
compiled ahead of time. It's compiled into dot class files, which are basically
byte code, and byte code is nothing more than, really, an assembly language
for the Java Virtual Machine. So just like computers in x86, an Intel PC,
basically, would have its own assembly language, the Java virtual machine
has an assembly language, which is the byte code. And because of this, you
can actually run more than just Java in a JVM. There's a whole host of
languages that exists now that compile themselves down to Java byte code
and therefore could be run inside of the JVM. So really, this idea of byte code
is abstracting away, helping to abstract away the operating system so that
you can run on multiple operating systems. But it's also abstracting away, to
some degree, the programming language. And you'll see a similar thing if
you're familiar with .NET. It's a very similar concept, except .NET wasn't really
designed to go for different operating systems, but it does allow different
languages. The JVM does garbage collecting, and we're not going to go into
detail in garbage collection, but garbage collection is basically a way that you
don't have to manage memory yourself. And the JVM is really what's allowing
this to happen. As your code is being run and you're creating new objects and
you're asking for new memory, the garbage filter is running in the
background in the JVM, where you're application is running and is determining
which things are no longer being used, and it's freeing up that memory for
you. So this is a really important concept that a virtual machine provides to
you and that the JVM is doing so. If you're familiar with C++ and allocating
your own memory and freeing it up, Java frees you from having to do that.
And the other thing along with that, by running in a JVM, is you have some
safety. It's kind of a sandbox. A JVM is going to do things, like verify that the
code doesn't violate its memory or address spacing, that it's not going to be
able to just access some random part of the operating system. Things that
are running inside the JVM are sand-boxed. They have that safety because
the JVM's enforcing that safety, whereas if you're running just a native
program, there's nothing to stop you from overriding some memory location
that doesn't belong to you, unless the operating system itself has that
control. But inside the JVM, you're guaranteeing that safety.
Hello World

So let's go ahead and jump right into creating our first Java application. And
so what we're going to do is we're going to create a "Hello World" application,

the basic program that you create when you first learn a programming
language, just to show that we can actually compile and build our application
and we can print "Hello World" to the screen. Now, before we do this, what
we're going to want to do is to make sure that you have the JDK installed. And
in Java, you have a Java runtime environment, or the JRE, and a JDK, which
the JDK is for software developers. It has the compiler in there. So you need
to make sure you got that installed and downloaded. If you don't have it
installed, you can just search for JDK, and it should take you to Oracle's Java
SE downloads page. And here you can see the latest version is Java 7.0. You
can use Java 6.0, if you want, but I'd recommend just go ahead and grab Java
7.0 and you want to download the JDK and pick the appropriate version for
your operating system and run that. Once you have the JDK installed, what
you're going to want to also make sure that you have is that you have Java in
your path. And if we go into your environment variables on your PC, under
advanced system settings, you should see that you have a path here. And
what you're going to want to do is to make sure that Java 7.0, if you've
installed Java 7.0, is the first thing in your path. Because there may be
another Java executable that's under your System32, and the way that the
path works is that it picks up the first one that gets loaded of something, so
you want to put this into your path, so that you can compile from the
command line. And typically, you're going to find the Java install under your
program files -- Java, JDK 1.7 or 1.6, if you installed 1.6. -- and then bin. And
you just want to take that entire path and put that at the beginning of your
path, and then, of course, a semicolon at the end of that so that the rest of
the path can still work. Once you've done that, you can test this out to make
sure that you have it installed correctly by typing Java and then dash-version.
And you should see if you have Java 7.0 installed or 1.7, you should see that.
And you should also be able to test Java C the same way, to make sure you
have the correct version. Those should match. If they don't match, then
you've got a problem with your path. So what we're going to do here is we're
going to go ahead and create "Hello World" and I'm just going to do this in
Notepad, just to make this as simple as possible. And then we'll get into an
IDE a little bit later. So I'm just going to type notepadhelloworld.java. And
what we're going to do here is we're just going to create our Hello World
class, so we're going to create a class called Hello World. All Java programs
have to have a class. It's object-oriented. Everything has to be inside of a
class. So what we're doing here is we're just creating the basic class that our
main is going to live in. And if you're familiar with C or C++, virtually all
programming languages have some kind of entry point. Our entry point is
going to be a public static void method called main. And if you're not familiar
with these concepts, don't worry about it. I'll explain it later. If you are, then
this is the method that you need to create. Don't worry if the syntax is not
familiar to you. And we're going to take an array of arguments. These are
arguments that would get passed in from the command line. And then, from

inside here, we're going to do sytem.out.print line Hello World. And what this
is going to do, it's going to create a class, which is a basic modular unit that
we use to divide our program up. And then, inside there, there's a method
here, which is basically a set of instructions that the computer is going to
execute, and we have this special syntax, declaring it, and then inside here,
this is a method call that we are telling the computer to print the line "Hello
World." Let me fix that. So I'll go ahead and save this, and let's go ahead and
run this and see what happens here. Now, the first thing that we're going to
need to do is to compile this program. So I'm going to call JavaC, which is a
Java compiler, and I'm going to type helloworld.java. And now you can see,
it's compiled, because there's no errors here. And if we look in this directory,
you can see now, there's a helloworld.class file. And if I were to notepad this
helloworld.class file, you'd see it's not -- it's not very friendly for us to read.
This is the byte code for Java. This is what the JVM can understand. So now
we can actually run Java, which is basically running the JVM and we can type
helloworld -- not helloworld class, just helloworld. It will find it inside the class
path. It will be able to find our program and it will run that; it will use this
class as the main entry point and then it will run that main method. So let's
take a look real quick, one more time, at our helloworld.java file. And you can
see here, this is the basic skeleton of a program. You have to have a class, so
we've declared our class here. It's called helloworld. Inside here, we have to
have an entry point and our entry point is a public static void method named
main. It's okay if you don't understand what this is right now. We'll explain
that as we go further into the class. And then what we're doing inside our
method, is we're just printing out the text Hello World. So that's it. That's the
basic java program, the basic, most simple Java program that you can create.
And we're going to do the rest of this class inside the IDE inside of Eclipse.
Eclipse

So now that we've been able to compile a Java program, let's take a look at
the IDE that we're going to use for the rest of this course. You can go to
Eclipse.org, and then go to Downloads and then from here, you can download
the Eclipse IDE for Java Developers. And you can choose the 32-bit or 64-bit
version. Just make sure that which version you choose corresponds to the
version of the JDK that you had installed for Java. These have to match.
Otherwise, it's not going to work. So once you've downloaded this, you're
basically going to extract the contents to a folder. And you can see here that
I've got my Eclipse under Tools, Eclipse. You don't have to actually run an
install. You just can run the Eclipse.exe right from here. So I'll go ahead and
run this. And Eclipse is basically a free IDE. It is one of the older Java IDEs. It's
completely open-source and there's just a lot of plugins for Eclipse. When I'm
teaching someone Java or another programming language that can be done

inside of Eclipse, I typically use Eclipse just because there's so many plugins
for it. There is some many people who understand Eclipse. We're going to go
over another popular IDE and talk about that a little bit, called IntelliJ. Some
people might argue that IntelliJ is better or Eclipse is better. It doesn't really
matter because they're very similar and they can both do most of the
common features that you would expect in modern IDE. So whichever choice
that you like. If you want to follow along for this course, I'd recommend using
Eclipse, but you can use IntelliJ if you want. So let's take a look, a little bit,
about the features of Eclipse here. And I've got a program here that I've
loaded up, just as a demonstration project here. And you can see the way
Eclipse is divided up here. You've got a lot of things going on in Eclipse. It can
be a little bit confusing at first, but we're going to kind of learn this as we go
and kind of stick to the basics here. On this left-hand side, you basically have
what's called a package explorer. And I'm going to explain packages a little
bit more, later. But it basically allows you to navigate the source of your
application. In the middle here, you've got your main code window, and this is
where you can actually do your development. And Eclipse gives you full
IntelliSense support so you can hit dot and then you can see what your
options are on objects and methods. Really helps you to code. On the right,
you have an outline -- this is in the default Java view -- of the methods that
exist and you can jump to them. And then at the bottom, you have your
console. This would be where the Hello World would be displayed. And you
have some tabs here for problems and things like that. The basic thing that
you're going to do is work inside of the IDE here, inside of the text editor part.
And then you're going to compile and run your application. And one
interesting thing about Eclipse is that you don't actually have to continue to
build your application. So with Eclipse, you'll notice that this run -- you can
just run right away. You don't see a compile option here because I have built
"automatically checked." And this is really nice because it's always ready to
go. I can just click Run. And we'll go ahead and create a new project in Eclipse
so you can see how to do that. We just go to File, let me choose New, choose
Java Project. Then we give this a project name. We can call this Hello World. It
automatically should pick up your JRE, so that it knows what version of Java
you're using. Here, it's picked up 1.7. And then we can leave the defaults
here and click Next. So you could add libraries here, if we wanted to add
additional libraries or their source files. I'll just go ahead and click Finish here.
And now you can see, I'll close this other project that we had. Then you can
see we have our Hello World project here and it doesn't have anything in it.
We can easily add a file to our project by going to New and then Class and
then we can create our class. We can create a Hello World class and then
from here, we can create our method. And you can see, as I'm typing here, if I
type in SYS and hold down the Control key and hit the space bar, it's going to
give me some auto-completion here. And so this is kind of useful when using
Eclipse. You can just select System here. And when I hit Dot, it's also giving

me auto -completion. And again, with the print line, I can always hold down
Control and hit Space. You'll get pretty used to doing that inside of Eclipse. So
now I can choose Print Line and I can print Hello World. So now we've created
the same Hello World program, but inside of Eclipse, and I'll save this and we
can just run this and now you can see, it said Hello World. So that's it. That's
the very basics for Eclipse. It's a very nice IDE. It has a lot of features. There's
a lot of things you can do with plugins. It allows you to de-bug within here.
You can set de-bug points, just by double-clicking inside of the margin and
there's a lot of refactoring that you get for free inside here, as well. And if you
haven't programmed before or you haven't programmed in Java, don't worry.
This might seem a little bit overwhelming, but I just want to kind of give you
an overview of everything first. And then, we're going to really get to the
basics, back down to the basics, and go over everything and build up our
knowledge of the language from there. So now let's take a look at IntelliJ.
IntelliJ

So I wanted to show you IntelliJ. It's another very popular IDE from a company
called JetBrains. If you're familiar with C# and Resharper, it's the same
company the ReSharper plugin for Visual Studio. Its another very popular IDE.
Sun -- or actually now, Oracle, also puts out an IDE called NetBeans, but that
one's really not as popular, I think, as Eclipse and IntelliJ. And really, I could
go either way on IDE's, between IntelliJ and Eclipse; I'd just tend to choose
Eclipse because, I think, more people are familiar with it and I think it's a
good place to start. But IntelliJ is definitely a great product. It may even be a
little bit easier to use for an advanced programmer than Eclipse, just because
it's very powerful. Eclipse, I think, is going to be something that is more
broad, there's more plugins for it and it's open source. Where IntelliJ is going
to be something that is a more focused product. So we can go ahead and
download IntelliJ and just take a quick look at this here. And they have an
ultimate edition and a community edition. The community edition is
completely free. It doesn't have as many features as the ultimate edition. So I
went ahead and installed and launched IntelliJ here. So you can see what
IntelliJ looks like. And you can see, just like Eclipse, we can create a new
project here. And we can create a new project from scratch. It will create a
Java project for us, and we can call this one Hello World as well. Choose the
default here for a Java module. Create a source directory. Now, the project
JDK we actually have to assign here. So I'm going to select the directory for
the Java STK, which I have under Program Files, Java, JDK 1.7. And so it's
found it here and we can click Next. You can see it's a little bit more of a -definitely, you can tell it's more of a commercial project. And my source, I can
go ahead and create a new Java class and I'll call this Hello world. Inside here,
we can do our public static void main string array. And then we can do

sym.out.printline. And we can type Hello World. And you can see some of the
things like the auto-complete are a little bit faster. Some of the things are a
little bit nicer. They're a little bit smoother inside of IntelliJ. So I'll go ahead
and click Run here. And you can see here it's run our Hello World program. It's
put the output right here. So this is just another option for you. We're not
going to go very much in depth, into IntelliJ in this course and in this module,
since we're going to be using Eclipse. But I just wanted to show it to you and
give you the option of choosing IntelliJ, if you wanted to develop your Java
applications in IntelliJ. A lot of what we're going to do is not going to focus so
much on the IDE, so you could do the course in IntelliJ, but if you get lost, you
might want to have Eclipse installed, just in case.
Packages

So let's talk about packages in Java. I think this is a very important concept
that I kind of wanted to show you first, because it's going to influence a lot of
how we develop our application and just the way that things are going to
work inside of Java. So if you look here, you can see, back in here -- in Eclipse,
that under my source folder, I've got a default package. And what this means
is that I don't have a package that my class is in. And a package in Java is
very much like a -- if you're familiar with C#, a name space. It is basically a
way to divide your classes up. So I could actually create a new package under
my source folder and I could call this, let's say, Greetings. And then I can
actually move my class into here. And then you can see what's happened
here is Eclipse is smart enough to automatically add this package to my file.
So my Hello World Java is in this package called Greetings. And all that this
does is make it so that we can segregate our application up and also so we
don't have a conflict if some other class was named Hello World. You can
have two Hello World classes that lived in different packages. Packages just
give you a way to divide that up. It also is very important to understand
because this is how the file system is set up in Java. So if we look on disc,
where this is stored, we can see I'm in the workspace in the Hello World
project. If we look at our source directory, you'll see that for every package,
there is a folder. So under this source, Greetings is our file. So this is
important to understand because when you're looking for a file on the file
system, it's going to be organized by these packages. You can almost think of
a package as a folder under your source directory. So you could have different
packages and a common convention is to do something with Dot so you can
say greetings.hello and then you're kind of making a more specific package.
And you'll notice here, when I did this, that Eclipse got angry and said, "Hey,
wait a minute. There's a problem here. The greetings.hello does not match
the expected package Greetings. That's because of the location of this file on
the file system is expecting those to match up. And I can do a quick fix here

and move it. So now, it's moved on the file system and so, it should be okay,
because it's under the greetings.hello. So that's the basic way that packages
work and they're really nothing more than a way to segregate your classes
and to prevent them from having the same name, from not being able to tell
which is which.
Java Class Library

So let's look at some of the Java class libraries. And we're not going to go
very in depth here. But I just wanted to give you kind of a big breadth of how
large Java is and just some of the things that you can do in Java, so you can
understand if you wanted to do something in Java, that one, it exists, and
two, you can find it somewhere in the basic Java framework, if you're trying to
write your own or to look for some project or some software to buy. And the
way that you access these libraries is basically by importing the packages
that come with Java or the Java platform. So you have some things like I/O.
You can write to disc. You can write to files. You can read streams, read data,
write that data out. Networking. You can do a lot of different network reading
and writing. You can do things like interpret a webpage or a process a
webpage, make any kind of network request or call. It supports several
different protocols, networking, common protocols. You have a little bit of
math here, to do common math operations. Collections, and this allows you -and we'll cover this a little bit more in the second part of the course, which
allows you to basically do things like create lists, create maps, dictionaries.
You have regular expressions support, and this is going to be similar to the
Perl syntax, using regular expressions, so it's kind of built into the language.
You have the ability to log, graphics and UI. There's several different graphics
toolkits that are available that you can use and UI toolkits and they do -they're somewhat similar but they're different concepts and you have to
choose from, when you're doing Java programming from your main -- making
an application that runs on the desktop. Text formatting. You can do all the
standard formatting that you'd want to do on date, time, and just regular text
processing. XML, their support within Java using jaxb2, serialize and deserialize XML into objects. Remote method indication, in order to remotely
call a method, maybe on a different server. On another instance of an
application or any of your codes, that you can communicate between two
different applications. Security -- a lot of this is implemented in the JVM but
you can use security features, cryptography, things like that. Databases -there's a large support in Java for accessing databases and using an object
and relational model. To get the data, you can either do raw sequel, or you
can serialize the database tables into objects. And then, of course, reflection,
to allow you to basically inspect the Java code itself and to dynamically load
up classes, dynamically create classes, all these kind of things. And there's a

lot more than this. This is just the basic overview of all the things that you
can do in Java. And we'll be exploring some of these things in the upcoming
modules.
Summary

So let's go over what we covered in this module. First thing we did, is we


talked about Java. We learned a little bit about the history of Java and the
background and what Java is: basically, an object oriented, statically typed
language that runs inside a virtual machine. We learned a little bit about the
virtual machine. We talked about what a virtual machine is, how it allows you
to extract away the programming language and environment from the
operating system, so that you could write your code in one place, against one
target framework and have it run everywhere. Then we went through and we
created our first Java program. We created a Hello World program, compiled
that and we talked a little bit about how the Hello World program works in
some of the components of a Java application. Then we went ahead and went
into Eclipse, an IDE for developing Java, and we talked about how we're going
to use this for the rest of this course, in order to do our Java development.
And we looked at another IDE for job and development, called IntelliJ, which is
equally good, if not better than Eclipse. It depends on who you talk to, but
we're not going to use that for this course, but I just wanted to show you
what was out there. Then we talked a little bit about packages and we saw
how packages could be used to group your source code and to make it easier
to find things and organize your source code and prevent names-based
collisions, naming collisions. And then, finally, we went over the Java class
libraries. I just gave you a really big view of everything that's out there in
Java, so that you would have an understanding of what is available and
what's possible using Java. And we didn't really go into depth in any of these.
We just kind of skimmed over it to see, "Hey, what's out there? If I wanted to
be able to do something in Java, can I do it?" Well hopefully, that's been a
good introduction to Java for you, and in the next module, we're going to
actually get into some actual Java code, and we'll start talking about
variables and operators, and I'll show you how to actually start working with
Java language.
Variables and Operators
Introduction

Hi. This is John Sonmez from Pluralsight, and in this module we are going to
be talking about variables and operators in Java. We're also going to be

covering a few other topics that are related to variables and operators, and
this is kind of going to be the really first steps in learning Java. And before we
get really into this module, I just wanted to let you know that for this entire
course and for all of these modules, a programming language is something
that is really hard to learn from a step-by-step, concept-introduction style.
And what I mean by that is that you may want to go back and review some of
these modules as we get further because I'm going to reference some things
in this module, for example, that are going to cover some material that we're
not really going to introduce until later modules because a lot of things in the
programming language are very dependent on each other. And so for us to
talk about variables and operators, we're going to have to talk a little bit
about things like classes and conditional statements. And so when we cover
those later on, you might want to come back here to get the full picture.
Usually, if you look at a lot of programming books, you'll find that a lot of the
books are kind of written this way, basically, with having you go back and
forth between chapters in order to really get the full concept of it. Now, if you
go through the course just one time straight through, you should be able to
definitely program in Java. But sometimes to get the really big picture,
understanding of it, you might want to go back and review some certain parts
of certain modules that will start to make more sense to you now as we go
further in. So I just wanted to say that just as a caution, so as we're going to
go through here if we encounter some concepts that we haven't really
introduced yet that are going to come in later modules, you don't feel like
you're lost, like you need to know this yet, because you don't. It's going to be
introduced later, but I need to show these concepts in order to show the
examples for some of the things that have to do with variables and operators.
So let's go over what we're going to cover in this module. We're going to
cover a lot of ground here, and we're going to start with basically defining
what a variable is. And if you're new to programming in general, this is going
to be beneficial to you. If you already know about programming, we're just
going to talk about it in terms of Java. And then we're going to do the same
thing with the type. We're going to introduce a type. Talk about what a type
is. Not go too much into detail there. And then I'm going to show you kind of
how to use a variable and type in Java and how to do some basic
declarations. And then we'll talk a little bit about how to name variables. I
think it's very important for someone learning a programming language to
get kind of some good skills in naming variables because that really helps
you to make readable code. Then we'll cover scopes a little bit, and we're not
going to go too in depth into scopes. I just want to introduce the concept of
scopes so that you're aware that variables have scoping in Java. And then
we're going to get into primitive types, and we're just going to cover what are
the primitive types, what is a primitive type in Java, and introduce that
concept. And then we're going to get into somewhat of a complex concept,
but I feel that a Java programmer really needs to understand this -- so we're

not going to go into the real technical details of this concept of boxing and
unboxing, but we are going to talk about it. And I'm going to give you an
understanding of what it means when someone is talking about boxing and
unboxing and just some of the things that you want to be aware of, how Java
operates as a language regarding that subject. Then we'll go into operators.
This is something that you're going to definitely need to know in order to
program in Java. These are things like adding, choosing whether or not two
values are equal or one is greater or less than another, all the kind of
operations that you can do in Java are going to be under this operator
section. Then we're going to talk about strings, which are a special type in
Java, and we'll go into details on how they are in that section. And then,
finally, we'll wrap this up by going a little bit into arrays. Arrays are
something that is not really a concept that's extremely important in most of
the programming today because we use collections, which is another topic
that we're going to introduce in the second part of this course. But it's still
good to have a knowledge of arrays, and we're going to introduce that here.
What is a variable?

So let's talk about variables. If you're new to programming in general, you


might not really know what a variable is. If you already are programming in
another language, you're probably familiar with this term. But it doesn't hurt
to go over this concept again, anyway. Basically, a variable is just like a
variable in a math equation. It's the same thing. If you're familiar with
algebra, then you already know, essentially, what a variable is. And you can
see here I've got an example of one plus three equals four. There's no
variable in there. But if we said one plus x, then it's going to be equal to
something unknown. It depends on what x is. Same thing in a programming
language. And if you think about it, really, if we didn't have variables in a
programming language, some way to vary the input or what was stored,
programs wouldn't be interactive because they would perform the same thing
every time. There would be no interaction from the user. So, really, when you
think about it, a variable, the concept of a variable, is allowing us to have
something be changing in our program, and that is really what makes a
program interactive. That's at the higher level. Now, at the low level, what is
a variable? What does a variable do in our code? It is basically a way that we
can store some data in our program. So we can store a number in a variable.
We can store a word in a variable. We have a whole bunch of things that we
can store inside of variables in Java. And when we get into classes and
objects later, you'll see that those are also going to be stored in a variable
because they can change. And that's kind of the key to a variable is it's a way
of naming something that can change. And, really, the best way to
understand it is just to think about it in terms of algebra. It's the same type of

thing. And we'll go into an example of using variables in a little bit here.
What is a type?

So now let's talk about type. So a type is -- basically, it represents what that
variable going to hold or what kind of variable it is. A variable can be of many
different kinds of all of the types or objects that exist inside of Java. Each one
of those could be stored in a variable. But because Java is strongly typed, we
have to declare what that type is. The compiler doesn't automatically know.
And you probably already have some, what are the concepts of types. If
you're programming in another language, for sure you would know what a
type is. But if you haven't, you still probably have some concept of types. If
you think about it, if I said, "What type is three?" Well, you might say, "Well,
what is three? It's a number." In Java, it would be called an int or an integer.
You can already classify a number, the number three, as a number. And if I
said to you what type is "hello"? You might say, "Well, it's a word." And in
Java, it would be a string. So we're already identifying things naturally in the
world by their types. If you see a chair, you recognize that and you say it's a
chair. It's a type of a chair. There's more than one chair in existence, but we
classify things by type, naturally. So that's all that a type is doing. And when
you look at that example when we declared a variable, we said, "Hey, we
want a variable of type integer." That means it can hold a number, and we're
going to give it a name. So that's all that a type is, and we'll get a little bit
more into the different kinds of types a little bit later in this module. But the
important thing to know about types in Java is that Java is strongly typed, and
what that means is that once you declare a type for a variable, that variable
is always of that type. If we say integer "i," that variable I named "i" is always
going to be of type integer. And we also have to declare the type. We can't
just say, "Give me a variable." We can't just say, "Just declare a variable of 'i,'
and I don't -- I'm not going to tell you the type." Instead, we have to say what
the type is.
Using variables

So let's take a look at how we can use variables in our code. I've got our Hello
World program open here, and I'm going to demonstrate creating a variable.
And then we're going to look at the value of that variable. So I'll go ahead and
create a variable, an integer, and we'll call this variable "number." And we'll
give it a value of three. And then let's go ahead and print out using print line,
just like we had done with Hello World, the value of that variable. And print
line is actually a method that lets us write to the console. We can call it, like
this, with system-dot-out-dot-print line. And it'll take a lot of the different

primitive types or string and let you print to the screen. So we can print our
number out, and it's going to print out three. You can see here it says Hello
World, and then we have three. And the way that this works is you can see
that we have our variable. We've declared the type as an integer. We've said
what the name is, and then we've done an assignment. And we've assigned it
to the letter of value of three. We could also do this with a string. We could
say string name equals Joe, and then we could print that out, as well. So let's
run this and see what happens. Now you can see we've got our Hello World.
We've got three. We've got Joe. So that's really the use of a variable. We
could also rename or reassign a variable. So I could change the name to
Jimmy. And then you can see that it was first set to Joe. Then it changed to
Jimmy. And now it should print out Jimmy. We can also do things like assign a
variable to a equation, basically, or a statement here. We can say number
equals five plus two, and, of course, we're going to get it assigned to seven
here. And we can prove that by running, and you can see that it's now seven.
So, really, this variable can hold the result of the computation, a string,
whatever type that we'd want.
Naming variables

Now, one thing that's really important about variables that I wanted to cover
here is the naming of variables. I think one of the critical things in creating
readable code and, really, the way that other people judge your code -- I
know especially when I'm interviewing someone, if I'm going to judge how
well they write code, is how well they name their methods and their
variables. So naming a variable correctly is very important. You should really
err on the side of making your variable name too long or too descriptive
rather than nondescriptive. So, for example, a bad variable name is going to
be something like x or i or y; "i" is sometimes used as a counter but, for the
most part, you want to name the variable after what's going to hold. So, in
this case, when we had "name" here, even this is probably not as good as a
name like -- or a variable name -- like "firstName" because that's really what
we want to hold. So this is more specific, so it's better. So, really, don't be
afraid of how long your variable name is. It's more important to be descriptive
and to clearly identify what the variable is for, rather than to try and be short
and safe on typing.
Variable scopes

So now I want to introduce to you the topic of scope. And when we're working
with variables, scope is fairly important because you're going to need to know
what is going to happen with a variable. When you try to grab the value of a

variable or assign a value to a variable, scope is really going to influence


what happens. And, really, what scope is, is just -- it's this concept that
variables can exist in different contexts. And what I mean by contexts is that
within your code, there's going to be certain sections of the code that are
basically a context in which that variable has a meaning or a different
meaning or no meaning that all. And if you look at this diagram that I have
here, this kind of represents some code. If you look at the green box, that
green box might be a class. And we haven't covered class yet, but class is the
basic thing that all things in Java must be contained within a class, all of your
code. It's a big container. It represents an object in the world. We'll cover this
more when we talk about classes. But within that class, you may have some
variables that are declared at the class scope. And then, within that class,
you might have a method. And a method is just a set of instructions that are
grouped by a name. And you may have some variables that are declared
within that method. And then, within that method, you may have some
variables that are declared within certain blocks or certain sections of code
within that method. So, really, what you're seeing here is that these variables
have a different scope based on where they are declared. And one of the
things with scope is that always variables that are from an outer scope are
visible within inner scopes, but variables from inner scopes are not visible in
the outer scopes. So let me break that down so I can -- this is the key
concept. We don't even really have to go much into depth here. If you
understand this, you'll understand how scoping works and all the rules. We
don't have to go over each individual rule. But this is the basic premise. If I
declare something at the class of the scope, that's an outer scope. It's the
outside. It's less specific. As we go into the method, the method is inside the
class and maybe the block or the statement are inside the method. So that's
-- the outermost is the class, and then within that is the method, and within
that is maybe a block or a set of statements. So from the outside, if you
declared a variable all the way up at the top, the class level, inside your
method, you'd be able to see that variable. It would exist. You could
manipulate it. Inside the block or inside the block of statements inside that
method, you would also be able to see that variable. Now, by contrast, if we
had declared a variable inside in the innermost block, inside a block inside a
method inside a class, we declared a variable all the way deep inside, you
can't see it from the outside. The class isn't going to be able to access it. So
that's -- the kind of the idea of scoping is that variables go out of scope when
they're a block or their section ends or they're declared that basic concept or
that construct that where they are declared is where they live and they exist
and outside of that, they don't. And so since you see that in this diagram I'm
showing that the class has a method which has statements or blocks, the
variables from the class exist all the way down that chain. But if you declared
a variable inside of a block inside of a method, it doesn't exist outside of that.
So that's the whole concept of scope, and we'll look at some examples.

Using scopes

So I've set up a quick example here to show you how scope works inside of
Java. And we're not going to go very far into depth here, but I just want to
give you an idea of how it looks in the code. So this declaration here is
actually creating a variable that is scoped at the class level, at our class level.
And don't worry about the syntax here. Just know that this is a variable called
"age" that is at the class level, and it's set to 50. And I've commented out
some other lines here. And we can see that if we call this system out a print
line and see what the age is, we can see that it is set to 50, just like we had
declared here. So this scope, even though we're inside this method, we have
the class of the scope, the method level scope, and then we're calling this
within the method. It's getting that 50. Now, if I uncommented out this age
that's declared inside this block, you can see that this is a new concept here
for Java, which is a block. And we'll get into this more when we get into
conditionals, but basically any set of statements in Java, any number of lines,
can be grouped into a block and they'll be executed as one statement. So
anywhere where you can have one statement, you can have a block instead.
A block has its own scope. If you remember from the diagram we looked at,
this is inside of a method. It has a scope. So when I run this, what do you
think is going to happen? Well, it's still going to grab the 50 because this
variable is only going to be in scope -- it's only really going to exist -- from the
beginning of this block to the end of this block, which is almost no time at all.
So by the time we get down here, it's already gone. And since this scope is
more specific -- it's an inner scope -- we are not being able to access the
variable from outside here. So if I run this, you can see it's just getting the 50
here. Now, let's change this. Let's uncomment this one, and this is in the
method level scope. So now what do you think is going to happen? Well, in
this case, we're still going to be able to see this one inside here by the time
that we get to the print line, but this other variable that's in scope in the
method is going to basically hide this one because this variable is in scope.
It's declared right here in the method. So when we run this, we should get 20.
And you can see we've gotten 20. Now let's try one more experiment here.
Let's go ahead and move this print line instead of in here, right into this
block. So now it's in this small scope here. Now what do you think that it is
going to print? Well, let's look at what's visible from inside here. Actually,
from inside this scope, if something was declared at the method level, we
would have that visible and at the class level, that's visible. But because we
have something declared right in this block here, it is going to override or
hide what is at the class or method level, and so we should just get 25. And
that's really how scope works. It's not that complicated of a concept.
Basically, variables live from within their scope, and they can always access

or be accessed by a deeper level of scope, by a deeper nesting.


Primitive Types

So let's talk a little bit about the kinds of types that exist in Java. There are
two basic kinds of types in Java, two big classifications. And really what we're
going to be concerned about right now is primitive types. But if something is
not a primitive type, it is, basically, a class or an object. And we'll get into
classes and objects later. But, basically, a primitive type is going to be any
kind of type in Java that is not an object, that basically is what it says. So
what I mean by that is that a primitive type, if you assign it to something,
that value in memory is exactly what you assigned, whereas objects and
classes, other types that are not primitive types, what a variable really
represents in Java is a memory location. It's a reference to a memory
location. And this is kind of confusing, especially if you haven't done very
much programming. You don't really have to understand this concept. I think
a lot of people teach this concept very early, and it confuses a lot of people.
But you don't really have to understand exactly how this is happening in
memory, but just to know that a primitive type is a special type that has its
value exactly represented, and it's not a reference to something else. And as
we get more in depth into more advanced Java topics, that'll make a lot more
sense. But, really, all you need to know right now is that a primitive type is a
special type in Java. And these are basic types. These are the most base
types. Primitive types are not types that you create in Java. They're types
that exist in the language. So if we look down this list of primitive types in
Java, there's things like a byte, and a byte basically stores memory data. It
can store a value from negative 128 to positive 127. It's basically a computer
byte, if you're familiar with that term. If not, it's okay. The next one is a short,
and a short is basically a 16-bit number. And what that means is that that
number can store 16 bits of information. So this would be negative 2 to the
15th power or positive 2 to the 15th power minus one or, basically, the
value's negative 32,768 to 32,767. That's how much can be stored in that
data. It's really the size of the variable, of what it can store. An integer is the
same thing, except it's 32 bits. So it's much larger. We're not going to go over
all the numbers on each one of these, but it's twice the bit size, which means
that it can store an exponentially larger number. A long, you could probably
guess, is double the integer. It's going to be a 64-bit number, which is a huge
number. But it's a number from negative to positive. It can hold either a
negative or a positive value, all these -- short, int, long. A float, a 32-bit
decimal number. A double is twice that. It's a 64-bit decimal number. A
boolean is true or false. It's a 1-bit value. And a character is a 16-bit
character that you would find in the keyboard. It's basically a letter or a
number. And then, finally, the last type that -- it's not really a primitive type,

but it's treated like a primitive type in Java -- is a string. A string is actually an
object, and a string is a sequence of characters, like when we created our
Hello World program and we said, "Hello World." That, what was in quotes
there, was a string. So a string is really an array of characters. It's a chain of
characters. But Java makes it real easy for you to work with this type because
it treats it like a primitive type for all intents and purposes. And we'll cover
string as a special case a little bit more later. But this is the basic idea -- that
these are the primitive types that you have in Java, and if you're using one of
these types, the difference is -- and we'll get into this a little bit more -- is that
it is going to have that type directly stored in memory. So when you copy the
value, it copies the exact value. Whereas any type that's not a primitive type,
it's really the variable's referring to some other memory location, and the
value that you'd actually find in that variable is a reference to that memory
location.
Boxing and Unboxing

So you might wonder why did we even introduce primitive types if we don't
really need to understand what the difference is so much and we don't really
care about references and memory. Well, it's because I wanted to introduce
this important concept in Java to you, which is boxing and unboxing. And you
kind of have to understand what a primitive type is in order to understand
this idea. And this is an idea that I think a lot of advanced Java programmers
might not even know about. It's an idea that really kind of can make people
little bit scared because it seems complicated, but it's really not complicated.
Here's the basic idea. We said that we have these primitive types, like an
integer or a boolean. Well, each primitive type has a corresponding object,
and it has a type that is a nonprimitive type that is the same thing. So the
lowercase "int" has an Integer class. The lowercase "boolean" has a Boolean
class, and we talked a little bit about classes. We'll talk about that more later.
But, basically, it has a nonprimitive corresponding type for it. And those types
act as a wrapper. So what do I mean by a wrapper? Well, if you look at this
diagram here, you can see that I've got an integer. It has a value of three.
And here I've got the big Integer, as it's called in Java, or the nonprimitivetype Integer. And it stores the primitive-type integer within it. And so it's
acting as a wrapper. And so this can be passed around. And the only purpose
of this is that there are certain methods, there are certain things that you
need to do in Java, that have to take a nonprimitive type as an input. And if
we did not have this ability to have these wrappers, then we wouldn't be able
to call these methods. We wouldn't be able to use this functionality in Java.
And so that all that we're doing here, it's called boxing and unboxing because
you could imagine this as a box. We're taking our primitive type. We're
putting it in a box, and we're sending that box over to whatever method or

whatever thing that we're going to call that requires a nonprimitive type. And
then when it gets it, it may do whatever it's going to do with it and return us
some value that's also in a box. And then we take our value out of the box,
and now we have the primitive type that we can use again. And a good way
to visual this is let's say you wanted to ship some baseballs to someone on
the other side of the country. Well, you couldn't just go to the post office, take
five baseballs, and say, "Ship this." You need to put it into a box first because
the post office doesn't operate with round objects. They don't really ship
baseballs individually, right? You would have to box it up, take the baseball,
put in a box, and then you can ship it. And then let's say that someone
shipped you one in return. Well, they wouldn't ship you just a loose ball. They
would ship it to you in a box, and then you'd pull it out. And so this is the
same concept here. It's just the certain methods or certain things in Java
require a nonprimitive type, and because of that, the primitive type needs to
go into a box so that it can be given to that method. And then you can take it
out of the box when you need that value back out. Now, Java will do this
automatically for you, as we'll see when we actually get into some method
calls. When we pass a value through a variable, Java can automatically take
an integer, and it knows that if this method requires a nonprimitive version of
the integer, it can automatically auto-box. It'll put that integer in a box and
then use it. And the same thing will happen if you try to assign a value out
that is in a big Integer, in the box Integer. It -- in your variables of the nonbox
types, the primitive-type integer, it's going to unbox that automatically so
you don't have to do this. You don't have to do anything. The reason why this
is important is you need to understand this is going on because it can be a
costly operation to do boxing and unboxing, especially if you're doing this in
your code where you have some kind of loop and you're doing a lot of
operations that are requiring a lot of boxing and unboxing. And kind of where
this happens is more of an advanced topic, but I just wanted to introduce this
concept to you so you know what's going on when someone's talking about
boxing and unboxing.
Operators

So let's take a look at some of the operators that exist in Java, and an
operator, basically, is just something that goes in between two variables or
two things inside of a Java statement. And a good way to think about this is
we already do this in arithmetic, in any kind of math. We already have
operators that we use to add numbers together. It's the same concept here.
In Java, in fact, we have math operators. And I'm going to go down this list. I
haven't included all the operators here. I've just included a lot of the basic
ones. So this is not all the operators that exist, but it's the ones that are the
most basic for someone learning Java. You're not going to need to know every

single thing. I'm trying to reduce this set down. So the math operators, you
can see here these are basic ones that you're probably already familiar with.
Subtraction. If you use a subtraction operator, you can say three minus two.
And then the response that's going to come out is going to be one. Same
thing with plus. You have a multiplication. If we go down the line here, you'll
see there's two division operators. One of them is a whole number division,
and the other one is called the modular or modulus. And what this does is if
you take, for example, five. And you use the regular division sign, the slash,
divided by two, the result is going to be two because it's only going to be -going to give you whole numbers. It's so that you're not having something
that was a whole number type and converting it to a decimal -- that is, if
you're working with whole numbers. If you're working with a decimal type and
you do the regular division, it's going to give you a decimal number. But if
you're working with integers or whole numbers, it's only going to give you a
whole number back. And that's why that second modulus operand exists.
That operator, it looks like a percent sign. If you said five mod two or five
divide two using that operator, it's going to give you back the remainder,
which is going to be one. So a little bit confusing if you're not familiar with the
concept, but it's basically the one gives you back the whole numbers that go
in and then the second one, the modular one, gives you back whatever the
remainder would be if you're doing long division and you've got a remainder.
That's the value. Next down the line, you see this weird plus-plus and minusminus. All this does, these are called increment and decrement operators.
And if you put this at the end of a variable or a statement, it will make it so
that that variable gets incremented. So if you had a variable x that was equal
to one and then you did a plus-plus, it's now going to be equal to two. And if
you did minus-minus, it would be equal to zero. So it's just basically a
shorthand way of incrementing or assigning that variable whatever it was,
plus another, or what it was, minus another. And there's a version of this
where you can do this before or after a variable, and we're not going to get
into the specifics of that right now, but just to know you have that ability. So
the next set of operators is assignment operators, and we've already seen
some of this in usage. We already used an assignment operator to assign a
value when we said int x equals three, we used this equal operator. And that
allowed us to assign a value to a variable. This is how we give a variable a
value. And then you have all these weird-looking assignment operators. You
have a plus equal, a minus equal, a multiplication equal. All this does, this is
another shorthand, and this is a shorthand for saying take my value and then
assign it to whatever I've put on the right-hand side of this operator, plus
whatever it was or minus whatever it was or multiply it by whatever it is. And
so this is just a shorthand. We can write out the plus operator, for example,
the plus equal, if we said x plus equal three, it's going to be whatever its
value was, plus three. So we can rewrite that as x equals x plus three. It's just
a shorthand. But we have all these operators for each one of the

corresponding math operators. Next is relational operators, and these


operators are going to compare two things. And as we get into conditional
statements, then this is going to make more sense. But for now, we're just
going to overview what these operators are. What it basically lets you to do is
to evaluate whether two different numbers are variables or types, and see is
one greater or less than the other. Are they equal or are they not equal? And
this is going to be important when you want to choose something, when you
want to say if this number is greater than the other one, then I want to do
this, or if this number is less than the other one, then let's stop this loop. So
you can see that these probably already make sense here, a lot of these. You
have a greater-than symbol, a less-than symbol, great than or equal to. This
is true if it's greater than or equal to, or less than or equal to, and then this
equal-equal. This is a true equal, and the reason why this exists in Java is so
that assignment doesn't get confused. So when you see an equal-equal, it's
actually asking the question are these two equal, rather than saying I want to
assign this value. And then the last one is not equal, and this is asking
whether or not these two values are not equal. It's true if it's not equal. It's
the opposite of the equal-equal. Finally, we have logical operators, and, once
again, this -- we'll go through little bit of an example of this. But you have
your "and," "and/or," and the "not." And the first one, the two ampersands, is
an "and," and it works just like logic, if you're taking a logic class or you're
familiar with logic statements, truth tables. It's the exact same concept here.
If you have a variable that's equal to true and you apply an "and" to it or an
"and" to a variable that is also equal to true, the result is true. If you had a
variable that was equal to true and you say "and" and another variable that
was equal to false, it's going to be equal to false because they both -everything has to be true for an "and" statement. The "or," either one can be
true. So if you had a variable that's equal to true, put the "or" in between,
and you had another variable that's equal to false, the result is going to be
true. The only way an "or" is not going to be true is if both sides are false.
And then the "not" just reverses whatever the value is of a variable. If you
had a variable that was equal to true and you put a "not" in front of it, it
would now be equal to false. If you had a variable that was equal to false and
you put a "not" in front of it, it would be equal to true. And these apply only
to boolean types of variables, which a boolean type is one that can be either
true or false.
Using operators

So now let's take a look at some of the operators that we had covered in the
slides. Well, let's look at some simple cases first. We'll create a number and
set its value to three, and you can see here that we have actually used an
assignment operator. This equal assigns the number. We've already seen

some usages of the math operator. We can assign our number to three plus
two, which would be five. We could assign our number to five minus one. We
can do multiplication, division, so the basic math operators. We can also take
our number and do plus-plus, which would increase that number. So if we
were to look at what that would do here, I'll go ahead and print out what our
number is after we've done the plus-plus. You should see that it is now four.
So that's all that the increment operator does, and we could also have used
the decrement operator, as well. We've already seen the assignment
operator. But let's take a look at how one of the more complicated
assignment operators works. So, for example, we can do number plus equal
two. And what this is going to do is it's going to be the same thing as if we
had typed number plus or equals number plus two. What's going to happen is
it's going to take our number, and it's going to add two to it. It's basically like
an increment operator, except that we're specifying what to add to it. So if we
run this now, we should see that our number was three. It added two, so it'll
be five. And the same thing works for multiplication, division, subtraction. So
now let's take a look at some of the relational operators, and what we can do
here is -- in Java, we can print out the value of a boolean. So I'm going to
create a boolean called "value," and we're going to set this to true. And then
I'm going to print out the value of this boolean. I'm going to print value. Let's
see what we get here. We get the word "true" because it's true. So this allows
us to test some equality operators. We can check to see if numbers are equal
or not. We can do this right inside of our print line. So let's take a look at if I
do three is greater than two. Is this true or false? It is true. You can do the
same thing here. Three is less than two. That will be false. And then, of
course, we could change this to greater than or equal to. And if we put a
three here, then this is going to be true. Less than or equal to, we can see if
three is equal to three, which is true. Or three is not equal to three. And you
can see that that is false. And this really isn't going to be very applicable to
you right now until we actually get into conditionals. But, if you can imagine,
we're going to get to a place where we're going to want to do something if
some variable is greater than another one or equal to another one or less
than another one, and that's where these operators will really come in handy.
And we can test out the same thing with the logical operators in the same
way. So we can check to see if we said true and true, what will this equal?
Well, this should be true. And if we said true and false, since one of these is
false, the result is going to be false. They both have to be true in order for it
to be true. And we can try the "or" operator. Now, if we said true or false, if
either one is true, it'll be true. So we have true. And if they're false or false,
since both are false, we're going to get false. And the "not" operator just does
the opposite. So if we had a false and we put a "not" in front of it, we'll get
true. And if we have a true and put a "not" in front of it, we're going to get
false. And we could put a "not" in front of that, so it's not not true, which
would be true.

Strings

So let's talk a little bit about the special type in Java, which is a string. And a
string is a special type because it is treated like a primitive even though it is
actually an object. And it's really not important as far as how that works.
What this really means is that you can use this anywhere that you can use a
primitive type. It acts like a primitive type. It can be just assigned without
using the new syntax, which we'll cover a little bit later when we get into
classes. But one other important thing about a string is that they're
immutable, which means that they cannot be changed. So when you create a
string, you initially create that string like you can see in this example below.
We have a string called salutation, and we have it equal to Hello World. If we
were to later change that, if we said salutation equals one, two, three, four,
Hello, it's actually going to create a new string in memory. It's going to
appear to us that we've changed it, but it has actually created a new string
because you can't change the string once you've created a string. And that's
where you can see that it really is an object because if it were not a
reference, if it were the actual value, then we would have changed it. But
because that variable actually points to some memory location, we can
actually assign it to a new memory location. It actually creates a new string.
And Java really makes it easy to work with strings. That's the whole point of
this, introducing this concept of strings, is that we'll see some examples how
you can do some string manipulations in Java, and Java has just made it
easier. If you look at the example below, we saw that the easy way to declare
the variable called salutation that holds a string is to just say equals, in
quotes, Hello World. You can also use the syntax of new string in creating the
object, but Java makes it easier for you so you don't have to do that because
it's a very common thing to use strings in Java.
Using strings

So let's take a look at some of the things that we can do with a string in Java.
So, if you remember, we can declare a string variable just by typing the word
"string," giving it a name. We'll call this "firstName." And let's have this equal
to John. Now, some of the interesting things that we can do with a string in
Java is we can, of course, just print out a string. So let's make sure that we're
able to print this out. And we can also -- remember we can't modify a string,
but we can add some strings together and it'll create a new string. So I can
use the plus operator to actually add strings together. So I can set first name
equal to first name plus -- space -- Sonmez. And I'll add my last name under
here. Of course, the variable name is not very good anymore, but you can

see that I'm adding two strings together to get a third string, which we're
assigning back to the firstName. In fact, why don't we just create a new string
here and we'll call this "fullName." So now the fullName variable is equal to
the firstName plus last name. And if I print this out, you'll see that it is equal
to both of those strings added together. Another interesting thing that we can
do with strings is because strings are actually objects, we can actually get the
length of a string by calling methods on the string. So we can call the length
method, and that will spit out the length of the string. You can see that is 11
characters long. And we can also find out where a letter is in this string by
calling the method of the string. We can call dot-indexOf, and we can pass in
a character or even another string. And, for this example, let's pass in the
character z. And you can see the special syntax I'm using to use a single
character, which is single quotes. This is something that Java interprets as a
single character. A string is always in double quotes, but a single character, if
you want to treat it like a character, is in single quotes. So we're going to find
out what index or what number count starting from zero would the z be in
this string. And you can see here that it's the 10th. So zero, one -- zero, one,
two, three, four, five, six, seven, eight, nine, ten.
Arrays

And the last thing I want to show you is arrays. Remember I'd said that arrays
are not so important nowadays inside of Java because we mostly use
collections, which we're going to get to in a later module. But you still need to
know what an array is, and occasionally you will still have to use an array. An
array is basically just a way that we can have a list of a size that we know of
some variables, and we can give that list a name. And so I've got an example
here where I am declaring an array of numbers. You can see here I used a
special syntax with these brackets here. This is the type. This means I have
an array type of integers. And then I've called it numbers, and I'm assigning it
-- and you have to use this syntax of new int -- and I specified the length. So
the length here is going to be ten. So this is going to create an array of ten
integers. Once you've created your array, you can assign the different values
in the array. So, in this case, I'm assigning numbers zero equal to five and
numbers one equal to eight. Now, this is zero index. So what that means is
that, within this array, it's going to be ten numbers starting at zero, so zero
through nine. And I haven't initialized all of them. I've just declared two of
them. But we can get those values out of the array. What you're using here is
a special syntax called an indexer, and this allows you to index into the array
in Java. So let's go ahead and print out some values of the array to see what
they are now. So I can use this print line again, and I'm just going to print
numbers zero. And we're expecting that to be equal to five. And you can see
it's printed five here. If we checked numbers one, we would see that was

equal to eight. And what do you think will happen if we choose numbers two?
We haven't declared it here. You see that it is actually equal to zero, because
it initializes as a default value for an integer is zero. So that's it. That's an
array. You can also notice here that they're -- we're using an array already in
our main entry point into our application. The strings that come in -- this is an
array of strings -- are the command line arguments that come in if you're to
run this program from the command line. Now, one important thing about an
array in Java is that once you've created this array of the size of ten, it cannot
be resized. You'll have to create a new array and then reassign the numbers
in that array. So this is one of the reasons why, typically, nowadays, arrays
aren't used as much as collections, which can be resized. You can have
basically arrays that are dynamic in size using a collection. But it's important
to know what an array is, and occasionally you will still have to use an array
when programming Java.
Summary

So let's go over what we covered in this module. The first thing that we did
was we talked about a variable. I introduced the concept of variable, and
along with that we needed to know about types. So I showed you what a type
is and how you could use a variable and using a type to declare the type a
variable and assign that variable. We saw how to do that in code. Then I
talked a little bit about naming variables. We talked about how important it is
to choose a good name for a variable because it makes your code a lot more
readable. Then we went through scopes just briefly, just to introduce the
idea. We didn't go into details in scopes, but this idea that, basically,
variables can exist in different contexts and you might not be able to access
a variable from a higher scope than what it was declared in, a higher context.
And we talked a little bit about the primitive types. We went over all the
primitive types, really in order to understand this concept of boxing and
unboxing. And we talked about how you could basically think of boxing and
unboxing as if you wanted to ship a baseball to someone across the country,
then the mail service doesn't ship round, single, loose baseballs. You need to
put it in a box, and then you can take it back out of the box and then actually
use it. Same concept in Java. And then we went through the basic operators
that exist in Java. We didn't cover all of them. We covered most of the basic
ones that you'll use. We talked about strings, the special case of strings, and
saw an example of doing some string manipulation in Java. And then, finally,
we briefly covered arrays, and I showed you how you could declare an array
and use an array in Java.
Classes

Introduction

So let's go over what we're going to cover in this module. Well the first thing
that we're going to do is we're going to answer the question of what is a
class. We're going to define from a very high level, what a class is and try to
really understand what a class is in object oriented programming and
specifically in Java. Then we're going to take our understanding of the class
and we're going to use that to define an object. We're going to see what the
difference between an object and a class is because this is a really important
distinction that you need to be able to make in Java. A lot of people get
confused between a class and an object. And I really want to clear this up so
that we have a good solid understanding to build from. Then we'll talk about
how to make up a class, which is to use members. We'll talk about how
members are the data and the methods that operate on a class. The data and
then the way to manipulate that data and how that is tightly bound together
in a class. Then I'll show you some examples of how to use a class. We'll
create a class and we'll create some members for that class and then we'll
see how we can create an object from that class. Then we'll talk about how to
create methods and what a method is. I'll show you how to create a method
on your class and the different kinds of methods that you can use in a class in
order to manipulate the data in the class or to access that data. Then we'll
get into some constructors. As we create our class in Java, we'll find that we
need some way to initialize that class or just set its default values or to set
some values on that class so that the object that gets created from that class
can be used. And I'll show you how to do that by using constructors. And then
finally we'll get into access modifiers which will allow us the capability to hide
data in our class or to make it visible.
What is a Class?

So let's answer that question that many of you may be having, is what is a
class? Well, to put it really simply, it's a way that we classify things in Java.
And you see all these printers that I have on this slide. The printers are a
good example of something that we already do in normal day to day life that
is very much like a class in Java. Which is we have a large number of printers
that exist in the world. They have all kinds of different attributes whether
they have a duplexer or different paper sizes that they will print on or color or
black and white or model numbers or manufacturers. But we typically would
just say hey, I want to buy a printer or I have a printer. We don't necessarily
go down to all of the details. And when we talk about a printer, someone
understands what we mean. They understand the general idea of what a

printer is. We don't have to tell them exactly what the attributes are for
someone to understand that we're talking about a printer. And when we try to
build a printer, we generally know what a printer needs to do. There's certain
things that all printers have in common and that is kind of a classification.
And that's really what a class embodies in an object oriented programming
language is. It's a way that we're trying to take something, a lot of times from
the real world, but in today's object oriented thinking, it's not always from the
real world. What it's more of is a set of responsibilities and some data that we
are grouping together to classify something so that we can create instances
of that thing and have the data vary. We're basically taking out what is
constant about a thing and using a name for it so we can identify that. And so
with the printer example if you think about it, when we say printer, well what
are some of the common things about a printer? You think that it has a paper
feed, it has cartridges depending on what kind of printer it is. But it has some
ability to print, some kind of printing engine. It usually has an on and off
switch. These are the kind of things that all printers have. So when we're
thinking about a class in Java, it's really just a structure to define this
classification of a thing. And so now let's look at a little bit more of a technical
explanation of what a class is in Java. Basically a class is methods and data.
And what I mean by that is data of course is things, attributes, like a model
number or a serial number or a paper capacity. It's data that can change
about a printer. Different printers might have different data. And methods are
actions, are things that can be done with a printer or on that data. So a class
is a way that we're going to group together this related set of actions or
things that manipulate data and the data itself. And that's really the key. You
can use a class in a different way than that, but the real reason for creating a
class and a thing that makes a good class, is how tightly bound together the
methods or the actions and the data, are. You want to put them together so
that they perform as one action. And so a class basically, another way of
thinking about this, is a blueprint for creating an object. So up to this point we
haven't talked about objects and we're going to talk about objects a little bit
more later, but basically a class is going to act as a blueprint or you can see
here, I've got another example, is a cookie cutter. And that class is going to
be the mold or the design that's going to allow you to create this other object
that's more specific. So when we think about this in terms of the printer, if I
said I have a class called printer, well that's not very specific. But you want to
be able to create something specific and what you want to know when you
create something specific is the important details. The things that make
printers different. So what are the things that make different printers
different? And what things are the same? The methods and data that are
common to all printers and that's part of the class. And then when we talk
about what makes them different, that's going to be where we get into the
objects and what a class is doing is it's allowing you to specify what are the
general characteristics of a printer so that you could actually create a printer

in your code. So another way to look at a class, getting even more into the
technical details of what a class is in Java, is it's a type. A class is a nonprimitive type. So what I mean by that is we had covered primitive types
before; you know, integers, the decimal representations of floats and doubles
and Boolean characters. A class is none of those. What a class is, is it's
basically a type that you create or that is created even by the Java class
library. But typically when you're using classes; or you create a class, you're
basically creating a type. So if you declare a variable, a variable can be of;
instead of a type, we did integer X equals 3; you can have your type or your
class be that type. So if you create a printer class, you might have printer X
equals, and then you'd create a new printer. So there's a way that we can
think about this also of why do we have a class and how does this whole type
system and classes work together? And that is basically if you think about
that in Java, everything is eventually made up of primitive types. You have to
have everything that exists in Java and Java programming language, at some
root of it, is a primitive type; an integer, a character, a decimal. And a class is
just composed of those primitive types and then some methods to work with
that data. So when you think about it, what you're doing with a class is you're
hurting complexity. You're taking something that is complex. You could take
any Java program, you can get rid of all the Java classes and you could just
use primitive types and not group them together. It would be really hard to
understand that program because it would be very complex, but you could do
that. And if you think about the contrast of that, what we're doing with the
class is we're taking that complexity, we're grouping it into roles and
responsibilities, data that belongs together and methods that work with that
data, and that is really what we're doing when we're creating a class.
What is an Object?

So now that we've talked about what a class is, let's define an object kind of
in terms of a class. So what is an object? The simple definition is it is an
instance of a class. And what I mean by an instance is, if a class is a
blueprint, an object is a house. It's a thing that you build with a blueprint. If a
class is a cookie cutter, an object is the cookie. So if you think about it that
way, the class kind of sets the parameters. With our printer example, the
class was a printer. The object is a very specific printer. It is yourPrinter that is
in your house, sitting on your desk with a model number and a serial number;
all these attributes. It's no longer this intangible thing. A class is intangible.
An object is a real thing. It's an instance of a class that was made by the
blueprint, the mold, that the class provided you. So another way to think
about this is a purchase in a store. Now if you went to a store and you said, I
want some candy. Well, that's not an object. Not candy. Candy is a class. If
you just said I want candy, the person selling the candy might say, you need

to be more specific than that. I want a specific type of candy. Well, that's still
not even good enough of a definition. That's still a class, because you might
have this idea of I want a candy bar or I want a Hershey's bar. You can't buy
this concept. You can't just buy candy or you can't just buy a Hershey's bar.
You have to buy a specific, actual candy bar. So if you're really going to the
store to buy candy, you'd pick up a candy bar, you'd put that on the counter
and you'd buy that. And that is an object. And so when you think about it that
way, that's how you can really separate a class from an object. A class is the
idea. An object is the actual, real thing. And when we're talking in code, it
becomes a little more blurry because of course everything is in memory, but
the real way to think about it is, you can kind of run through that test and
say, is this thing something specific; an exact one of a kind unique thing? An
instance? Or is it this general idea? Class is a general idea. An object is a real
thing.
Members

So now let's talk about members. Members are basically the way that we
define a class. If we want to create our printer class, it's not enough just to
say hey, we need to have a printer class. What you need to do is to define
what makes up that class. What data does it have? What kind of actions can
you do on that data? So what we call these things, the data and the method
that make up a class, are members. And if we look at our printer example
again, we can see that here are some things that might be considered data;
the model number, a manufacturer, the sheets of paper that are loaded,
whether it's color or black and white, whether the printer is currently on or
off. Things like that. All the attributes that would be specific to a printer. Not
just a printer like yourPrinter sitting on your desk, but the current even state
of that printer. These are the things that are considered data. Then the other
half of this is methods. In order for you to have a good class, these methods
should work with that data or operate on that data. So let's look at some
examples here. Some methods might be print. All printers should be able to
print. You should be able to turn them on or turn them off. Show some kind of
error where there's a paper jam, whether you have an LCD display or flashing
lights. Somehow you need to be able to show an error. So this is just kind of
some simple examples and we'll get into the code of how you do this. When
you think about creating a class, you want to think in terms of data and
methods. And those are going to be the members that exist inside of a class.
Creating a Class

So I've got our HelloWorld project open and I want to show you how we can

actually create a class. So what we're going to go ahead and do here is we're
going to create a new printer class just like we had talked about in some of
the slides, and we're going to see how we can actually create that class in
Java. So using Eclipse it's pretty easy to do this. I'm actually going to create a
new name space for our class. I'm going to go and go to new package and
we're going to call this printing. And actually the Java syntax is usually to
have these start with the lower case letter so we'll set this to printing. And
then from inside here I'm going to click new and then class and I'm going to
create a class called printer. I'm going to leave everything default here and
then click finish. And you can see it's created a class called printer. And the
details of this public is not really important right now. We're going to cover
this a little bit later when we talk about the access modifiers. But you can see
we have our printer class here and the basic thing that you need for a class is
basically just this access modifier, the word class and then the name of the
class. And that creates a class. And because it has this package printing here,
it's putting it in the package that we had defined of printing. So within this
class, some of the things that we're going to want to do is to find some data
members and some methods. And for now we're just going to create a very
basic class that just has some data members. So what I'm going to do is
basically just create some variables that are class level variables. Before we
had worked with variables, we had created variables that were method level
variables. In this case we're going to create a class level variable. So I'm
going to create actually a Boolean variable. So we're going to call this
Boolean variable isOn. And a good way to name a variable, a Boolean
variable, is to use is in front of it and it's kind of a convention that people use
in order to indicate that it's a true or false value. So let's create another
attribute of this printer. Let's create a string for the model number. And again,
don't worry about this public declaration. This; we'll cover this a little bit more
later. For now, this is just telling us that we're not hiding any of this data, that
this data can be set by anyone using this class. So that's enough data for
now. We've created our printer class and really it's just that simple to create a
class in Java. And what we've done is we've taken some things that are
attributes of a printer. We said what is the state of the printer? Is it on? And
what is the model number of the printer? And you can see here looking at this
definition of a class, that this doesn't have the specifics of a particular printer.
What we're going to do when we create an object is we're going to give
values for this on or this model number and that's going to allow us to create
a specific printer.
Using a Class

So now that we've created our class, we're going to want to be able to
actually use our class to create an object. So let's go ahead and go into our

main HelloWorld program where we have our main here and let's try to create
a new instance of this class. So in order to do that we're going to just create a
variable, just like we had done before with prototypes. But this time we're
using the type printer. And one quick shortcut that you can do here is in Java;
if you happen to know you have this class printer, in Eclipse, you can hold
control shift and O and what that is going to do is auto import any kind of
packages that are needed in order to access that type. And there's 2 ways I
can do this. I can do printer and we'll call this p equals new printer. And then I
can hit control shift O and it's going to automatically create this import
statement. And what this does is this basically brings this package's name,
into our class so that we can use it. If something is declared in printer, right
now we're in this greetings package so we need to be in the printing package
in order to use a printer. And this import statement is very specific, saying I
want you to import this class that I'm going to use; this printing dot printer
class. We could have also just imported everything in the printing name
space, but typically in Java, we just import what we need. The other way that
I could do this is I could start typing printer. So I'll take out this import
statement and if I hold down control and hit space, and I start typing some of
the rest of the letters, I can see there's a printer here, and if I select this and
hit enter, you can see it's automatically added this import statement for me.
So let's create our printer. We'll create a variable called myPrinter and then
we need to assign this variable. And in Java, in order to create an instance of
an object from a class, we use a special key word called new and a special
syntax of calling a method on the class that is called the constructor. So what
we're going to do is we're going to do new, printer and then we're just going
to do begin parenthesis and an end parenthesis. And what this does is this
calls what's called a default constructor on the printer. It's something we
haven't created yet and we're going to cover this a little bit more in detail
later. But for now, just know that this is the basic syntax for creating a new
object out of a class that you've defined. Now another thing that we're going
to want to be able to do is to actually make this printer be specific; be
different than any other printer. So in order to do that we're going to actually
need to set the data on this printer. And what we can do here now is we can
call myPrinter and dot and dot is just a way of calling a method or accessing
data on an object. So in this case we only have data. We don't have any
methods that we've created, so we want to set the isOn state to false. And
we can do myPrinter dot model number; we'll set this to ABCD. So now we
actually have a printer and this printer is now specific. It has a state, it has a
model number. Now in a real class, a real printer class, you'd probably have a
lot more data than this. For this example we're just going to set this data. We
can create another printer called yourPrinter just like this. And then we can
set different data on this. We could say yourPrinter dot isOn equals true and
yourPrinter dot model number equals FGH. So now we have 2 different kinds
of printers that have different data. So you can see the difference between a

class and an object. These are 2 different objects, but they're defined in
terms of this class. So let's prove that we have some data on our printer. Let's
go ahead and print out what the model number is for myPrinter. In order to do
that I'm going to call system dot out dot print line and then I'm going to pass
myPrinter dot model number. And again, we're using this dot syntax to get
the value out of this variable. So let's go ahead and run this and see what
happens. You can see that it's printed ABCD which is the model number. And
right below this if I've printed from yourPrinter the model number, we would
see that it's indeed different and that one is FGH. So you can see here that
we're able to create an object. It's really simple; we just have to use the
syntax, we declare the variable to store the object; give it a name and then
we call this new in order to call the constructor on our class.
Methods

So our class really isn't very useful since it's just holding data. It doesn't have
any kind of way for us to manipulate that data and it doesn't do anything
besides hold data. Really a class needs to have methods as well. So let's look
at how we can create a method and what a method really is in Java. So we
had talked a little bit about methods before and looking at our printer class
here, what we had said about methods before, is that a method is a way to
act on some data or to manipulate that data, that's related to the class, or
related to that data that belongs to that class. So let's do something useful.
Let's create a way to print. So a printer should be able to print something and
in this case, we're not going to try and print something to paper. We're just
going to print out the model number in this example. A lot of printers are able
to print out a spec sheet or a configuration page that says what their model
number is. Let's create that kind of capability. So I'm going to use the syntax
again. Don't worry about this access modifier yet. We'll cover this a little bit
more but later, but this just tells you that anyone can call this. And we're
going to call our method, print and we're going to specify the return type for
this method which is void. This key word void basically tells us that when we
call this method, there's not going to be any result from this method. It's not
going to return back a value. When you create a method you could also
return back a value and then use that value. So a method can be used to
perform a calculation. In this case we're going to create the simple case first,
which is basically to just do something. So let's have our method print the
model number. So let's call system dot out dot print line and then let's have it
print the model number. And you'll notice also that I don't have to say printer
or myPrinter or anything model number. Instead I'm using this class level
variable. So from within your class, a method in your class can use any data
in that class. So it can just reference model number. And it's going to use
whatever we set the model number to. Now you'll notice a problem here

which is what happens if we don't set the model number? And that, we're
going to cover when we get into constructor, but you're going to see why
we're going to need to use a constructor in order to make sure that our class,
our object is in a good state when it gets created. So let's go ahead and try
this out and see how this print method would work. So we can go in here and
I'm going to eliminate these lines that were doing the print and now we're
going to call myPrinter dot print. Now what's going to happen is we're going
to call this method on our object, this print method, and this print method is
going to actually do the print line. So let's go ahead and run this and see
what happens. You can see ABCD is printed out. So that's how you can create
a method and a method is definitely going to be useful when creating a class
because it allows you to do something with your class.
More methods

So let's look at some other things that we can do with methods. Well we
created a method that basically just did an action. It didn't take any input; it
didn't put any output. We can do 2 things with a method. We can give input
and we can give output as well. So let's try creating a method that is able to
take some input. And in this case we're also going to use a concept called
overloading, which is to have the same method name, but to have a different
way of calling it. So we're going to create a special kind of variable here
called a parameter. And we'll make this a string. We'll call this text and what
we're going to do here is we're going to pass to this method, a value that is
going to be used in this method. So I'll take this system dot out dot print line
and now we're actually going to use this. I'm going to use this text value. So
you can see what's going to happen here if you think about this. We're going
to call this method now. We're going to provide a value here, a variable of the
string type called text. And then whatever we had passed in here, that's
what's going to get printed out. So let's see how we could use this in action.
Instead of calling myPrinter dot print and not passing anything, let's use the
version of this method, the overloaded version where we take a string. So in
this case I'm going to print hello printer. Now what is going to happen here is
that when this print method is called, it's going to take this string that we've
passed in. It's going to be set to this variable called text and then this text is
going to be passed into this printing method in order to print it out to the
screen. So let's run this and see what happens. You can see the words hello
printer were printed out. So now we've actually done something useful. We've
created a method on our printer that allows us to put in any text we want and
then spit that back out. Now let's look at one other thing that we can do with
methods. Let's create a method that will return us the model number. Now
this isn't very useful because we know we can just grab the model number
just by calling dot model number and getting that data out. But when we

actually try to hide the data, which is a best practice of creating a class, later
on, we're not going to have access to this model number. We're going to need
some kind of method in order to do that. So let's go ahead and create that
method. So I'm going to do the same thing here except instead of using void
here, we're going to specify a return type. This is the type of data that this
method needs to return, which in this case will be a string. And we're going to
call this method get model number. And in Java this kind of method is known
as a getter. This is a special kind of method that allows you to get some data
from the class. We also have another special kind of method in Java called a
setter, which allows you to set data on a class. So let's look at how we would
implement this method. What we can do here is we use a key word called
return and this is going to return whatever comes after this return key word.
In this case we want to return the model number. So now you can see that
what our method is going to do is when this is called, it's going to just return
a string that is the model number. Now we can actually assign whatever
comes back from here to a variable. Let me show you how we can do this. So
I'll get rid of this line here and we'll create a new variable of type string called
the model number and then we'll call myPrinter dot get model number. Now
you can see what we're going to do here is we're going to get the result of
this method called when we call myPrinter get model number, it's going to
return us a string. We're going to immediately assign this string to this
variable. So now I could actually print this out from inside of our main by
doing system dot out dot print line and then printing the model number. Let's
run this and you can see it's printed the model number. So just to recap what
we've covered here, we basically saw how we can create methods inside of a
class and these methods operate on the data that's inside of the class. We
created a method that didn't return anything, but it did something. It actually
printed to the screen what the model number of the class was. We saw how
we can create a method that took a parameter. And if we want to specify
multiple parameters, we could do that as well. And we can use each one of
these parameters when we call a method. We simply pass in what we want to
use as a parameter. So in this case, we had passed in the value of hello
printer and it printed out that value. Then we also saw how we could create a
method that could return a value and we used this return key word to return a
value back. And we returned the data that was part of our class or part of our
object.
Constructors

So now let's talk about another important concept, and important part of
creating a class. This is the initialization of that class. We're setting up some
initial data and what we call that is a constructor. In Java, we use a
constructor to set up our class or to construct our object from our class. Now

we saw here that when we called new printer here, we used what was called
a default constructor. We didn't implement a constructor. We didn't create a
special kind of method here in order to do the construction. By default, Java
will automatically give this to you and it will just create an instance of your
class, an object from your class and it won't do anything in addition to that.
But we can create a special kind of method called a constructor. And the way
that we do this is we do public and then we say the name of our class, so
printer, and then this method can take some parameters. So let's create 2
parameters; one for on and then one for the model number. And we'll create
this as isOn and the model number as model number. And what you'll notice
here is this is our scoping problem is going to come into play here and we're
going to have to use another special key word in order to refer to the class
level variable instead of this method level variable in order to do an
assignment here. And what we're going to do here is we're going to take in
some values and those values that we take in, we're going to use them to set
up our class. So we're going to take an isOn value and then we're going to
use this this operator which allows us, even though this name is the same, to
specify that we want to; we're talking about the class level variable. So we
can set this isOn equal to is on and we can set this dot model number equal
to model number. Now we could have also just initialized this to a default
value. We could have not specified this isOn and just said that if you don't
specify it, we're going to make isOn be equal to false. But in this case let's
see how we can use this constructor to automatically create a printer that
has the values that we want set on it. And we'll leave these other methods in
place so that we can examine what the value is going to be. In fact, let's
modify our print method so that it will also tell us if the printer; what state it
is; if it's on or not. So let's go back into our HelloWorld and now you can see
that we don't have a default constructor anymore because we've created an
actual constructor. And so now we have to use the constructor we created.
We have to actually pass in some parameters into our constructor. So I'm
actually going to get rid of all this code and we're going to start over here and
we're going to just create a new printer. So let's create a printer called
myPrinter and we'll do new printer and I'm hitting control and space to see
this list of what the parameters are. And you can see the first one is a
Boolean whether or not it's on. Let's say true. And then for the model
number, let's make it myPrinter. Now you can see that we've done here is
we've initialized this printer object and we can prove this by calling myPrinter
dot print. And now you'll see that it is true and the model number is
myPrinter. So let's run this and you can see isOn is set to true and myPrinter
is a model number. We can create another printer and it could have different
values. So for yourPrinter, we'll set this equal to false and we'll call the model
number yourPrinter and let's print this one out. And let's run this. And you
can see it has print out the values of the second printer. So constructor is
basically something that you're going to use to initialize your class or

initialize the object that you create from your class.


Access modifiers

So we've been ignoring one topic as we've been working through our classes
which is these public declarations that are in front of all our classes and data.
We're just going to cover 3 of the possible access modifiers right now in Java,
and we're just going to cover these in regards to methods and to the data
members. So what you're seeing here now is basically a way that we can
specify how this method or this data can be accessed. And public is a way
that we can specify that anyone can access this. You don't have to be part of
this class. You don't have to any kind of special restrictions or special
privileges in order to access this data. Now I can demonstrate what will
happen if we take away this public, if we change this, and you can see what
will happen here with this, this model number. So let's take a quick look at
what the difference between public is and the other access modifier I'm going
to show you called private. So we'll leave the model number as public and I'll
go into this going to this HelloWorld program and we'll; we have our printer
here that we created. We'll delete this other printer. And notice that we can
change the model number. I can access this. I can call myPrinter dot and you
can see that model number is visible here. And we can set this to new value.
Now if I run this, you can see we've actually changed the model number. This
is bad because we're able to reach inside of here and change this class's
data. Really the class itself should be responsible for its own data. Other
people shouldn't be able to change its data. So we can change this so that
that can't happen, by changing this from public to private. Now you'll see that
this code won't compile because this model number is not visible. You can't
actually see model number. If I hit dot here you can see that isOn is still
public but model number has disappeared. Now this is the reason why we
had created this method called get model number. What we had done here is
given someone a way to get the model number without being able to modify
the model number. And that's really the value of using an access modifier. So
that basic access modifiers that you have are public, private and protected.
And we're not really going to cover protected right now. Protected is going to
be used when we talked about inheritance and it's a way to make it so that
when you have another class that inherits from your class, it is able to access
s that data or that method. That concept isn't going to make much sense to
us yet until we start talking about inheritance. Private simply makes it so that
the only thing that can access this data or this method is the class itself. So
you can only access it from inside the class. In this instance we had seen that
the model number was not accessible from outside. It gave us a compile error
when we had set this to private. But you can see here that we're accessing
the model number and changing it inside of our class. We don't get an error

here and that's because private allows us to have the visibility only from
within our own class. There's also another type of access modifier which is
called a default access modifier and that's when we don't specify one. And
that has a couple of special attributes but we're not really going to get into
that right now because we're going to try to keep this as basic as possible.
And mostly what you're going to be using is public, private and protected.
And really, the general rule of thumb when creating data is that you want to
make all your data private. And you only want to expose what you need to
expose externally. We could also make methods private and that would make
it so that we could only call those methods from within our class. So let's take
a look at a quick example of how we could do that. So let's take this print
method and let's change it so that it is private. Now you can see that we can't
actually call this print method specifying as a string to print from outside our
class. If I went myPrinter dot print, you see there's only 1 method showing up.
But I could call this print method that takes a string inside of our class. So for
example, in our print method here, we could call the other print method and
pass in a string. Now what will happen is it will print out the isOn value, the
model number and then it will print I can call this. So let's go ahead and run
that and see what happens. You can see here that when we call print, it's
called I can call this. So really an access modifier is a way to lock down your
data or to expose your data in your classes.
Summary

So let's go over what we covered in this module. Well the first thing that we
did is we defined what a class is. I showed you from a very high level what a
class is and we kind of drilled down deeper, understanding that a class is
really a custom type that we're able to make and that really, a class is a
grouping of methods and data. We saw that if a class is a blueprint, then an
object would be a house. Or if a class is a cookie cutter, then an object would
be that cookie. Then we went through and we talked about members. We
talked about how to make up a class and that a class consists of data and
methods that operate on that data. So we saw how members are really the
thing that builds up a class. Then we went through some examples and I
showed you how we could create a class. We created a printer class and we
made some data for that printer class. And we saw how we could create
different instances of that printer class and then use those objects and
manipulate those objects in our code. Then we went through and we needed
to do something useful with our printer class so we created some methods to
be able to print and we created a method to be able to get our model number
from our object. I showed you some of the ways that you could use methods
and we played around with some ways of using methods on our printer class.
And then we went over an important point of how to initialize our objects. I

showed you how you could create a constructor that would allow you to pass
in some data that you could use to create your class. And then finally we
went over some of the access modifiers in Java. We didn't cover all the access
modifiers and all of their uses, but we basically went over public and private
and saw how we could use access modifiers to hide certain data in our
classes and to expose other data and methods. Well that's it for this module
on classes. Hopefully you've learned a little bit about what a class is in Java
and there's a lot more to this subject. But I just wanted to give a basic
introduction so that we can build from this and get into some of the more
complicated aspects of Java.
Control Statements
Introduction

Hi. This is John Sonmez from Pluralsight, and in this module we're going to be
covering control statements in Java. And really up to this point we haven't
done anything particularly interesting in Java. We've learned about Java itself,
we've learned about variables and how to declare them, and we've learned
about classes in Java but we haven't actually been able to solve any problems
or to do any real logic. And the reason why we haven't been able to do that is
because we haven't gotten to control statements or conditional statements.
Control statements allow us to actually branch our code and to change the
flow of the execution of our code. This allows us to actually solve problems
and to do some interesting things in Java. So let's go over what we're going to
cover in this module. Well, the first thing that we're going to do is we're going
to talk about control statements in general. There's basically three types of
control statements, and I'm going to introduce those three types to you so
you can understand from a high level what kinds of control statements can
exist. Then we're going to go down and we're going to cover each of the
particular types of control statements that exist in Java. First we'll look at the
if and else statement, which a basic way to branch your code based on a
boolean condition. Then we'll get into the switch statement, which is a way to
do almost the same thing as an if and else but is a lot cleaner when you have
a series of conditions that you want to check and do something based on that
condition. Then we'll look at our first loop which is the for loop, which is a
loop that allows us to increment a counter while we're looping through some
section in our code. And then we'll look at the for each loop, which is another
special kind of loop, which makes it very easy for us to do a loop and to loop
through things in a container or in some kind of collection. Then we'll look at
the while loop, which is just a very simple and basic loop that allows us to
loop until some condition is met. And then finally, we'll look at the break and
continue statements, which are used to get us out of a loop early, either by

breaking out of the loop entirely, or continuing to the next iteration of that
loop.
Control Statement Types

Control statements are a very important part of any programming language.


Without control statements there isn't much that we'd be able to actually do
in our programs. Control statements allow us to be able to branch to different
parts of the code, to be able to loop through the code, and to be able to jump
to different areas of the code. Without these kinds of statements, our code
would basically just run from start to finish without ever returning back up or
looping or choosing a different path. So the basic idea behind a control
statement is that it allows us to control the flow or the execution of our code.
And control statements can basically be divided into three main types, and
we're going to cover some of each one of these types in the rest of this
module. The first type that we're going to cover is conditional statements.
And conditional statements can be thought of as statements that allow the
code to branch or to choose a different path. We're going to cover two types
of conditional statements. One is the if and else statement and the other is
the switch. And both of these statements, we'll see, will allow us to evaluate
some kind of condition and then choose a code patch to take based on the
value of that condition. The next type of control statement that we're going to
look at is an iterative control statement. An iterative control statement is
basically just a loop. And we're going to look at several different kinds of
loops in Java and see how we can construct the loops and how we can both
enter and exit the loops. The final kind of control statement is a jumping
statement, and we've already covered one of these so far. The return
statement, when we looked at methods, is an example of a jumping
statement, and that's because it jumps from one location of the code to
another location of the code. There's two others that we're going to cover
here, and they're both related to loops, which is the continue and the break
statement. And we're going to use these statements in order to exit a loop
early or to go to the next iteration of a loop early.
If / Else

The first control statement that we're going to look at in Java is the if and else
statement. This is one of the most basic statements that we can use in order
to branch our code in some way or to execute some conditional logic. So I've
got our printer class open here from our HelloWorld project, and we are going
to modify this so that we can do something useful based on the state. If you
remember, we had created our printer and we even create a constructors so

that we could create a new printer set, whether or not it's on or off and set its
modelNumber in the constructor. And then we of course printed out the
model of our printer. And if I run this right now, we can see that it prints out
true because it's on and the modelNumber. Well, let's try and do something
more useful than that. Instead, let's make it so that this print statement will
tell us the modelNumber and then whether or not the printer is on. So right
now, we can't really do that very well without some kind of a conditional
statement. What we really want to do is we want to say, if the printer is on,
then print the modelNumber and isOn so that we can say, this modelNumber
is on. We don't have a way to do that without using a kind of statement that
we're going to see now, which is the if statement. So let's go ahead and
comment out these println statements, and let's change this so that we're
now going to make it so that if the printer is on, then we want to say the
modelNumber and then that the printer's on. So the way that we do that is
we just use if. and then what goes in these parentheses has to evaluate to
true or false. So it has to be boolean. We could just put the word true here
and this would evaluate to true. We could put false there, it would evaluate to
false, or we can put any kind of statement that's going to result in a true or
false there or a variable that's a boolean type. In this case what we're going
to check here is this isOn variable. So we can check if isOn, and then we can
do something here. Now, we can execute one statement after this check, the
if condition is true, or we can use a block here and execute multiple
statements, as many as we want. In this case, we're just going to need one
statement, but I'm going to go ahead and use a block here. A lot of people
like to use blocks and if statements because if you add more statements to
them, you don't accidentally create a new statement on another line that
doesn't get executed as part of this if. So in this case, let's check. If the
printer's on, let's do system.out.println, and then we'll print the modelNumber
+ isOn. So now we're going to check to see if the printer's on when this is
called, and if it is, then we're actually going to print something out. And if it's
not on, we're not actually going to print anything out at all. So let's go ahead
and test this out and see how this works. So I'll go to our HelloWorld and we'll
run this. And you can see, it's printing out the modelNumber, which is
myPrinter, is on. And if we created a printer that was not on and then we ran
this, you can see there's no output. It didn't print anything. So the basic
syntax of an if statement is very simple; we just say if, we check our
condition, and then we put what we want to do if the condition is met, either
in a block following it or the very next statement. We could have also written
this like this without the block statement and that would have worked as well.
Now, one thing that we might want to be able to do is to have another piece
of code execute if the printer is not on, if this condition evaluates to false.
And we can use an else statement to achieve that. So in this case, all we
have to do is you already have to have an if statement, you can put your
code to execute if the if statement is true in a block if you want or not, and

then you need to put an else statement. And you can put the code to execute
in a block or not there as well. Now what will happen is if this condition
evaluates to true, what is in the if statement or the if block will execute, and
if it evaluates to false, what's in the else will execute. So we can take this
same system prinln, and then in this case, let's print is Off!. And I just wanted
to say something here about these strings here. Generally, you don't want to
concatenate strings by using this + symbol in Java. There's some better ways
to do this. We'll probably cover this a little bit later on, but just so if you're
looking at this and saying, oh, can't you format that string. If you know what
I'm talking about when I talk about a string formatter, then go ahead and use
a string formatter in Java. But if you don't, if you're just starting out, I just
want to show you the if and else statement and I want to keep things as
simple as possible. So that's why I'm just using the +, because I think the + is
a lot easier for people to understand when they're first learning a
programming language. So now let's see what this code will do when the
printer's off and when the printer's on. So I'll save this file, we'll go ahead and
we'll run, and right now the printer is off so we get mMY PRINTER is Off! And
if we set this to true, then you should see that it's now saying that it's on. So
that's it. That's the if and else statement -- a simple way to branch your code.
Switch

The next kind of control statement that we're going to look at is a switch
statement. And the switch statement is a statement that allows us to
evaluate the value of some variable or some statement, some expression,
and based on that value, do different things for different values. So a good
example of a way that we can test this is we can have our print statement
print a certain number of copies. And based on that number of copies, we're
going to print out the modelNumber and then is On! or Off! that many times.
So let's go ahead and modify our print statement so that it'll take in a number
of copies. So we'll put int copies here, and this will be the number of copies.
And then we can use a switch statement by calling switch and then what we
want to switch on, we want to switch on the number of copies. And then what
we'll do now is inside of our block here, we're going to provide cases for the
different cases that could exist. So case of 0, we can do something. And for
each one of these case statements, we need to provide a way to get out of
this, either to return or break, so that we don't fall through, because a switch
statement, what will happen is, if we have case 0 and case 1 here, if our
number of copies that comes into 0, it's going to execute the code that we
put after this case 0, and then it's going to go right on to case 1. It basically
falls through in Java. So this can be useful if we want to utilize this in this
switch statement, but if not, we can use this break statement, which we'll
cover a little bit more in detail later when we get into loops, but for now, just

know that you'll need to put a break statement after each case if you don't
want it to fall through. So I've got a case 0 and a case 1 here, and what I'm
going to do here is I'm going to put after this case what I want to happen in
the code. So we're going to do something that's a little inefficient here for
now, and then we're going to make it more efficient when we get into loops.
What I'm going to do here is I'm going to put our code that prints here, but
I'm going to put this only for the case of 1. So in the case of 1, then we'll print
this statement once, either the On! or the Off! In the case of 0, we're not
going to do anything. Let's go ahead and add another case here. I'm going to
add a case of 2. If the copies amount is 2, then we're going to print this twice,
and if it's Off!, we'll print this twice. And again, this is very inefficient what
we're doing here, but I just want to demonstrate to you how the case works
and then show you how a loop will help to make this code a lot cleaner later
on. Right now we're programming without a loop, and that's why this is going
to be a little bit messy here. The other thing that you can do with a switch
statement is you can have a default case. So if it doesn't match 0 or 1 or 2,
then we can choose to use the keyword default, and this is a special case.
This default case is going to get hit if it doesn't match any of the cases that
are here. So if our copies is passed in as a 3, it's not going to hit 0, it's not
going to hit 1, it's not going to hit 2, it's going to hit the default here. In this
case, we're going to print out "Number of copies is not supported!". So if
anyone picks a number greater than 2, we're just not going to be able to print
that out. We're just going to say that it's not supported. So let's go ahead and
run this and see what happens. We'll have to go in and we'll have to modify
our call to print because we've required a parameter now. If you remember
we're added this copies parameter. So let's make a copies of 0 and see what
happens. I'll run this, and you can see nothing has happened, because what
has occurred here is we pass in a 0 here, we switched on copies which was 0.
And because it was 0 it went to this case 0 and it did nothing. It just broke out
of the switch statement. So now let's try print(1) for one copy. We get MY
PRINTER is On!" because the printer is set to On!. And what we can see has
happened here is it switched on (copies), (copies) is 1. We have a case 1. It
executed everything here until the break, then it broke out. Let's go ahead
and try print(2), and you can see it's printer MY PRINTER is On! twice. And
that's because when we went to our switch, the copies was 2, it hit this case,
it hit this is On! statement, and then it simply printed out twice. And again,
this is not very efficient because we're repeating a lot of code. We have a lot
of code duplication here, and that's because we don't have the ability to use
a loop because we haven't learned about that yet, but once we get to the
loop, we're going to be able to clean that up. Now, let's give a number that's
greater than 2. Let's put 50 here and see what happens. You can see Number
of copies is not supported because it's hit this default case. And let's see
what would happen if we took away one of these break statements. Let's say
that you forgot on case 2 to put a break statement here, so let's delete this.

Now we'll go back and we'll make it so that we try to print 2 copies, and we'll
run this. And you can see it actually hit the statement for 2 but then it went
right on and hit the default statement. It fell through. So it's very important to
remember to put a break statement or some kind of return, something to
stop it; otherwise it'll just fall all the way through. And sometimes the
behavior you want, for example, if you wanted to do the same thing for let's
say 1 and 5, we could actually do case 1, case 5 here and you can see either
1 or 5 is giving to execute this code right here. So I'll go ahead and switch
this to a 5 now, and you can see that it still did what 1 had done before. So a
switch statement basically let's you switch based on the value, some value.
And if you're using Java 7, you can actually switch on a string, so you could
put a string here and not just a number. But if you're using an earlier version
of Java, it'll have to be an integer to switch on. And you can see here that we
could make our numbers go up to any number up here, and we can provide
cases for any number of values that we wanted to, and we always have this
capability of creating this default case. And we don't need a break here on
the default case because there's nothing for it to fall through to.
For

The next statement that we're going to look at in Java is the for statement.
And this is not the simplest of loops, but it is perhaps one of the most
common loops in Java. A for statement is a statement that allows you to loop
through a series of statements or execute some code a number of times, and
in that process it allows you to keep track of a counter or to do some action
on every loop. So let me show you a simple example of a for statement. And
what we're going to do is we're going to simplify this code. We're going to do
a little bit of what's called refactoring here, and this code right now is a mess,
because it's really duplicating a lot of stuff here. We see that we have the
same line kind of printed out in these different places, and when we want a
case for printing 1 copy, we do one of these statements, and when we have
the case for 2, we just repeat it. And that's really inefficient and it's really
copying a lot of code. And so when this changes, if we wanted to make a case
3, we'd have to have 3 of these printlns and that's really just not a good way
to go. But with the loop, we can simplify this. So I want to create a loop up
here. We'll go ahead and delete these statements, and I'm going to show you
how we can use a for loop. So the syntax of a for loop is you use for here, and
then you have some parentheses. And there's 3 things that go into the
parentheses, and they are separated by two semicolons here. So I'm going to
put these semicolons into place, and I'm just going to put what each one of
these is. So this first section here is going to be an initialize, the second
section here is going to be the condition, and the third one is going to be an
increment. So the idea here with a for loop is you need to initialize some

variables or some kind of count, you check it. Every loop, it's going to check
this condition and see if this condition still evaluates to true. If it doesn't, it's
going to quit looping, and then you want to be able to increment. You want to
be able to do something that changes the condition so that it will eventually
end. So let's go ahead and see an example of this. So I'm going to use int i
here. I can declare a variable right inside this for loop, so I've declared a
variable called i. And i is commonly used for a counter. You could use a name
like count, and that's a little bit more descriptive, but for this example I'm
going to use i to save a little bit of space here and make it easier to read. So
here I've declared my variable i. I've set its count to 0, and we're going to
loop until i is less than the number of copies. And then I have another
semicolon here. And then every time we loop, we're going to use this i++.
And if you remember, this i++ is the same thing as saying i = i + 1. What
we're going to do is we're going to increment i every time. Now, the same
thing as with an if statement. We could just use one single line here or we can
use a block. Commonly in a loop you're going to use a block, and everything
that's in this block is going to get executed every iteration of the loop or
every time this loop goes around. So right now if we just looked at this
structure of this for loop that we have, we're going to start at 0, it's going to
check and see, is i, which is start at 0, less than the number of copies. If it is,
then it's going to increment i and then it's going to go on and do what's in
this loop. So for example if we put int copies of 2, i's going to start at 0, i is
going to be less than 2, 0's less than 2, so then i's going to become 1, then
it's going to do whatever's in here, and now we have an i = 1. It's not going
to re-execute this initialization statement. Now it's just going to check this
value. 1 is less than 2, so we're going to get i++, which is going to make it 2.
Then we're going to execute what's in this loop and now, is 2 less than 2? It's
not, so we're done. So it's going to executer that loop 2 times. So let's
actually change our code to make use of this, because what we're doing in
our print method here is we're trying to print the number of copies. We want
to print this statement is On! or is Off!, however many times that's passed in
here. And we only supported 1 or 2 or the default. For the default we said
Number of copies is not supported because we couldn't really support 3, 4, 5,
6, 7. It would have been a lot of coding to write all that code, and we could
never have supported 1,000. It would have been way too much typing in
order to support that much. But we're using a loop, we could support pretty
much any number of copies. So what we'll do here is we'll take this whole if
statement, and we'll just move it inside this loop. So now what we're going to
do is however many copies there are is how many times we're going to go
through this loop, and each time we're going to print either the MAL number
and then either On! or Off! So we'll take out this old switch code, and you can
see how much code that we've been able to eliminate just by getting rid of
that switch statement and replacing it with the loop. This loop is going to be a
lot more efficient. So let's go ahead and run this and see what happens. And

we'll go ahead and leave this 5. We'll print 5 times. You can see here, it's
printed 5 times. If I put a 1 in, it's only going to print once. If I put in 0, it
won't print any times. It completely skipped it, and I can put in 10 here and it
will work as well. You can see there's 10. So what's happened here? What
happened when we put in 10? Well, we had 10 get passed in, it was set to
copies, and we looped from 0 to 10. And this is one of those things that
always confused me when I was first starting out programming, is how to
initialize the for loop and how to know how many copies I want to do. It starts
at 0 or do I start at 1. The best thing to do is just to kind of memorize this
kind of convention here, so if you start at 0 and you always make your
variable less than whatever the max is, you're going to get that number of
iterations. So for example, when 10 comes in here, because we start at 0 and
we're looping till i is less than 10, it's going to happen 10 times. You could
also start at 1 and then say less than or equal to, but I find that a little bit
more confusing. I think it's a lot easier to just remember to do it this way for a
for loop. Now, for loops can be more complicated than this. We're not going to
get into all the details here, but you could have multiple statements here. You
could initialize different variables. You could have a complex condition here.
The basic idea here is that you have this initialization that happens once
when the loop is first entered, you have this conditional that is checked every
time and if it ever evaluates defaults to the loop it's done, and then you have
this other statement that executes on every iteration of the loop that can
access whatever variables you've declared here. There's one more
refactoring I'd like to do here, just to make this a little bit cleaner. You see
that we are actually checking this if statement every iteration of the loop.
What we can do is we can pull this out and we can just check once to get our
text here and use a variable and print out the value of the variable. So let's
try that. Let's create a string, and we'll call this textToPrint, and we'll set this
= modelNumber +, and then we need to have ei8ther is On! or is Off! So let's
stop this thought for a second, and let's create another string, and let's put
the is On! or is Off! in this string. We'll call this string onStatus and we'll set
this =, let's set this = an empty string at first, and then we'll say if (isOn)
onStatus = is On! else onStatus = is Off!. Now we can make our textToPrint
be = to our modelNumber + our onStatus, and then inside of our loop we can
eliminate this whole if block and we can just say system.out.println, and
we're just going to print the textToPrint. Now we've simplified things a lot
better and we've made it a little bit cleaner to read this code, and we're not
executing this if condition every time we go around the loop. We're only
executing this once to build our string, and then we're printing it out however
many times.
For Each

So the next kind of loop that we're going to look at in Java is the for each
loop. And this is one of my favorite looping constructs because I think it's a
very elegant loop and it's very easy to do and it makes a lot of tasks that
would have been much harder much easier to do. So in order to create this
loop, I'm going to create an example here. And we're going to create a print
statement that will allow us to print the different colors, red, green and blue.
And we could fill this with more than those colors, but let's just make an
example where we have red, green and blue, and we want to print those
colors. So I'm going to create a method here called printColors, and it's not
going to take any parameters. And the idea here is that we're going to create
an array of colors as strings, and we want to print each one of these out. So
I'm going to create a string array, and I'm going to use a special syntax here
in order to create this string array. What I'm going to do is we're going to
declare this string array and we're going to call this Colors. And then we're
going to do new String and then we're going to use -- we're not going to
specify the length of the string like we had done with an array. We could have
put 10 for 10 strings and said, we're going to let the compiler figure this out.
Instead, we're going to use some brackets here and then we're going to put
our strings followed by commas, and the compiler will figure out how long to
make the array. So I'm going to do red, blue, green, then a semicolon at the
end here. So now we have an array of colors. Now, a for each loop will let us
basically iterate through this array, or really anything that is iterable in Java.
And iterable is just a fancy way of saying that you can loop through. There's a
lot of things that you can loop through in Java, anything that it would make
sense to be able to loop through, like a list. In this case, we're going to use an
array, and when we get into collections later, you'll see that we can loop
through most collections. But we can use this for each loop in order to loop
through this array. And the syntax for the for each, it looks just like a for. It's
just the keyword for. It's called for each but it's actually just for. And what you
do is you declare the variable that's going to hold the temporary value of the
element, the current element in the array, because it's going to go through
each one of these. So we'll create a string and we'll call this currentColor. And
then you use a colon here, and when you use a colon you can think in your
head "in." So we'll say currentColor "in" colors. And this is going to loop
through every color stored in currentColor in this color's collection. So for
each currentColor in colors, do this. And what we can do here is we can just
do system.out.println, and then we'll print whatever the currentColor is. So
thinking about how this is going to work, it's going to look at this color's
array, it's going to loop through until it's hit every single one of these, and it's
going to store it in the currentColor, each pass-through. In the first passthrough it's going to have red stored in here, then it's going to print out red.
On the second pass-through it's going to have blue stored in here, it's going
to print out blue, and the third pass-through it's going to have green and it's
going to print out green. So let's take a look at how this will work. So let's,

instead of calling print, let's call printColors, and then let's run this and see
what happens. You can see it's printed red, blue, green. So it's real simple.
This is a very elegant loop. I really like this loop because you don't have to -like we had to do in this for loop, we had to figure out where to start and
where to end. Instead the for each loop is able to do that for you. All you have
to do is choose the variable that you're going to store the current item in, and
then use this : and then your list or whatever collection -- whatever iterable
thing that you have. In this case, we have this array of colors. The other nice
thing about this is that we can easily expand this. If I added yellow, orange
here, it's automatically going to work, and we don't have to do anything else.
So I'll just run this, and you can see now it's added those colors. So for each
loop is a really useful loop, and you just have to remember the syntax. It's the
same as the for loop except you're going to use this : here and you're going
to declare your variable to store for each item, and then you're going to give
the actual array at the end here.
While

So the last kind of loop that we're going to loop at is called a while loop. And
there's a variation of this called the do while loop, but we're not really going
to look at this, because mostly you're going to use while loops. In fact, you
really never have to use a do while loop. There are certain conditions where it
might be more convenient, but a while loop is really the one that I think
you're going to use a lot more often. So a while loop is a very simple loop. It's
actually more simple than a for loop but it's not quite as powerful, because
you have to do a little bit more because you have to handle the increment or
decrement yourself. So we could actually rewrite this print method to use a
while loop instead of a for loop. If you remember, when we created our for
loop here, we looped basically starting at 0 and then every time we
incremented our count until it was greater than copies or equal to copies, as
long as it was less than copies we continued to loop -- not less copy that
number of times. With a while loop, we can write this exact same code,
except a while loop simply has a while statement, and then what's in
parentheses is a boolean condition, either true or false. And if it's true, it's
going to continue to loop and if it's false, it will end the loop. So we could
actually do while(true) here, and this would loop forever. It would create an
infinite program. It would never end, because there's no way to get out of this
loop. But what we can do here instead is we can say, while copies is less than
or is greater than 0, then let's print this out. And then we need to modify
copies, so we're going to do copies-- . So what's going to happen here now is
as long as copies is greater than 0, as long as the value int to true, then it's
going to continue to loop and it'll print out our text, and then it will also
subtract 1 from our copies. So if we put copies of 5 in here, it would come in 5

is greater than 0, it'd print the text, it would set copies to 4, 4 is greater than
0, so on and so on until our copies hit 0. 0 isn't greater than 0, so then it
would exit our loop. So let's go ahead and try this out and see how this would
work. We'll change this to print and we'll print say 4 copies. If I run this you
can see we've printed 4 times. And if I change this to 1, you can see it's just
printed once. So while loop, again, a very simple loop but you do have to be
careful that you don't get into an infinite loop, and you just have to make sure
that whatever conditional that you create here, that within your loop you're
changing that conditional so that it'll eventually be met. You're changing the
variable that make up that conditional.
Break / Continue

So the last two control statements that we're going to look at here are the
break and continue statements. And these statements are really used in the
loop or in a switch statement. You saw when we had this print method and we
had used the switch statement, we were using break so we kind of already
understand a little bit how break works. What it does is it breaks us out of
whatever we're in. Usually that's loop, or it could be a switch statement. Let
me show you how break works first in this printColors method. So anytime
that you're in a loop, if you decide that you want to exit that loop, you can
always call break and then it'll immediately exit the loop as if the end
condition had been met. So we can do this in a for loop, a while loop, a for
each loop -- any one of those loops. In this case, let's do something here.
Let's break -- let's break out of the loop when we hit green. And the way we
can do that is we can check to see if the current color is equal to green, we're
going to skip it. And so what's going to happen is we'll get red, we'll get blue
printed out but we're going to skip green and we're going to be done. So the
way that we're going to implement this is we're going to use an if here. We're
going to check if -- we'll say if -- and we're going to use a special syntax here
to compare strings. We don't want to say == when we're using strings,
because strings are objects, and with the == operator, if you compare two
objects, it's going to check to see if they're the exact same object, not if
they're basically equivalent. And this is kind of a bit of a complex topic with
the equals, but you just have to know that when you're comparing objects, if
you want to compare the values, especially this is a rule you have to follow
with strings -- and this is different than C+. And Java -- If you're familiar with
C+, this is going to seem a little bit weird to you. But in Java, you want to do
a certain comparison like this. You'll do your string. = and then your other
string. So we're going to say if green = currentColor, then we're going to
break. And this will break us out of the loop. And this does look a little bit
weird, but all we're doing here is comparing two strings. We could have
written this as ==, but that could cause a problem if these strings aren't the

exact same string, which a lot of times they're not going to be because
they're different memory locations. So let's go ahead and run this and see
what happens here. I'll change this to printColors, and we'll run this. And you
can see it's just printed red and blue. It didn't go through a whole list,
because once it got to green, this if statement evaluates it's true and it hit
the break and it broke out of the loop. Now, let's say that we didn't want to
break out of the loop. We just wanted to skip green because we don't ever
want to print green. We just want to print all the other colors. If instead of a
break statement I use a continue statement here, it's not going to break
completely out of the loop. What it's going to do is when it hits continue
statement it's going to be like it hit this end bracket of the loop. It's going to
go back to the beginning of the loop. And so it'll print red, it'll print blue.
When we get to green, this if statement's going to evaluate to true, it's going
to hit the continue, which is going to cause it to skip the println, and it's going
to go back to the top of the loop, and it'll then hit yellow and then it'll hit
orange. So let's go ahead and run this and see how that works. You can see
here, red, blue, yellow, orange. So basically a break statement is going to
break out of a loop, and it'll work for a for loop, a while loop, a for each loop,
and a continue statement is going to end that iteration of the loop and go on
to the next iteration of the loop, just like you would hit the end bracket of the
loop.
Summary

So let's go over what we covered in this module. The first thing that we did is
we talked about control statements. We talked about the basic idea of the
control statement being some way to interrupt the flow or change the flow of
your programs, and that without control statements our programs would just
flow from top to bottom without ever choosing a path to go down or doing
any kind of looping or jumping around. Then we went through and we looked
at each one of the control statements that exist in Java. First we looked at
if/else statement. We saw how to create an if statement that would check a
condition, whether or not it's true or false and then execute some code. And
we could use the else statement to execute another branch of code if the
statement was false. Then we looked at a switch statement and we saw how
we could do the switch statement to switch on a particular value, and then
have a bunch of different cases and execute different code based on each
case. Next, we looked at the for statement. We saw that this is one of the
simple types of loops that we can create in Java and we saw how we could
use the counter in a for statement to do things like iterate through a list or to
count and exit the loop after we've reached a certain count. Then we looked
at a for each statement, which is a specialized kind of for statement that
makes it really easy to iterate through a collection or list of items. Then we

took a look at the while loop, which is perhaps the simplest of loops. It will
continue to loop until the condition that we're looping on is false. Then finally,
we took a look at the break and continue statements. We saw how we could
use a break inside a loop to break out of a loop early based on some
condition, or we could use the continue statement to go to the next iteration
of the loop. So that covers all of the basic control statements that exist in
Java, and with these control statements now you'll be able to create a much
more complicated Java program and actually be able to solve some
algorithms. With the knowledge that you've covered so far and the modules
up to this point, you should now have the ability to actually write a Java
program that would do something useful. Now, in the upcoming modules,
we're going to get some more tools that are going to allow you to enhance
your skills in developing Java program and to make your programs more
efficient, but in general, you have what you need now to understand the
basics of Java programming.
Inheritance and Composition
Introduction

Hi, this is John Sonmez from Pluralsight, and in this module we're going to be
talking about Inheritance and Composition in Java. So let's go over what we're
going to cover in this module. We're going to cover a lot of gourd here and
this is a fairly complex topic, but we're going to try and make this as simple
as possible and really try to get the most benefit that we can out of this so
that we can design our programs in Java and our classes to be very easy to
use and easy to reuse. So the first thing that we're going to talk about is an
important distinction between inheritance and composition, which is the Is-A
and Has-A relationship. And we're going to talk about how these two types of
relationships between classes really define whether or not something is going
to use inheritance or composition. Then we're going to go through some
demos. I'm going to show you what basic inheritance looks like. We're just
going to take a look at how we can create inheritance in Java, and then we're
going to do the same thing for composition. I'm going to show you how to use
composition inside Java. Then we're going to look at an interesting topic that
confuses a lot of people, which is polymorphism. We're going to ask the
question of what really is polymorphism? Do a lot of people that we talk to
even understand what it means. Even though everyone kind of has an idea of
what polymorphism is, a lot of people can give examples of polymorphism,
but what is it really? What is the core of polymorphism? We're going to
answer that question. Then we're going to get into a discussion about why we
actually favor composition, and this is somewhat of a debated topic, but I'm
going to give you my advice on this topic and tell you why in Java you should

really be trying to use composition instead of inheritance wherever possible.


And then finally we're going to cover the topic of interfaces. One of the things
that we're going to need to be able to do in order to use composition instead
of inheritance is to make use of interfaces, and I'm going to show you why
and how to do that.
Is-A and Has-A

So let's talk a little bit about the Is-A and Has-A relationship in Java. And
really, what the purpose of discussing this is because in Java you're pretty
soon going to find as you're programming in Java, that classes don't stand
alone, that classes actually need to depend on other classes, that you really
have relationships between classes. So classes -- one class is going to be
related to another class in some way. And they're usually going to be related
through either an Is-A relationship or a Has-A relationship. Let me give you
some examples here. So you can see that there's some relationships that we
just think about in real life, which are relationships like a cat. It's an animal, a
car. Well, it has wheels, it has an engine. A train also has wheels and an
engine. A car and a truck, they're both vehicles. So you can see how these
classes or these objects in real life are related to each other, and both of
these relationships that I'm talking about here in all these cases are either an
Is-A relationship or a Has-A relationship. We said that a cat is an animal; a car
has a wheel or has wheels. A car has an engine. Really, when you think about
how do I tell the difference between inheritance or composition, it's as simple
as that. If you would say that something is another type or a subtype of a
type, then it's an inheritance relationship and if you would say something has
another thing, then it's a composition relationship. And really all that means
is that inheritance means that something is related to another thing in a tree
fashion, that it inherits from it, that it is a subtype, it's a more specialized
type. And for composition it just means that it's composed, so it's made up of
these other types. And really this all comes from an important need in Java,
which is to be able to reuse code. The reason why we model things this way
is it's partially to make things a little bit simpler and easier to understand in
graphs, but really a lot of it comes down to the ability to reuse code, either to
reuse some code that is common for two types or to be able to reuse some
code that operates on a type so that it'll operate on multiple types that are
alike in some way. So let's take a look at what specifically is inheritance. If
you look at this example out of here, you can see that I have an example of
an animal and a cat. And a cat really is an animal. It is a type of animal. So
this relationship is appropriate, and when you think about what's going to
happen here, why are we modeling inheritance this way, one of the reasons is
because an animal might have a lot of things that it does that all animals do.
For example, animals eat, most animals I think sleep, and they reproduce. So

all of these types of functionality you could basically build into an animal
class, and then if you had a cat class, you wouldn't want to have to repeat all
that. You would want to be able to utilize -- you want to be able to say, a cat
is an animal but here's what it does differently, and so I'm going to specialize
it. And this really comes in play if you had multiple types, you had a dog and
a raccoon or whatever types of animals, you would want to be able to share
this common code, this common functionality from animal amongst all of
those derivatives of the animal type or the subtypes of animals. That's really
what inheritance is. It's really saying that something is another type. And one
caution with inheritance is you have to make sure that your type really is
going to be treated as that other type, which means that it needs to be able
to be substituted anywhere that the higher level or the base type would be
used. So for example, in this case, if you had some code that was using an
animal, anything that inherits from animal should be able to be used by that
code; otherwise your relationship is kind of broken because if a cat can't be
used anywhere that an animal was used, if a cat isn't truly an animal in all of
the contexts that an animal is used, then it really is not properly modeled
with an inheritance relationship. And one thing that you'll find as we discuss
this a little later on is that there's very, very few things that are actually truly
an Is-A relationship. A lot of times you're going to find some way that that
relationship breaks, and that can cause a lot of problems in your code if
you're depending on it. So now let's look at composition. Composition really is
a much simpler topic. It is something that I think we understand a little bit
easier, which is basically that something is made up of some other parts. So
in this example here, I've got a car, and inside my car you can see I've got
wheel, I've got engine. A car is made up of these things, so you have a car
and then a car contains some wheels, contains an engine. It's a really simple
relationship, and anytime that you see this kind of relationship you can model
it as composition. And I'm going to show you a Java code how to model both
inheritance and composition, but this is the basic idea of composition. It's
also known as aggregation, which is that this car is made up of these other
classes, and that's how these classes are related to each other.
Basic Inheritance

So let's look at an example of inheritance in Java. I've got a HelloWorld


program open and we've got our Printer class up here. And let's go ahead and
change this so that we're using some inheritance here. One thing about
Printer is that it is basically a kind of machine, so we can envision that
perhaps there's a base class that we could use that our printer would inherit
from that's called Machine. So what I'm going to do is I'm going to take these
isOn, this functionality or this state of isOn and I'm going to move it up to the
Machine class that we're going to create, and we're going to make the printer

inherit from that. So it's going to derive its isOn functionality from the
Machine class. So I'll go ahead inside our program, and then I'll add, under
Printing I'm going to add a new class, and we're going to call this Machine.
And then this machine Class, let's go ahead and move this isOn up to there.
So we're going to take everything that has to do with isOn, I'm going to
create this variable in our Machine class, and then we'll create a constructor
for our Machine class that handles the isOn and we'll take this setting of the
isOn here out of the printer. So in the Machine class, we'll do public Machine
and then we'll have it take a boolean for isOn and we'll set this.isOn = isOn.
SO now we have a Machine class that has an isOn, and that's all we're really
going to put in the Machine class is this functionality. We're going to also add
some methods. Let's add the public Method called TurnOn. And this will just
be very simple here. All it's going to do is turn on the machine, so we'll just
say isOn=true, and we'll make another method called TurnOff, and it will just
set isOn=False. So now we have our Machine base class. We've got our
printer here, and it's trying to use this isOn that doesn't exist, so we need to
inherit from the Machine class. So I'm going to make, printer extend Machine.
So now Printer is basically inheriting in Java. This is how we do inheritance in
Java is we just use this extends keyword, and you can only extend one thing
because we cannot inherit from multiple classes. So Printer is going to extend
Machine. It is a subtype of machine. We've got a little bit of a problem here
that, it says implicit Machine is undefined. Must explicitly invoke another
constructor. So we actually have to call the constructor of machines, since we
made the machine constructor take a variable. So one nice thing about using
Eclipse is we can just click here in the margin, and a lot of times you can just
have this automatically be fixed for you. In this case we don't have that
option, but what we can do is basically we're going to just call the constructor
of Machine and pass it in the isOn flag. So we're going to use Super(isOn),
and what this will do is this will make sure that it calls the constructor of the
Machine class. Super just means call my parent or who I'm inheriting from,
call that constructor or use the attribute. It just refers -- just like this, refers to
the current class that we're using. Super refers to the parent and will pass the
isOn there. Now, the other thing that you'll notice here is that we can't use
this isOn, because it's not visible to us, and that is because if we look at
Machine, we made isOn be private. What we can do is we can change this to
protected, and what that will do is it'll allow any subclass, any children of
Machine, anyone who inherits from Machine, to be able to access this
variable as well. So now you can see in our printer class we can access the
isOn. So let's go ahead and run this code just to make sure that what was
working before is still working. You can see we had created our printer with it
being set to on, and a serial number, a model number of myPrinter, and then
we get these print colors. So I'll run this, make sure that this works. It still
works. Let's go ahead and change this so that we're going to call print and
we'll do one copy. Now, we can see that it is set to on and the printer is set to

on. And now what we can do here is because we've used inheritance,
because we have inherited from Machine, we can call this TurnOn or TurnOff
method. So we should be able to do MyPrinter.TurnOff, and because it
inherited from Machine it has this method, and TurnOff should turn the printer
off. So now if we print (1) copy after turning it off, we can see now that it was
on and then it turned off. So just to recap what we did here is we created this
Machine class and then this Machine class, we put this isOn. We moved it up
from Printer so that all machines could have this isOn because all machines
have this in common, and then we created a TurnOn and TurnOff method that
flips it from true to false. Then in our printer, because we had created this
Machine constructor that took the isOn, we needed to actually call Super from
inside of our printer's constructor and pass on the isOn so that our Machine
class, our base class, could be properly constructed as well because it
requires this isOn to be passed into its constructor. Then everything worked
fine as long as we were able to access this isOn from our subclasses, which
we made our Machine isOn protected so that Printer could access it. And then
Printer just worked as normal, but now what we've done is we've extracted
out this concept of being on to a higher level to a machine, and our printer
has inherit from Machine by extending Machine.
Basic Composition

So now let's look at a basic example of composition in Java. So I went ahead


and I created a new class for us called a PaperTray. And we're going to use
this because a printer usually has a PaperTray that's usually part of a printer.
So while a printer is a machine, a printer has a PaperTray, and so we want to
include a PaperTray as part of our printer. So I've printed a PaperTray class,
and this PaperTray class is pretty simple. It just holds the number of pages,
and you can add paper to it, number of pages to it. It keeps track of how
many pages it has. It can use a page and you can check if it's empty. So we're
going to kind of simulate a real printer with this. So what we're going to do
here is we're just going to create a private variable of type PaperTray, and
we'll call this PaperTray, and this will be our PaperTray. And we need to make
sure that we either initialize it here when the printer's created or inside the
constructor. I'll go ahead and just initialize it here so that as soon as this
variable is created that it's initialized. We'll create a new PaperTray. So now
we have a PaperTray. This is our composition. A printer now has a PaperTray.
Now, let's go ahead and utilize this just to see how you would actually utilize
composition in the real world here. So let's go ahead and make our print
method depend on having some paper in the PaperTray. So we'll change it so
that when we do our print of printing copies, we'll go ahead and print the
copies while our copies is greater than 0, like we had done before and we'll
put an & condition here and we'll say & PaperTray.isEmpty or & not

paperTray.isEmpty. So as long as the PaperTray isn't empty, we'll continue to


print our copies. And then let's go ahead and send a message if the PaperTray
is empty, let's say if PaperTray.isEmpty, then we'll do a
System.out.println("load more paper!"). So let's go ahead and see how this
would work here. So I'll go ahead and just leave our example here. In fact,
let's just change this to try and print one page. So let's go ahead and run this,
so we're going to try and print (1) page, and you can see it prints "load more
paper," because we haven't actually loaded any paper into our printer. It's
trying to use this PaperTray, but there's no paper in it. So let's call
myPrinter.LoadPaper. But you can see we don't have a method on printer to
load the paper. Printer should be able to load paper, so let's go ahead and
create a method. We'll pretend like we already have one, and let's load, let's
say 3 pages here. And one thing you can do in Eclipse is you can go ahead
and write the method that you want first. I like to program this way so that
it's a little bit easier to use your classes by trying to use them first, and then
you can just go over here and create a method automatically. Eclipse will do
this for you. So now it automatically created this method for loading paper,
and I'm going to just change this is that (int count) and then what our
loadPaper method is going to do is we're just going to call
paperTray.addPaper, and we're just going to add whatever that count is. So
we're going to use this class that we are using in Composition, this paperTray
that belongs to our printer. So let's go ahead and run this now and see what
happens. Now, you can see it did print MY PRINTER is On! And if we tried to
print 3 pages, you can see it printed it 3 times, but if we tried to print 4 times,
it's actually still letting us print 4 pages. So there's a problem here. We're not
fully utilizing our paperTray, so let's go into Printer and see what's going on
here. Ah, every time we're printing, we need to make the pages in our
paperTray be one less, so we'll go into paperTray and we will say UsePage. So
we're using a page of the paperTray. So we're treating this paperTray as an
object. We're letting it handle its own data. We're just saying, we're using a
page, which is kind of the benefit of composition here, is that instead of
trying to manage all this state and match all this stuff inside of our paper
class, we're using a paperTray, a concept of the paperTray, and so we're
encapsulating that data and that logic in the paperTray class. So let's go
ahead and run this now and see what happens. Now you can see it's
behaving as we expect. The page printed 3 times and it said "load more
paper." So that's the basic idea of composition, is just that you have another
class, and your class has an instance of that class. In this case our printer has
a paperTray. And I wanted to show you more of a real world example, so I'm
actually showing you how to use a class that you might have through
Composition.
Poly-what?

So let's talk a little bit about polymorphism. Polymorphism is a pretty difficult


topic. A lot of people are very confused by it. They don't really understand
what it means. So let's try to break this down and really understand what is
polymorphism. Well, polymorphism, the word comes from the word many,
poly meaning many, and morph, meaning form. So what it really means is
many forms. And it's still kind of a confusing concept to a lot of people. I think
if you ask a developer -- I know I've been on both sides of an interview asking
the question and being asked a question -- a lot of the response will come out
something like, well, if you had a shape and then you had a square and then
you had a Draw method, and so on down the lines describing an example,
instead of really understanding what is polymorphism, what is the base
concept of it. So I'm going to try and make this as simple as possible. There's
two components to polymorphism. You have some code that's dependent on
some kind of interface, and when I use the word interface here, I just mean
some method of operating with it, some way that that code is being used or
that class is being used. And interface for a class is simply just the methods
that exist on that class. So you have some code that's dependent on some
methods that exist in the class or some methods that are defined, and then
the second component is that you have behavior of that code is determined
by the actual class that's implementing that interface. So what that means is
that when you actually use that code that's dependent on the interface, what
the methods that it's going to call, they're not preset. We don't know what
they are, that code doesn't know what they are or what they're going to do.
Instead what happens is when that code runs, depending on what type is
actually implementing that method or that interface, that's what's going to
happen. So a good way to think about hits is if you ask someone to give you
something to write with, an interface would be something that writes, and
they hand you something. You don't know what it is. When you ask -- if you
ask the question, give me something to write with, you might get a pen, you
might get a pencil, you might get a marker. All of those things are able to
write. Think about it as the right method. But depending on what you get is
what gets put on the paper is what it's going to look like. So if you got a
marker, it might be a thick markery line, it might be a red line if it's a red
marker. If you got a blue ball point pen, it's going to be a small blue line. If
you got a pencil it's going to be a pencil line on that paper. So that's really
what polymorphism is. It says, hey, as the user or the code that's using some
interface, I don't know what you're going to give me. What actually
implements that interface or what I actually get is what's going to determine
the behavior. So let's look at an example of this. In this case, I have our
animal class here. And our animal class has a method called makeNoise. A lot
of animals make noise. So we have a base method in our animal class called
makeNoise. Now, we're going to use Inheritance here, and we have a dog and

a cat and they both inherit from animal. They're both types of animals. So
what we're going to do here is for dog, we're going to override. We're going to
redefine that makeNoise method, and we're going to put out bark. We're
going to make a dog bark. And for cat, we're going to redefine the makeNoise
method, we're going to override that and we're going to have a meow. And so
if we had some code that was using animal, we don't have to specify in that
code. That code doesn't need to know whether it's working with a dog or a
cat. Instead, it will program against the animal's interface, which is against an
animal type with a makeNoise method. And at runtime when we run our
code, if we have actually assigned our animal to a dog instance, then it'll do a
bark. If we've assigned it to a cat instance, it'll do a meow. So really
polymorphism is just that ability for at runtime or dynamically for that code to
be able to call whatever method is implemented by the class that inherits
from the base class, so whatever the real class is, the underlying type. So
that's a real simple way, and I'm going to show you how we can actually do
this in code.
Polymorphism (Demo)

So let's extend our Printer example a little bit further here and let's look at
polymorphism. So what we're going to do here to set this up is we're going to
go into our Machine class and we're going to basically make polymorphic
behavior on this TurnOn method. And the way that we're going to be able to
detect this is we're going to print out when the machine turns on a certain
message, and we'll print out a different message when the printer turns on.
So we'll do a System.out.println, and we'll say "machine is on!" So now what
we can do to demonstrate this is we'll go ahead and create our printer, but
the way we're going to create our printer here is we're going to use a
reference to machine. So instead of creating our variable type as Printer,
we're going to use Machine. Since the Printer is as type of machine, we can
just actually use the printer or the machine. This Machine variable can hold
either a printer or a machine. Anything that inherits from machine, anything
that is a machine can be held by this variable. So we're going to actually
create a new printer here, though, even though this code is going to act on it
as if it's a machine, and we'll call machine.TurnOn. So let's go ahead and run
this. And you can see that Machine is on! is printed because Printer doesn't
have a TurnOn method. It's using the one that's inside the machine. Now, let's
see how we can actually make this polymorphic. If I go into our Printer class
and I override, which is to create a new implementation for the TurnOn
method, then we should see the TurnOn method for the printer is going to be
called instead of the one for Machine when we're using a type of printer. And
in Java, the way that we overwrite a method is we use this attribute here or
this annotation in Java called Override. And you don't actually have to use

this, but this makes it so the compiler will check to make sure that when you
put it here, if you don't override a method that actually exists, if your override
isn't going to work, it's going to give you a warning. It's going to give you an
error. So I'm going to create a method called TurnOn and it has to be the
exact same method Signature that exists in the parent. And in Java, all
methods are virtual. What that means is that I don't have to tell the compiler
that this method can be overwritten, that we can have a method that is going
to override this in our subclasses. And so by default all methods are virtual.
So this method is going to be called if the type is of Printer. So let's go ahead
and change this TurnOn -- let's make sure that we call our super.TurnOn so
that it still does actually turn on the printer, but let's change our message
here and let's add an additional message. Besides what was happening in the
machine, let's go ahead and do System.out.println and we'll print "warming
up print engine." And let's go ahead and change the order here so that we're
actually warming up the print engine before we actually turn on the machine.
So now I'll go ahead and run this. And we still have a reference to a machine
here, but because the type is Printer, it's going to use the Printer's TurnOn
method. So you can see that it said Warming up print engine and then
Machine is on! So it has actually called this method, and it determined which
method to call based on what this type was. So we can prove that that's true
by changing the type here. If instead of a printer we change this to say new
Machine and we say (true) or we can say (false) here, start it in the off state,
and we run this, you can see that it's now set to -- it's now just saying
Machine is on, so it's actually calling the method inside machine. And that's
really what polymorphism is, is it's this ability that based on what type this
variable is assigned to, even though this variable itself is actually a machine
type, it's only reference to Machine type, if this is a Printer, if we made this a
printer, then the same call here to TurnOn will call the program method.
Favor Composition

So I wanted to touch on this topic real quick before we move on here. Since
we're talking about inheritance and composition, I think it's really important,
espeically in Java, to mention that you should be favoring composition.
Basically, almost all inheritance can be rewritten as composition. We can find
a way to make something that is inheritance composition. And I'm going to
show you some ways to do this. It might not seem like this is true, but let's go
through this and maybe you'll see what I'm talking about here. So one of the
problems with object oriented programming, it's kind of changed, the idea
behind it has changed. Back when it was first used, a lot of inheritance was
used. Now it's more composition because object oriented programming was
originally about modeling the real world. And we found that that doesn't quite
work out all the time. It's still good. It still helps us, but really what object

oriented programming today is about is about modeling interactions in a


system and roles and responsibilities. And however you can do that, what
makes sense inside of that system, that domain that you're creating, really is
how you should model your classes, not exactly after physical objects and
what exists in the real world. And with that knowledge, you can divorce
yourself from the idea that the Is-A relationship has to be implemented in
terms of inheritance. And this is kind of opposite of what I had talked about
before when I said, well, Is-A is inheritance. There's a way to rewrite Is-A so
that we can actually make it a composition. We can make it a Has-A. And one
way to think about that is we can say -- we can take an Is-A relationship and
we can say that same relationship Has-A implementation of something. So for
example, if we took our example of an animal and a cat -- well, a cat Is-A
animal. We could rewrite that and say, a cat has an implementation of
animal. So we're going to put an animal implementation inside of cat so that
cat can use all of the methods and all of the functionality that's inside animal,
but it doesn't have to be one. And this distinction's really important for one
main reason, which is inheritance is really difficult to maintain. A lot of the
messy code that we've inherited over the years is because of inheritance
itself being used in that code base. I know that I've personally worked in a lot
of code where inheritance was overused, and it makes things really difficult,
because when you make changes to a base class, espeically if you have a
large inheritance tree, those changes ripple down and they cause breakage in
all these subclasses. The same doesn't happen so much with composition.
With composition, you kind of know what you're in for. So that's just some
basic advice to try and favor composition. Now, I'm going to show you some
ways that we can do that using what we're going to discuss next, which is an
interface.
Interfaces

So let's talk about interfaces. This is another programming topic that


confuses a lot of people, and it's really not as difficult as it seems. Basically in
terms of Java, in terms of what we've discussed so far, an interface is just
inheritance without all the baggage. It doesn't have all this weight that's
associated with inheritance, all the bad things that we had. And some of the
weight that's lost is the implementation details. When you created an
interface, an interface is just going to specify what the contract is or what the
methods signature look like for some class that's going to implement that
interface. When we use inheritance, we might have had our animal class and
our animal class might have had some methods that had some default
behavior -- maybe a walk or a eat or sleep. We're using an interface, we
might still have all those same methods. We're just not providing any default
implementation. We're saying, if you implement this interface, if you're going

to inherit from this interface basically that you have to provide these
implementations yourself. And so that's the basic difference here. Now, the
thing that we get when we do this is suddenly we can have multiple
implementations. We can implement multiple interfaces, one class. An animal
or a cat could be an animal interface. It could also be a mammal interface. It
could also be a furry interface. Whatever interface that you want, it can have
multiple ones of them which you can't do in Java with inheritance because
you can only inherit from one object or one class. So we get that ability, and
the other ability we get is that interfaces work with polymorphism. So this
gives us a way to really break apart our inheritance relationship and change it
to a composition relationship, where we're going to use an interface as a
substitute for a base class. So an interface is just the definition of what
methods need to be implemented by some class. That's the simplest way I
think to put it in Java. And here's an example. This is our animal example
again, and I name interfaces I, and then the names so IAnimal. This is really
not a Java convention. When I program in Java, I do this anyway because I like
to know what is an interface, and to me this is the most clear way. This is
perhaps more of a C# convention but you can do whatever you want. The
standard way in Java to do this would be to have animal and then animal
imple. I find that a little bit confusing, especially the way that we use
interfaces today. But with that said, this example, what we're looking at here
is we have an IAnimal interface. This is our interface. It's going to define
some methods, maybe eat, sleep, walk, and then you can see, looking at the
right first we have our dog and our cat. And they both are going to implement
this IAnimal interface. It's just like inheritance, except that they're not getting
the methods, they're just getting the requirement to implement those
methods. So if we had an eat method, for example, dog would have to
implement it, cat would have to implement it. Looking at the left here, this is
where we're going to get into that kind of trick where you can actually change
inheritance into composition. We could have a default animal, which doesn't
really model the real world. There's not like a default animal, but we could
use that to put all of our methods, all our default behavior inside there. Then
we could actually have dog and cat be composed of default animals, each
one of them could contain a default animal, still implementing this animal
interface and then when they want to, for example, eat, they can just call
defaultAnimal.eat and return the result of that. And if they want to do
something special, they could just not call the defaultAnimal.eat and they can
provide their own implementation. This gives you kind of the best of both
worlds. You can both reuse the code inside this defaultAnimal class, but
instead of using inheritance you're using composition here.
Interfaces (Demo)

So let's convert our example here over to use an interface instead of


inheritance. And we'll make it so that we can actually do polymorphism with
interfaces instead of inheritance, and then we'll actually be able to use
composition and interfaces together to avoid inheritance altogether and
basically duplicate the same functionality of inheritance without all the
drawbacks. So let's take this one step at a time, and the first thing that we're
going to do is we're going to change our printer so that it is no longer
inheriting from Machine. Instead, let's create an interface called iMachine.
And what we'll do here is we'll take out this extends Machine and we'll put
implements IMachine. And this implements keyword is how you implement an
interface. Just like extend works to inherit from a class, implements is used
with an interface. So I'll go ahead and let Eclipse create this interface for me.
This is one of the nice things that you can do in Eclipse, because it's
automatically going to be able to create this because it realized that I was
trying to refer to something that didn't exist. So I'm going to click Finish here.
And so it's created my IMachine interface. And on my IMachine interface, let's
go ahead and declare some methods that are going to exist. Now, remember,
you're not going to be able to declare data, you're not going to be able to
declare the actual implementation of Method, but just what this interface
looks like. So let's create our methods. Let's create our TurnOn and TurnOff
method. Because any machine should have TurnOn and TurnOff. Now, we had
implemented this in Machine, but for now we're just going to ignore Machine
and we're not going to utilize Machine at all. We're going to just make it so
our printer is implementing this interface instead. And so now you can see
we've got a whole host of problems here, because we don't have the ability to
call this isOn or to use isOn is on or to basically use this base class, since
we're not using the base class anymore. In fact, what we need to do is we
need to implement these methods ourselves, because we're not getting the
implementation from anywhere. When we inherited from Machine, Machine
was providing us with these TurnOn and TurnOff methods. So I'll use Eclipse
here again, and you can see I can just click this to add unimplemented
methods. And when I do that what it's done here is it's created a TurnOff
method and a TurnOn method. In fact, we already have a TurnOn method, so
it didn't try and recreate that because that's part of the interface, but it
created a TurnOff method because we need to have a TurnOff method. So I'm
actually going to move this isOn back into our class for now, so that we can
implement this interface properly. So I'm going to create a private variable,
boolean called isOn, and I'm going to set it in our constructor here, just like
we had done before. We're going to say that this.isOn=isOn. And now, when
we want to call TurnOn, we're going to just implement this ourselves. We're
going to say isOn=true, and then for TurnOff we're just going to set
isOn=false. So now you can see we have no dependency on Machine, on the
machine class. We created this IMachine interface and we're implementing
this interface by having an overridden method for TurnOn and one for TurnOff.

Now, what this is going to allow us to do is to basically, instead of referring to


our object as a machine, we can basically use this IMachine interface here,
and we can set our printer = this.IMachine interface. And we have to import
this type, of course, to be able to use IMachine. So now we have an interface
that is referring to our printer, and then we can call TurnOn on that interface.
So we can call any methods that exists on this interface. We don't have to
know what the implementation is, Printer implements it. And so let's go
ahead and run this and see what happens here. So you can see it just has the
Warming up print engine because it's calling the TurnOn method in Printer
when we use that interface. Now, let's take this one more step further and
let's go ahead and make it so that we are going to use composition in order
to avoid having to repeat this logic. Because we had this logic for the isOn in
Machine, and the problem with using an interface, a lot of people complained,
is well, I don't want to repeat this code and manage this isOn dislogic in every
single class. if we created another printer, another type of machine, we'd
have to implement the machine interface and reimplement TurnOn and
TurnOff. So we're going to use Machine as kind of a base, but we're not going
to inherit from it. And the way we're going to do that is we're going to have
Machine implement the IMachine interface, and then we're going to have our
printer class have an instance of a machine. So just like we did with
PaperTray, we're going to create a machine variable called Machine, and
we're just going to leave this machine here. And then in our constructor we're
going to construct our machine. So I'm actually going to take this isOn
variable out again, and instead what we're going to do here is we're going to
say that Machine=new Machine, and we're going to pass the isOn here. So
the Machine is going to manage this. It's going to have that logic. We're going
to take this logic for handling the isOn out of our actual class. And then this
TurnOn method, we still have to implement a TurnOn and a TurnOff method,
but all we have to do here, is we can just say Machine.TurnOn. So we're going
to delegate -- this is called Delegation -- because we're going to implement
this interface by delegating it to our internal machine class. So for TurnOn we
just call Machine.TurnOn. For TurnOff, we'll just call Machine.TurnOff. And then
this has actually helped us to figure out part of the interface that was missing
that we didn't even think about here, just that this isOn. We need this
machine interface to provide a way for us to tell if the machine is on, not just
to set the state of being on or off. So I'm going to go ahead and implement a
method here that would allow us to check isOn. So I'm going to change this
instead of a variable to a methodCall and we're going to create this method.
But we need to create this in our interface first, and then we want to create it
in the machine, because we don't want to implement this in our actual
printer. So let's go into our interface here, and let's create a method that
return the boolean called isOn. And now you can see, both machine and
printer have an error here because they need to implement this method. So
I'm going to click add unimplement methods and for Machine, it's going to

have an isOn, and the way that we impalement isOn is to return the value of
our isOn variable. Then in Printer, the way that we're going to implement isOn
is we're just going to return the value of our machine's isOn. We're just going
to delegate our call. So we're going to return Machine.isOn. So now you can
see that the same thing here, when we want to check our isOn, we're just
going to do Machine.isOn. So now you can see we're actually not inheriting
from Machine but we're able to use Machine through composition. So we
have the same polymorphic behavior. If we go to our main class here and run
this, we're now using IMachine and our IMachine can either hold a Printer or
Machine, and it's going to call the TurnOn method. And so if I call this TurnOn
method here, you can see it's calling the code inside Machine. And if we
decided that we didn't want a printer to use Machine's method, or we wanted
to use Machine's method but we wanted to do something else as well, we can
just do System.out.println, for example, and we can say "Warming up printer."
Now if we run this, you can see that it's calling our code, which is delegating
to machine.
Summary

So let's go over what we covered in this module. The first thing that we did is
we talked about the Is-A and Has-A relationship, and how inheritance and
composition are different and how they're modeled differently by the Is-A
relationship and the Has-A relationship. I showed you an example of using
basic inheritance and Java. We saw how we could actually create inheritance
inside Java and inherit a class or inherit some data from a class. Then we
went through and did the same thing for composition. I showed you how in
Java, you could use composition or create a class that's composed of other
classes. Then we covered the difficult topic of polymorphism, and we really
strove to understand exactly what polymorphism is in Java. Then we went
through and we talked about how you should favor composition, and I gave
you my personal opinion and advice on why composition is better to use than
inheritance, especially in Java, where you can't do multiple inheritance. And
finally, we talked about an important concept, interfaces, which allows us to
use composition and still allows us to do polymorphism. Well, that's it for
inheritance and composition. I hope you learned a lot about using inheritance
and composition in Java. And in our next module, we're going to get into a
very interesting topic, which is generics.
Generics
Introduction

Hi! This is John Sonmez from Pluralsight and in this module we're going to be
talking about Generics in Java. So let's go over what we're going to cover in
this module. The first thing that we're going to do is we're going to talk about
what is a generic. We're going to answer the most basic question about
generics and we're going to see why you might use a generic and what
purpose it serves in the Java language. And I'm going to show you how to
create a generic class. That is a generic type that can be used to basically
reuse a class's code for different types, then I'll show you how to do the same
thing except at the method level, we can create generics that operate at the
method level. And then I'll show you how to do that in code as well. Then
we'll go ahead and we'll see some examples of bounded generics which are a
special way of declaring a generic that makes it so that it's restricted to a
specific type or set of types. And then we'll look at another concept that has
to do with generics which is using wildcards in generic which is the kind of
generic that is a subtype or can represent multiple different types and you'll
see why this might come in handy when using generics in Java. Finally, we'll
talk about how generics are actually implemented in Java, and this is a really
important concept to understand because in Java, generics are implemented
using erasure. And we'll talk about what exactly erasure means and why that
is important to you as a Java developer.
What is a Generic?

So, you may be wandering what is a generic in Java. And this concept is one
that often confuses beginning Java developers, but I think a real easy way to
explain what a generic is, is to basically say it's a way that we can write some
code that doesn't depend on a type. It's independent of a type. And what I
mean by that is that if you look at this example that I have below, you can
see I've got some different kinds of houses. I've got a-- what would typically
be a person house. It's a small model version but we could think of that as a
human house. I've got a dog house here and I've got a bird house. Now, you
might write some code in Java that incorporates some of the things that have
to do with the house. You might have it, have some methods to open a door,
open a window, or let someone in the house, let someone outside of the
house count the people that are in the house, some generic code that replies
to any kind of house, anything that provides shelter that some animal or
person lives in. Now, if you don't have some way of specifying that code to
work on any kind of type, then you're going to have to write a specific class
or specific type and then repeat that code for a dog house, a person house
and a bird house. And you could create an inheritance hierarchy and try to
reuse some of that code in that way, but a generic allows you to do this a lot
more efficiently. It allows you to basically create a house and then specify the
type in your code instead of trying to make a specific type of house. So for

example, using generics, we'll create a house of type question mark and
when you want to create that house, when you want to use that house to
create an object of that type of house, it will be of type and you'll specify
what the type is. So, person, dog, bird, and then that house will be
specifically customized for that type. And we'll get into the code and I'll show
you a little bit more about what that means. But just as a concept, the way to
think about this is just some way of being able to create a class that will
operate on different types. So, let's talk about the kinds of generics that exist
in Java. You basically have two main ways that you can declare a generic and
Java or use a generic. The first is at a class level. So, if we create a class level
generic, that's kind of the example that we had talked about with the house is
you're going to make a house of a generic type. We don't know what the type
is. We don't know what that house holds. It might hold a bird, it might hold a
dog, it might hold a person. We don't know what that house type is, but we're
able to create a class that specifies that it's going to use whatever type that
the programmer that wants to use this house says in their code, a way to
think of that is a class of type T. T is kind of what we use to represent a
generic type or whatever type is going to be used for that class. So, it's a
class of some type. House of type T and we'll specify T. So, you might have a
house of type dog, that would be a dog house. The other way that we can
create a generic is that the method level. And it's basically the same thing,
except instead of where we're declaring our class and we're using a type that
is going to be the type throughout that class. With the method level, we are
just declaring a type for our parameters. So one of our parameters or more
than one of our parameters can be of a type we specify, a parameter of type
T. So that means that this method is going to take in some variable or some
parameter, but we don't know what the type is until it's called in code. And at
the point that it's called in code, then we're specifying what the type is. So
this method is generic in the sense that it will operate on multiple kinds of
types. And a good example of this is if you think an add method. And add
method should be able to operate on integers and decimal numbers and even
strings. If you created some kind of generic add method, you wouldn't want
to have to make that add method be written for every single type. You'd want
to be able to create one generic add method that would work for all kinds of
types. Same thing with maybe printing out to the screen or printing out to a
printer, you wouldn't want to create a different print method for every single
type when it's going to do the same thing. So let's look at kind of an example
here that's going to maybe clear things up a little bit more. I know this is a
little bit confusing, but if you bear with me here, we're going to get this
figured out and you're going to understand generics by the time we're done
here. So a good thing to do is to look at what will our life be like without
generics and Java. So this is also a good time to tell you that all classes in
Java inherit form object. This is sometimes the first thing you learn about
programming in Java. But up to this point, we haven't really need to know this

information, so I don't think it's a great place to start. And I'm telling it to you
now because this is the first time that we're actually going to really need to
know this. And the reason why this is important is because if you wanted to
create some kind of generic method or generic class without generics, you
could basically make that class operate on object. Since you know all types
inherit from object, all types are essentially objects in Java, that method or
that class will work on any type because it's going to be an object so as long
as you use object. Now the problem with using object everywhere is it's not
very specific. Object could be anything. So you're going to lose the ability for
the compiler to tell you if you've mismatched types since it will take any type.
So let's look at an example of this and why this could hurt you. So I've
created our house example here. You can see I'm creating a new house. I'm
creating a new person. And I'm going to call a method on house add person.
Now in this implementation, I'm not using generics. So my add method is
going to take an object. And this is in order to make it so this house would
work with the dog, with a cat, with a bird, with a person. So I don't have to
rewrite this code otherwise I would have created a person house, a dog
house. But this house will operate on any object. So I could put a person in
there with that. Then I can remove a person and you notice I have to use this
special operator called a casting operator. I'm casting, I'm telling the compiler
that what you get out from here is of type person. Because I know I put a
person in so I know I have to take a person out. Because what's going to-with this method, if we look at this House.remove method, we would see that
it returns an object. And that's because we're making it so that this house
class could work with all different types. So this is without generics. Now let's
see what happens when we try to add a dog to this house. Well, there's going
to be a problem here because we are writing some code that's operating
assuming that you've only added a person to the house. And we have to do
that because we have to have some way to get the person out. So we have to
expressively type or cast that person back out when we do House.remove. So
I've created dog here. I've done house.add(dog). And this isn't a problem. The
compiler was not going to complain about this because remember in this add
method, we're using object. And we're doing that to make this somewhat
generic without using generics. Now what's going to happen, we're going to
get a runtime error when we try to remove that dog from the house because
we're going to try and cast it the person. So it's going to give us a class cast
exception at runtime which means when our program is running, that's the
only time it's going to figure out there is something wrong and it's going to
blow up. It's going to crash the program. So this is very bad. And this is
because we don't have a way to specify to say, yeah, this instance of the
house I created, I only want it to hold people. We have to rely on other
programmers using this class once it's created using this object, once it's
created, to only put one type in there and only remove one type from there. If
we mix them up, we won't have any way to know which type is in there. And

even if we did, it would create really messy code. So now let's look at the
same example using generics. Generics are basically going to give us some
guidance here in this case that allows the compiler to know what we intend to
put in our type or what we intend our type to be. So in this case, we've got
our house again. And this time, you can see I'm using this syntax for creating
a generic and we'll get into this when we get to the code, is I'm using in these
angle brackets persons. So I'm saying create me a new house of type person.
So this house is only going to hold types of people. So I create many person. I
add the person to the house which is fine. In this case, this signature for this
add method will look a little differently. It would have a T for the type, but
ignore that for now. And then I can remove the person. Now when we get to
the dog example here, we're doing the same thing here. We're adding the
dog and actually what's going to happen here, we're going to get a compile
error for either of these things. We can't do a house.add(dog). That will give
us compile error. And if we try to do a House.remove and assign a dog to a
person, we would get a compile error. We wouldn't be able to do that or we
wouldn't have been able to put the dog in, in the first place. The house.add is
going to stop us from doing that. If we try to remove something from there,
it's always going to be a person because it's kind of a guard here. The add
method is only going to accept a dog. Because we-- when we declared our
house all the way up here, we said that this house is of type person. So that's
the basics of generics and it's really not going to make a huge amount of
sense until we put it into a real usage, and that's what we're going to do next.
Class Generics

So let's look at an example of creating a class level generic in Java. So I've


got our HelloWorld project open and we've got our Printer class here. And
what I'm going to do here is I'm going to pretend like we want to make printer
be able to have a type of print cartridge. So we want to have different types
of printers. What we don't want to have to do is to re-implement printer and
make a printer called black and white printer and another printer called
colored printer. Instead it'd be nice if we had a generic printer class and we
specified when we created our printer whether we wanted it to be a black and
white printer or a colored printer and then we could pass in to our constructor
the print cartridge. And we could pass in a black and white print cartridge or
colored print cartridge. So in order to do this, what we're going to is we're just
going to take our class definition of printer and we're going to change this so
that it takes the type T. And this is going to be the type of printer. That will be
either black and white or color or whatever kind of cartridge that we could
come up with. And we'll see some ways to restrict this later and while we'll
want to, but for now it will actually take any kind of type, any type basically in
Java besides of primitive type. So what we're going to here is we want to hold

a reference to whatever this type is. So we're going to use this. This is
basically our mystery type. And we can use this everywhere whenever we
would declare the type. So in this example, we're going to want to pass in this
type into the constructor so that we can store an instance of this type. We're
going to, in this case, store our print cartridge. So we'll call this cartridge. So
we're going to start cartridge. And then we need to have a class of a variable
here. So I'm going to make a private of type T and I'm going to call this
cartridge. Now you notice this type T here is the same as this T and this T, so
whatever type is going to get filled in here. So for example, let's say we had a
color cartridge, then T would be represent color cartridge and this is just like
replacing color cartridge here and color cartridge here and color cartridge
here. So let's assign this variable. We'll do this .cartridge equals cartridge.
And so now, we are storing a reference to whatever cartridge gets passed in.
So let's look at this syntax real quick of how we would actually use this. So I'll
go to our main program here and let's change this a little bit. Let's-- we had
our machine example in here. Let's go to Printer and in fact let's just declare
this as a new printer here. So when we declare our printer type, we used
these angle brackets to say what the type will be. And in this case, we're
going to do something like a ColorCartridge. We haven't declared this type
yet, but this is a type that we could use here. And we'll call this printer. And
then when we do our new Printer, we do the same thing here. We say this is
also a type of ColorCartridge, or printer of type ColorCartridge. So this Printer
is going to take color cartridges. And then in our constructor, we're going to
pass in-- we're going to need to create a new ColorCartridge. And so you can
see here this is the kind of syntax that we're going to use here. We still need
to create a class called ColorCartridge, but you can see that in order to use a
generic class, we have specify what the type is because remember in our
class here, it's of type T. We don't know what T is. So when we actually use
the class, we're specifying what the type is and then that type is going to
basically represent T for this instance of the class. Remember the difference
between a class and an object. This object is going to get created and it has a
type known. The class is generic. The class doesn't know what the type is
until you create an instance of the object and then it has the type defined
here, this ColorCartridge in this example. So let's go ahead and create some
classes that we'll be able to use here. I'm going to create two process. I'm
going to create a ColorCartridge and then I'll create a black and white
cartridge. And so now, you can see our printer class. We've set this up to use
a cartridge. And in our main here, we need to just import this ColorCartridge
until we've got our import ColorCartridge type. So this compiles, this is fine
here. I'm going to get rid of the machine references here. Now let's actually
use this. And this is going to have a little bit of a limited use right now until
we find a good way to use it. So we'll go into our printer class and what we're
going to do here is we're going to use this cartridge and we're just going to
use this in a very simple way. When we call our print method here, if you

remember this print method that prints a number of copies, the first thing
that we're going to do is we're going to print out a toString on our cartridge.
And this isn't going to really do much for us here. But just take a look here, I'll
do this print line and we can look at our cartridge and you can see the
methods we can call on this. Not much. We can only call methods that exist in
object since all types inherit from object. That's because our class has no way
of knowing what type this is or what methods could exist on cartridge. So
we're going to just use this toString method here since all types, all objects
have toString. And we're going to override toString in our ColorCartridge. So
I'll go into ColorCartridge. And if you remember how to do an override, we're
going to an Override for public String toString. And toString is just a method
that all classes have by default because object has it that puts out a string.
Usually you could override this to provide a string representation of your
class. So we're going to return for this. We're going to return Color. So now if
we call this, whatever cartridge that we get in, we're going to call the toString
on it. And I'll do the same thing for the black and whit cartridge. And here,
we'll return black and white. And so now, let's go ahead and take a look at
what we're going to do here on our main class here. We're going to create a
printer of type ColorCartridge and then we're going to pass in a new
ColorCartridge into it into our constructor. So now we've got a reference to
our ColorCartridge. Then in our Printer, we're going to print out whatever the
cartridge just was. We're going to print out its string, the toString on it. So
let's go ahead and call our copy, go printer.print and we'll print one copy.
Let's see what we get here. As you can see here, we've printed out Color and
then the Load more paper from before. Now if I change this, I could change
this to a type of BWCartridge and I can put BWCartridge here. And now we've
got a black and white cartridge. If I run this, you can see it's printed BW for
black and white. Now typically we would do more with our type here, but in
this case we're making it so that we can have a printer that accepts multiple
types. It can be typed when we create our printer. And the funny thing that
you'll find here is this isn't really useful yet. Now if we're creating some kind
of collection where we're holding a lot of different cartridges and they all
need to be the same type and we kept on adding them to the printer and
then getting them back out, then this would be useful using generics here.
But what you'll find is as we restrict the generics, and I'm going to show you
how to do that in a little bit here, then we'll actually be able to get some real
good use out of this. And the reason why we're not able to get much out of
this yet is because we can only call so many methods on the cartridge. We
can only call the methods that are common to object.
Method Generics

So now, let's take a look at how we can create a generic method. And again,

this isn't going to be extremely useful at this point until we're able to restrict
the generic method. And I'll show you how to do that next, but first let's just
look at the basic syntax of this and you'll just going to have to bear with me
here to see that this example will show you how to do this, but it's not going
to really give you a lot of value yet. So let's create a method that is going to
allow us to print using a different print cartridge than what the printer is
configured with. If you remember, we made our printer be able to take to
take a type and then be the type of the cartridge. But let's say we want to
have a print method that would print you could specify a cartridge. Think
about inserting a cartridge just for a temporary print. So one thing that we
need to do when we declare our generic method is we need to specify what
the generic is going to be right here after the public before the type, before
the return type. So I'm going to use a different letter here. I'm going to do U
here instead of T because we're already using T in our class to make this a
separate type. And this U is only going to exist for this method. It's not going
to exist outside of here. The T exists in all the methods. It's the type that's
defined for that class. But this U is going to exist just for this method
indication. So you could call this method multiple times and pass in a
different type for U. Then we're just going to declare our method. We're going
to call this printUsingCartridge. And then we're going to say it's of type U,
whatever the type that you want to use. And we'll call this cartridge. And
then we'll have a String which will be our message to print. And then we'll go
ahead and just sandwich our message in between our cartridge, which is
toString here. So we'll make two of these. And then we'll make it so that will
print out message in between here. So let's take a look at how we can
actually use this. This is the basic syntax. We have our type and then you're
passing in the type of the parameter. So let's see if we actually called this.
Instead of calling print, we're going to call printUsingCartridge and then we're
going to do a different cartridge than what our printer is. We're going to a
new ColorCartridge then we'll pass in the message: "Hi!" And one thing that
you'll notice here with the method is it auto-infers what the type is. So I didn't
specify the type. I didn't do this. I didn't say a ColorCartridge because I don't
need to do because Java is smart enough. The compiler is smart enough to
figure out that, okay, if you've passed in the type of ColorCartridge here, then
this U, I'm going to replace this with ColorCartridge. And so everywhere in the
code where I see U, I'm going to use ColorCartridge instead. So let's go ahead
and run this and see what happens now. You can see here we're actually
using the ColorCartridge because it printed the Color, the toString for color,
and then it printed our "Hi!" and then Color again. And so we have autoinferred this type, we have our generic method and our generic method is
using whatever type we pass in here. And now before we get into actually
using the bounding to make it so that we restrict our type, I'm going to show
you why we're going to need to do this real quick. So in this method, there is
nothing that's stopping us from doing something like this. You see 3 is a type

of integer. It's a type, so when we got to our printUsingCartridge, this U is


going to be integer, our big integer because this is the boxed version of an
integer because it has to be an object. So now, we're going to be using an
integer here which is not a type of cartridge at all. And if I run this, you can
see it's printing 3 which is strange. It doesn't make much sense here. So it
will take any type here, basically any class. I mean, we can even do
something silly like passing our own reference to printer. And you can see it
prints out the actual class like the memory of that printer. So we've got a bit
of problem here and I'm going to show you how to solve this problem next.
Bounded Types

So now let's take a look at bounded types using generics in Java. So one of
the problems we had with our class, you can see in our printUsingCartridge
and our printer, we had a type T and a type U that we'd used. But both of
these types were unbounded which means that we could have passed any
type in there and you can see that when we used our printUsingCartridge,
we're able to pass in a number, we're able to pass in a printer, we're able to
basically pass in anything we wanted and it didn't complain. We could use
that type just like we could use a print cartridge. And because of that, we are
only able to call the toString method on our cartridge because we basically
had to be reduced to the lowest common denominator. Since any type could
be passed in, we could only use methods that were available on every type,
and so the only method that really made sense was toString. So we were kind
of restricted to use toString here. So with bounded types, we can actually
restrict the types that can be used and we can restrict them down to a set of
types based on a class or an interface. So we can say that in order for you to
be able to substitute the type T for printer, you have to either implement the
cartridge interface or extend some other class. And the way that we do that
is we use a keyword called extends and we use it when we declare our type.
So I went ahead and I created an ICartridge interface here. And on this
ICartridge interface, I created a method called getFillPercentage. And all
classes that want to implement that interface will have to implement that
method. So I made our black and white cartridge implement getFillPercentage
and it's just going to return a hardcoded value of 50 percent, and it did the
same thing with the ColorCartridge. I created the getFillPercentage and it's
going to return 97 percent. And what we're going to do now is we're going to
restrict the type in our printer class using this extends so that it has to be of
type ICartridge. So the only thing that you're going to be able to substitute in
there for type is something that implements ICartridge. And we change this in
our method as well. We're going to make it so that our printUsingCartridge
requires or is bounded by the type ICartridge. And this is going to make it so
that everything that can be passed in here have to be implementing that type

ICartridge. Now you can see that that 3 is no longer valid because 3, that
integer does not implement ICartridge because that's this type mismatch. So
this bounded typing in generics is useful for restricting down the set of types
that can be used. So now we'll change this to new black and white cartridge.
Or we could change this to new ColorCartridge and either one will work fine.
The other that we'll be able to do here now is we don't have to just call
toString. Since we've restricted this to adjust things that implement
ICartridge, we can actually look here and we can see that we can actually use
any members that are available on ICartridge. So we have this
getFillPercentage. So now because we've used this bounded type, because
we've restricted it and we know that whatever gets passed and whatever
type is there is going to extend ICartridge, we can actually call this get
percentage, getFillPercentage method that exists on ICartridge or any
methods that exist on ICartridge. So this is another use of using the bounded
types. So let's go ahead and see how this will work now that we've changed
this so that we're going to actually call this getFillPercentage .print. And we'll
run this and you can see it's now saying there's 50 percent because it was
able to use that method on the interface we're now calling cartridge
getFillPercentage and we're printing that out. So that's the basic usage of
bounded types. And it's really useful when you want to restrict down the type
and you want to be able to actually do something with kind of an interface or
a super class that has some methods on there that you want to be able to
use inside of your generic type. ( Pause )
Wildcards

So the next topic we're going to discuss here is wildcards in Java for generics.
And wildcards are kind of a difficult concept to explain here. I've changed our
project up a little bit to save some time. I've created a new method here
called print 1 and I've modified our printer class. What I did here is I took out
our bounded type. So printer is now unbounded. Printer can accept any type
T. And the reason for this is because wildcards are going to be used in a
situation where you might not be able to bind T or set a bounded type inside
of the class. For example, let's say that printer was not a class we created or
we didn't have the source to it and printer took any type T. But we wanted to
do something with all kinds of printers. So we wanted to create some method
that operated on all kinds of printers that took print cartridges for example.
We need to be able to do that, but we don't have access to that source code.
So this is where wildcards can help us here. So you might think that a way to
do that is in this print 1 method that I have created here that we are going to
pass in the printer and we're going to call getCartridge. I created the
getCartridge method on printer in order to get the cartridge that's currently
set to the printer. And then we would call our getFillPercentage and be able to

print that out. Now, there's a problem here which is first of all that just using
printer without a generic at all, it doesn't know that we have this
getFillPercentage because printer, the getCartridge that comes back, isn't
going to know anything about this. If you look here since printer can be of
any type, that means that what getCartridge can return can be of any type.
And so, in this case, we are restricted down to the same methods that exist
on all types or that exist on object for example which getFillPercentage is not
one of those. So somehow we need to specify that the printer that we're
going to pass in is of a type of ICartridge in order to be able to call this
getFillPercentage. So you can see I've declared two printers up here, a printer
and a printer 2 and one has a black and white cartridge and one has a color
cartridge. So, both of them are types of printers that implement ICartridge.
So we might think at first that we could just do this, printer of type ICartridge.
And now we can actually call getFillPercentage, but there's a problem here. If
you look at the print 1 method call, there's an error here. It won't let us pass
in the printer. Because in Java, printer of type ICartridge even though
ICartridge is implemented by BWCartridge and ColorCartridge, printer
BWCartridge is not a child. It is-- it does not implement printer ICartridge. It's
a totally different thing here. In some languages, this would be the same. You
could say printer ICartridge and printer BWCartridge would be a type of
printer ICartridge. And even though this conceptually makes sense and it
seems like this should work, it doesn't work in Java. And part of this is
because of another topic we're going to talk about next which is because of
erasures. But regardless of that, we need some way to specify that our
method is going to take any printer that extends ICartridge. So any printer
that is T of ICartridge. And if we were able to use a bounded type before, we
had done this in the previous example, but in the instance where we can't
control our type from inside printer because maybe we don't have access to
the source code, we need a way to basically declare printer ICartridge. The
way that we do this is with wildcards. If we were able to change our class
here, if you remember, we would have just said printer extends and then
ICartridge. But we can do kind of the flipside here and we can use a wildcard.
We use this question mark extends ICartridge. And what this means is it just
means that this variable will hold any type that extend that is of printer, but
is of type ICartridge. So that whatever the T is that we pass into the printer,
as long as it extends ICartridge, then this variable will be able to hold it. And
this allows us to basically pass into this parameter either a BWCartridge or a
ColorCartridge. And then we can actually use the getFillPercentage on that
because, again, it's working just like we had with the bounded types where
we knew that because we've restricted the type for printer down here that we
know that the methods that are on ICartridge must exist. ( Pause )
Erasure

So one thing a lot of developers failed to realize about generics in Java is that
they used type erasure. And type erasure is just a fancy way of basically
saying that generics are not real. And what I mean by that is once you
compile your Java application, the generics are not in the bytecode. They're
not in the code that is running the JVM. So this is kind of a strange concept to
understand here, but what essentially happens is the compiler uses generics.
And the complier uses generics to determine if something's wrong or right. If
you can-- when we showed the example of adding the wrong type to a house,
it would tell you that and give you an error. But once the code is compiled,
those generics are stripped out. They're erased essentially. And everything is
essentially an object. We had seen that example of the house earlier in this
module where we have not used generics. Well, after you have compiled your
code, it basically reverts to that. The bytecode, if you looked at it, would look
just like the first example where it was dangerous. The generics made it so
that the compiler was able to help us and ensure that we never tried to put
the wrong type in our house. But it doesn't need that anymore afterwards.
And this is different than a few other languages that have features similar to
generics. For example if you're familiar with C#, C# has true generics.
They're not erased. I've compiled them. They actually exist in the by code. If
you looked at the code that runs in the virtual machine that that .NET code
runs in, it actually has generics in there. And if you know about C++, in C ++
actually code is generated. There-- it's actually a template. It's what C++
uses. And code is actually generated that is of that type or it takes that class
and actually generates real code that operates in that type. It's creating new
classes for you automatically. So those are real and they exist in that sense.
But one of the things to be aware of in Java because of this is that generics
are going to behave a little bit differently than what you might expect. You're
not going to be able to do a lot of things with generics that you might want to
do. For example, if you're in a generic method or a class that's using a
generic, you can't check the type of that generic. You-- if you had some
generic type T, you couldn't ask is this type-- what is the type? Because it
doesn't exist at runtime. So you can't check the type at runtime. Remember
it's going to be of type object to always because that type got erased. The
same goes for creating a new instance of that type. If you got a type passed
in or you're at a house of type dog, you couldn't, inside of your class, do a
new T or new-- which would be new dog because Java doesn't know about
that at runtime. So it's not going to be able to utilize that type. And rather
than listing out all these scenarios in which it will cause a problem for you, I
think it's better for you to just understand this. So when you're thinking about
using generics in Java and whether or not something is legal in Java, just
think about what would happen if this code was compiled and the types were
changed to object. If you use that as a guideline, then you'll be able to figure

out scenarios where you're not going to be able to do something with the
generic. For the most part, you're probably not going to run into this very
much, but if you're trying to do something fancy with the type inside of a
generic method or a generic class and you're trying to examine what the type
is, that's where you're going to run into problems.
Summary

So let's go over what we covered in this module. Well we went through and
we talked about what a generic is which is basically just a way of writing
some code that's independent of a type. And we found out that we could do
this in a class and we could do this in a method. So I showed you how we
could create a generic class and we created a generic class so that we could
specify what type we wanted to use and reuse that class for a whole bunch of
different types. Then we went through and we did the same thing and created
generic method, a method that could be used and operate on multiple kinds
of types. And then I showed you some examples of bounded generics. We
learned that bounded generic is a way to restrict your generic so that
whatever type is being passed in to that generic method or to that generic
class has to extend or implement a certain interface or class. Then we looked
at this special case of wildcards in generics. And this is one of the more
complicated features that exist in Java for generics. And we talked about how
you could use a wildcard to represent almost a generic of generic type, a type
that would either represent a whole class of types, any types of generics that
would inherit from whatever the type is or any classes that were apparent of
whatever the type is. And then finally, we talked about how generics are
implemented in Java that they used type erasure which just basically means
that when the code is compiled, the generics are gone. They're-- they
disappear from the code and I gave you a little bit of caution that you should
remember those when using generics in Java and to basically just think about
when this code is compiled, if the type changed to object, would decode that
I'm writing work because that's what's going to happen when your code is
compiled. So that's the end of this course on Java fundamentals. You should
now have a pretty good understanding of the basics of Java. And the second
part of this course in the second course on Java, we're going to cover some
more advanced topics that are still fairly basic, but will help expand some of
the usage of Java. But at this point, you can pretty much understand Java
code and should be able to write Java code that is able to accomplish some
simple goals and we've really covered most of the language features that
exist in Java, at least most of the basic ones that you'll use on the day-to-day
basis. But thanks for joining me on this course and I hope that you've learned
a lot about Java.

Course author
John Sonmez

John Sonmez is the founder of Simple Programmer


(http://simpleprogrammer.com), where he tirelessly pursues his vision of
transforming complex issues into simple solutions
Course info

LevelBeginner
Rating
(3170)
My rating
Duration4h 12m
Released4 Nov 2011

Share course

Vous aimerez peut-être aussi