IntroductionWelcome| 00:04 | Hi! My name is David Gassner.
| | 00:06 | And I'd like to welcome you
to Java Essential Training.
| | 00:09 | If you want to build native Android apps,
dynamic web applications for use on a
| | 00:13 | Java Enterprise Edition Server or
applets that are delivered through a web
| | 00:18 | browser, you need to know Java.
| | 00:20 | In this course I'll show you how to
download and install the Java Development
| | 00:24 | Kit on Windows and Mac OS X and how
to get started with Eclipse, the free
| | 00:30 | cross-platform IDE for Java
developers from the Eclipse Foundation.
| | 00:34 | I'll introduce you to the basics of the
programming language including its data
| | 00:39 | types, keywords and best practices.
| | 00:42 | Since Java is a peer object-oriented
language I'll describe how it implements
| | 00:46 | concepts like encapsulation,
inheritance, and polymorphism.
| | 00:51 | The goal of this course is to get you
started with Java so you can go on to
| | 00:55 | build mobile, desktop, Web or
other types of applications.
| | 01:00 | So let's get started learning Java.
| | Collapse this transcript |
| Is this course for you?| 00:00 | This course, Java Essential Training is
designed to teach you the basics of the
| | 00:05 | Java programming language.
| | 00:07 | You might be asking yourself whether
this is the right course for you, and here
| | 00:10 | are some questions to ask.
| | 00:12 | First of all, what kind of
software do you want to create?
| | 00:15 | Java is used to program a
variety of applications.
| | 00:19 | You can use Java to build Web-based
dynamic applications using programming
| | 00:24 | models known as servlets or Java
Server Pages, also known as JSP.
| | 00:29 | Java is also used to program mobile
applications, that is, applications that are
| | 00:34 | for the Android or BlackBerry mobile
platforms, both phones and tablets.
| | 00:39 | And there are many other types of
applications you can build with Java, and I'll
| | 00:43 | explain some of these in later videos.
| | 00:45 | There are some things however that Java is not.
| | 00:48 | Java is not JavaScript.
| | 00:50 | JavaScript is the dynamic scripting
language that's incorporated into all modern
| | 00:55 | Web browsers and is used to create
dynamic applications where the application
| | 01:00 | code is executed by the browser itself.
| | 01:03 | Even though Java and JavaScript
share the term Java, they are very
| | 01:07 | different languages.
| | 01:09 | They have some similarities in their
syntax and appearance, but the way you use
| | 01:13 | them and the way they work
internally is completely different.
| | 01:17 | So if your goal is to learn how to
build dynamic webpages, where the code is
| | 01:21 | executed in the browser, you
should be learning JavaScript.
| | 01:25 | Java is also not used to build
native mobile apps for all platforms.
| | 01:29 | It isn't used to build native iOS
applications that is applications for
| | 01:34 | the iPhone and iPad.
| | 01:35 | For that you should use Objective C and
the Xcode IDE, and it's also not used to
| | 01:41 | build native Windows Phone applications.
| | 01:44 | Windows Phone is the operating system
of the new phone platform from Microsoft.
| | 01:49 | For those types of applications you
should use either C# or VB.NET and some
| | 01:54 | version of the Visual Studio environment.
| | 01:57 | Some people think that Java isn't
the easiest language in the world.
| | 02:01 | It is a compiled language and it
has very strict data typing rules.
| | 02:05 | And in order to be effective in
Java you need to understand something
| | 02:09 | about object-oriented programming,
but I'll be teaching you all that
| | 02:12 | during this course.
| | 02:14 | And the other thing that's true of
Java is that it's not the most difficult
| | 02:17 | language in the world.
| | 02:19 | Java is an incredibly consistent language.
| | 02:22 | Once you learn the rules of Java,
once you learn how to think in the
| | 02:25 | languages' terms you will find that
you can extend your tools and your
| | 02:29 | capabilities very, very quickly.
| | 02:32 | So who is the target
audience for this particular course?
| | 02:36 | The course is designed for anybody who
wants to build software using the Java
| | 02:39 | programming language, but specifically
it's designed for those who already have
| | 02:44 | a basic programming vocabulary.
| | 02:47 | Software developers as with many
trades have their own unique vocabulary
| | 02:52 | incorporating terms that they all understand.
| | 02:55 | Many of these terms have different
meanings from one programming language to
| | 02:59 | another, but programmers can talk to each other.
| | 03:02 | So if you are not sure whether you
have that vocabulary already in place,
| | 03:06 | here is a little test.
| | 03:08 | Can you answer these questions?
| | 03:10 | You don't have to answer them in the
context of Java, but can you answer these
| | 03:15 | very simply in reference
to any programming language?
| | 03:18 | First, what is a programming statement?
| | 03:21 | What is a variable?
| | 03:22 | What is a function, and what is a
condition or a logical condition?
| | 03:27 | If you can answer these questions
then you are ready for this course.
| | 03:31 | I'll show you how these terms are used
in Java and how they are implemented in
| | 03:36 | this particular programming language.
| | 03:39 | If these terms are foreign to you and
you haven't worked with any programming
| | 03:43 | languages before, you might
first want to watch this course.
| | 03:47 | Foundations of Programming: Fundamentals.
| | 03:50 | This Lynda.com course explains
these terms and shows you how they are
| | 03:54 | implemented in a variety of
programming languages, including Java;
| | 03:58 | and after you watch this course
you'll be completely ready for Java
| | 04:01 | Essential Training.
| | 04:04 | For those who can answer those
questions and who might have worked in at least
| | 04:07 | one previous programming language,
you'll find that certain programming
| | 04:11 | languages get you ready for
Java more easily than others.
| | 04:15 | Java is a C-Style language, that is,
its syntax and basic appearance look very
| | 04:21 | much like the language C and there are
a number of programming languages who
| | 04:25 | share these characteristics.
| | 04:28 | If you've worked in any of these languages
you'll recognize Java very, very quickly.
| | 04:33 | They include C, C++, C#,
JavaScript, and even PHP.
| | 04:42 | All of these languages share basic
syntax rules, and you'll be able to adapt
| | 04:47 | your existing knowledge to Java very fast.
| | 04:50 | If you've worked in any other
languages those languages might not match the
| | 04:54 | basic appearance of Java.
| | 04:56 | These might include Visual Basic or VB.
NET or ColdFusion developers, ColdFusion
| | 05:02 | Markup Language or
Assembly language and many others.
| | 05:06 | If you know any of these languages
or any others that don't share C-Style
| | 05:11 | syntax, you should still be ready for
this course because along the way I am
| | 05:15 | going to explain Java syntax and Java
concepts, and how to use Java variables
| | 05:22 | statements, functions, and conditional logic.
| | 05:25 | As long as you've worked in some
programming language and can answer those basic
| | 05:29 | questions, you are ready.
| | 05:31 | So let's get started learning
the Java programming language.
| | Collapse this transcript |
| Using the exercise files| 00:00 | If you are a premium member of the
lynda.com Online Training Library or if you
| | 00:04 | are watching this course on a disc,
you'll have access to the Exercise Files
| | 00:08 | that are delivered with the course.
| | 00:10 | I've copied the Exercise Files to my Desktop,
but you can place them anywhere on your system.
| | 00:15 | The Exercise Files for this course
consists of a set of Java project files built
| | 00:20 | for use in Eclipse, but the source
code in these project files can be used in
| | 00:24 | any Java development environment.
| | 00:26 | On my system there is a file named .metadata.
| | 00:29 | You won't see it on your system if you
haven't opened Eclipse yet, but it will
| | 00:33 | be created automatically as you
work through the course's exercises.
| | 00:37 | Each chapter is represented by a
folder in the main Exercise Files folder.
| | 00:41 | So for example Chapter 03
has a set of four subfolders.
| | 00:46 | Each of these subfolders is an Eclipse project.
| | 00:49 | For example the APIDocs folder
contains an Eclipse project for learning
| | 00:54 | about API documentation.
| | 00:56 | Within this folder you'll see a
source folder that contains the actual Java
| | 01:00 | source code and a bin folder where
the application is being compiled.
| | 01:06 | If you are working on Windows you'll also
see these two files .classpath and .project.
| | 01:11 | These are files that are generated by
Eclipse and that are used to configure
| | 01:15 | the Eclipse project.
| | 01:17 | If you are working on Mac you might not see
these files in Finder but they are still there.
| | 01:22 | Here is how you use each project.
| | 01:27 | I'll open Eclipse, which I'll show
you how to install very early in the
| | 01:30 | course, and I'll show you that in this copy
of Eclipse I already have four projects open.
| | 01:35 | Now I am going to import another project.
| | 01:38 | From the menu I'll choose File>
Import>Existing Projects into Workspace.
| | 01:44 | I'll click Browse and
navigate to my Exercise Files.
| | 01:49 | If I choose this folder as my root
folder I'll see all available projects
| | 01:54 | throughout the entire folder including
all of the beginning projects and all of
| | 01:59 | the solution projects.
| | 02:01 | Alternatively you might decide you just
want to import one chapter's worth of projects.
| | 02:06 | I'll choose 04_Primitives and
now I'll see a much shorter list.
| | 02:11 | Or you can choose to
import just a single project.
| | 02:15 | This time I'll choose 04_Primitives>
Booleans and click OK, and I'll see only the
| | 02:21 | project in that folder.
| | 02:22 | Whether you import one project at a
time or a whole chapter or all the projects
| | 02:27 | for the entire course it's completely up to you.
| | 02:31 | When you are done with a project I
recommend that you at least close it or
| | 02:35 | optionally delete it from Eclipse.
| | 02:37 | To close a project right-click on it in
the Package Explorer and close the project.
| | 02:43 | If you prefer to get rid of the
project completely just select the project
| | 02:47 | folder and press Delete.
| | 02:49 | You'll be prompted to remove the
project from the Eclipse workspace.
| | 02:54 | Don't check this option and then the
project will still be there on disc.
| | 02:58 | If you do check the option you are
actually deleting the project and all of
| | 03:02 | its source code from the disc and you'll have
to extract it from the Exercise Files again.
| | 03:07 | So that's a look at how to work with
the exercise files for this course.
| | 03:11 | If you don't have access to the
Exercise Files you can use your own Java code.
| | 03:16 | In each video in the course I'll show
you all of the code that I am working with.
| | 03:20 | So you can either copy that code
into your application or you can create
| | 03:24 | your own custom code as you begin
the process of learning the Java programming language.
| | Collapse this transcript |
|
|
1. What Is Java?The history of Java| 00:00 | The Java programming
language has a long history.
| | 00:03 | It started in 1991 when Sun Microsystems
began something called The Green Project.
| | 00:10 | The goal of The Green Project was to
create a new portable programming language,
| | 00:15 | one that could be used to create
applications that could be run on multiple
| | 00:18 | operating systems without
having to recompile or port the code.
| | 00:23 | The original name of the language was
Oak, for a large oak tree that stood
| | 00:28 | outside the windows of the developers' offices.
| | 00:30 | But between the time the project began
and the time the language was released,
| | 00:34 | it was renamed as Java supposedly
because of the amount of coffee that the
| | 00:39 | developers were drinking.
| | 00:41 | Java was first released to the
public in 1995 and thereafter saw a rapid
| | 00:46 | evolution and change.
| | 00:48 | Starting in 1995 the phrase Write
Once, Run Anywhere was popularized.
| | 00:54 | Again the goal of Java was that you'd
be able to write a program, you'd be able
| | 00:58 | to compile it once and then run it
on UNIX, on Windows, on Mac, and other
| | 01:05 | operating systems for which
there was a Java virtual machine.
| | 01:09 | Java evolved swiftly.
| | 01:12 | In the early years there was a
new release about once a year.
| | 01:16 | In 1996, Sun released the first complete
Java Developers Kit or JDK supporting a
| | 01:22 | broad range of application development
tasks, version 1.1, the following year
| | 01:28 | saw improvements to the object-
oriented nature of Java with Inner classes and
| | 01:32 | JavaBeans, the JDBC API for talking
to databases, RMI or Remote Method
| | 01:39 | Invocation for distributed systems,
and Reflection for improving the dynamic
| | 01:45 | capabilities of the language.
| | 01:47 | In 1998, Java was rebranded as
J2SE or Java 2 Standard Edition.
| | 01:55 | The Standard Edition distinguished it
from Enterprise Edition which was the
| | 01:59 | framework for building
large scale Web applications.
| | 02:03 | The version number was Java 2, version 1.2.
| | 02:07 | A little confusing, and the 2 after the
J stuck around for many, many years, but
| | 02:12 | the versions were
incremented using point numbers.
| | 02:15 | Java2SE 1.2 included the swing
graphical API for building Desktop applications,
| | 02:23 | the collections framework for managing
multiple data elements, and new tools
| | 02:28 | including the Just-In-Time compiler and
the Java Plug-in which standardized the
| | 02:33 | version of Java across Web browsers.
| | 02:35 | A couple of years later J2SE 1.3
added new tools including the HotSpot JVM,
| | 02:42 | a new version of the Java Virtual machine,
the Java Sound API and improved debugging.
| | 02:48 | In 2002 version 1.4 added new tools in
the language, and then in 2004, a major
| | 02:56 | new release came out J2SE 5.0.
| | 02:59 | This version was known both as 1.5 and 5.0.
| | 03:03 | But subsequent new releases
would just use the major numbers.
| | 03:07 | So it'd become 5.0, 6.0, 7.0 and so on.
| | 03:10 | J2SE 5.0 was a major new change for the
language, a new feature called Generics
| | 03:17 | was implemented that lets you
strongly data type collection elements.
| | 03:22 | Enumerations, variable arguments, and
looping with for-each were all improved.
| | 03:28 | And in terms of language syntax this was
really the last major change to the language.
| | 03:34 | Everything since then has
been nibbling around the edges.
| | 03:37 | In 2006 Java 6.0 came out.
| | 03:41 | It improved performance for
database connectivity, improved graphical
| | 03:45 | programming and added other
small features to the language.
| | 03:49 | And then the pace of change slowed,
from 2006 to 2010 Sun Microsystems released
| | 03:57 | occasional maintenance releases to the language.
| | 03:59 | So you'd have Java 6.0
Maintenance Release 10, 11, 12, and so on.
| | 04:04 | And as of this recording Java 6.0
Maintenance Release 29 is the most recent
| | 04:10 | version of that version of Java.
| | 04:12 | Then in 2010 a major event
occurred. Oracle bought Sun.
| | 04:17 | Sun Microsystems and all of its assets
including the Java programming language
| | 04:22 | became a part of Oracle.
| | 04:24 | And as of the time of this recording
Oracle Corporation manages Java along with
| | 04:29 | JCP, the Java Community Process that Sun began.
| | 04:34 | In 2011 J2SE 7 was released.
| | 04:38 | It included minor changes in the language
listed here and some other small scale tools.
| | 04:44 | And we are expecting another version
of Java down the road, possibly known as
| | 04:49 | J2SE 8.0 and it would include many
things that were deferred from the version
| | 04:53 | 7.0 effort including something
called Lambda expressions or closures.
| | 04:58 | If you don't know what those are, don't
worry about it, they are not currently a
| | 05:02 | part of the Java language.
| | 05:04 | So that's what's happened in
the world of Java since it began.
| | 05:08 | Java has been around in strength
since 1995 and it's been used in a lot of
| | 05:13 | programming environments, and I'll
talk about some of those programming
| | 05:16 | environments in the next video.
| | Collapse this transcript |
| Understanding the principles of Java| 00:00 | The Java programming language has been
developed over the years following some
| | 00:04 | very strict principles.
| | 00:06 | The five principles of Java as
declared when Java was created include, first,
| | 00:11 | that it's a simple, object-
oriented, and familiar language.
| | 00:14 | Its simplicity lies greatly in its consistency.
| | 00:18 | Once you learn how to do one thing in
Java, you know how to do it the same
| | 00:21 | way throughout the language because
it never deviates from the way the
| | 00:25 | language is architected.
| | 00:27 | It's an object-oriented language.
| | 00:29 | So once you understand the
principles of encapsulation, inheritance, and
| | 00:34 | polymorphism and how those are
implemented in the Java programming language,
| | 00:38 | you'll have a much better sense of
how to architect your applications.
| | 00:42 | And for developers who've worked with
C-Style languages like C and C++, the
| | 00:48 | syntax of Java is very familiar.
| | 00:51 | Java was created to be robust and secure.
| | 00:54 | Its robustness lies greatly in its
object-oriented characteristics, because
| | 00:59 | you're designing everything as an
object, everything has methods or functions
| | 01:04 | and properties also known as fields.
| | 01:06 | And you create applications by
combining multiple classes together.
| | 01:11 | This lets you create your code in small
chunks and it makes it easy to debug and
| | 01:16 | maintain your applications over time.
| | 01:19 | Java was designed to be portable, so
that you'd be able to compile it once and
| | 01:23 | then run your application on
multiple operating systems and processors.
| | 01:27 | Java was created to be high-performance.
| | 01:30 | The original version of the Java
Virtual Machine wasn't as fast as C++
| | 01:34 | applications, but over the years
it's been improved enormously, and today
| | 01:39 | Java applications run just as fast or
sometimes even faster than applications built in C++.
| | 01:46 | And finally Java was created as an
interpreted language, it supports
| | 01:51 | multithreading and it's dynamic.
| | 01:53 | Interpreted, means that the
application is compiled to a format that's
| | 01:57 | interpreted at runtime rather than
being run as machine code directly, this is
| | 02:03 | what makes the applications portable.
| | 02:05 | It's multithreaded, and it makes it easy
to build applications that do more than
| | 02:09 | one thing at the same time.
| | 02:11 | And it's dynamic, in that it can change
data types at runtime as long as those
| | 02:16 | data types are compatible with each other.
| | 02:19 | Here is the runtime architecture of Java.
| | 02:22 | Again, it's an interpreted
language, the application is compiled to
| | 02:26 | bytecode rather than machine language,
and that's what makes it portable
| | 02:29 | between operating systems.
| | 02:30 | Here is the software stat that's used
at runtime when you run your application.
| | 02:37 | You start with the operating system.
| | 02:39 | You can run Java applications on
Windows, Mac, Linux, Solaris, and any other
| | 02:45 | operating system for which there
is a usable Java Virtual Machine.
| | 02:49 | The Java Virtual Machine you use most
of the time will be the one provided by
| | 02:53 | Oracle, the one that was created by Sun
Microsystems, but there are other JVMs
| | 02:58 | out there provided by IBM, the Virtual
Machine that's provided for Android by
| | 03:03 | Google and many others.
| | 03:06 | On top of the Virtual Machine you add
the core runtime and additional libraries.
| | 03:11 | The core runtime is sometimes called
the Java Class Library, and it consists of
| | 03:16 | all of the functionality that's
provided with the core Java developer toolkit.
| | 03:21 | And finally your application runs on top
of all that once again as compiled bytecode.
| | 03:28 | So let's compare Java to a
couple of popular languages.
| | 03:31 | First C++, Java was originally created
by C++ developers and they had in mind
| | 03:38 | improving the developers' lot.
| | 03:41 | Here are some ways in which
Java is different from C++.
| | 03:44 | If you're a C developer all of
your code can be run in C++ as well.
| | 03:49 | The two languages are compatible with
each other, that's not true for Java.
| | 03:53 | Even though Java has syntax that's very
similar to C and C++, its code is unique.
| | 04:00 | It has its own rules and its own syntax.
| | 04:02 | I have mentioned earlier that C++ is
compiled to native machine language and
| | 04:08 | while that makes it very fast and
gives it access to low-level functions, it
| | 04:12 | means that your application has to be
recompiled for each operating system and
| | 04:17 | processor that you want to target.
| | 04:19 | Java is compiled to bytecode.
| | 04:22 | Because C++ is compiled to native
machine language, it allows direct calls
| | 04:27 | to the native system.
| | 04:28 | In Java there is an interface called
Java Native Interface sometimes called JNI,
| | 04:34 | that lets you call those
native functions through the JVM.
| | 04:37 | C++ lets you write once and then as long
as you followed standard C++ syntax you
| | 04:44 | can recompile for each operating
system you are targeting, whereas the
| | 04:48 | principles of Java say that you
can write once and run anywhere.
| | 04:52 | Java runs in a protected virtual
machine environment, and again, you have to go
| | 04:57 | through that JNI interface to make
those low-level system function calls.
| | 05:02 | Here's a way in which the two
languages are very different.
| | 05:04 | C++ requires explicit memory
management and uses pointers.
| | 05:09 | C++ applications as a result can have
memory leaks and it's up to the developer
| | 05:15 | to make sure that they've sealed up
all the holes in their application.
| | 05:19 | In Java, memory is managed for you.
| | 05:22 | When you create instances of classes
or objects, the Java Virtual Machine
| | 05:27 | automatically allocates the memory.
| | 05:29 | And when you're done with the objects
the JVM sweeps up the memory by destroying
| | 05:34 | dereferenced objects, this is
called the Garbage Collector.
| | 05:38 | This means that in Java applications
you don't have to know specifically how
| | 05:42 | much memory is being used at any given
time, you still have to pay attention to
| | 05:46 | making sure that you only
create the objects you need.
| | 05:50 | And in C++ you can use multiple
inheritance, this means that when you define an
| | 05:56 | object you can inherit
functionality for multiple super classes.
| | 06:00 | The Java inheritance model is single
inheritance so you can only inherit
| | 06:05 | directly from a single superclass.
| | 06:07 | This makes it easier to figure out
where there are problems when your
| | 06:10 | application has bugs.
| | 06:13 | Let's also compare Java to JavaScript.
| | 06:16 | Even though the names of these
languages share the term Java, they are really
| | 06:20 | not closely related.
| | 06:22 | Java again wasn't compatible with
previous languages even though it
| | 06:26 | borrowed syntax from C.
| | 06:28 | Java has morphed into a standard
known as ECMAScript or ECMAScript.
| | 06:34 | Other languages that are based on
the ECMAScript standard include Adobe's
| | 06:38 | ActionScript 3.0 and JScript from
Microsoft and a number of others.
| | 06:44 | Java is compiled to bytecode
and interpreted at runtime.
| | 06:48 | JavaScript is interpreted
directly from source code.
| | 06:52 | Java can make native function calls
through the JNI interface, while in
| | 06:56 | JavaScript at least as it's implemented
in a browser, is restricted to something
| | 07:01 | called a browser Sandbox.
| | 07:03 | It can only play in the Sandbox, and
it can't make native function calls.
| | 07:09 | Java is write once, run anywhere.
| | 07:11 | JavaScript is even more portable in the
sense that it has brought compatibility
| | 07:16 | in many browsers and many operating systems.
| | 07:19 | Java runs in a protected virtual
machine but you have to explicitly have that
| | 07:24 | virtual machine installed.
| | 07:26 | And in a similar fashion JavaScript is
executed by the browser and restricted to
| | 07:31 | that browser sandbox for security.
| | 07:34 | Both languages manage the memory for you,
neither requires that you specifically
| | 07:39 | allocate or deallocate memory.
| | 07:41 | And in terms of inheritance, Java uses
a traditional class-based inheritance
| | 07:47 | where you define classes and
then inherit their functionality.
| | 07:51 | JavaScript uses something
called prototype-based inheritance.
| | 07:55 | This model allows you to add functions,
properties, and other functionality to a
| | 08:00 | pre-defined class at runtime,
something Java doesn't allow you to do.
| | 08:05 | So that's a look at the principles
of Java and how you might compare this
| | 08:09 | language to C++ and JavaScript.
| | 08:13 | In the continuum of languages you
might play C++ at the strictest level, Java
| | 08:19 | somewhere in the middle, and
JavaScript at the most dynamic.
| | 08:23 | And you typically use Java when you
want to build applications that rely on that language.
| | Collapse this transcript |
| Java compilation and syntax| 00:00 | When you download and install Java
from Oracle you are installing a number
| | 00:05 | of development tools.
| | 00:06 | The package is called the Java SE
Development Kit or JDK and it includes the
| | 00:12 | runtime, a compiler, and many other tools.
| | 00:15 | The first tool you'll be using is the compiler.
| | 00:18 | It's an application called javac.
| | 00:21 | And the name of the application will be
the same, regardless of whether you are
| | 00:24 | working on Mac, Windows, Linux
or any other operating system.
| | 00:29 | When you run javac you are provided with
the names of your source code files and
| | 00:33 | the resulting output will
be a set of bytecode files.
| | 00:37 | To run an application you use the command java.
| | 00:41 | Again it looks the same on any operating system.
| | 00:44 | When you run the java command, you'll
provide it with the name of the class that
| | 00:48 | you want to start with.
| | 00:50 | I'll show you an example
of that in a few moments.
| | 00:53 | The JDK also includes many other tools.
| | 00:56 | The jar tool lets you
package up your applications.
| | 01:00 | A complete Java application will
typically consist of many classes, and when you
| | 01:04 | compile the classes, you end
up with a whole bunch of files.
| | 01:08 | But it's a lot more convenient to
deliver the application as a single file, and
| | 01:12 | so you use the jar
application to do that packaging.
| | 01:15 | When you package up the files you end up
with an archive file in zip format, but
| | 01:20 | with the file extension of .jar.
| | 01:23 | The javadoc application lets you create
documentation based on comments in your source code.
| | 01:29 | I'll show you how to use this
in a later video in the series.
| | 01:33 | And there are many other command
line tools that are a part of the JDK.
| | 01:37 | So how do you get started?
| | 01:39 | Well your Java applications are built in
source code files that are pure text files.
| | 01:45 | You can create these text files in any
Text Editor, although, I'll be using the
| | 01:49 | Eclipse Integrated Development
Environment throughout this course.
| | 01:53 | Here is a classic Hello World application.
| | 01:56 | If you've worked in other programming
languages, you might be accustomed to
| | 02:00 | Hello World applications
being just a single line of code.
| | 02:03 | That's not the case in Java.
| | 02:05 | In Java everything is encapsulated
in a class of some kind, including
| | 02:11 | your start-up code.
| | 02:12 | So this bit of code that I have on
the screen represents the simplest
| | 02:16 | possible Java application.
| | 02:18 | The first line of code is
called the package declaration.
| | 02:21 | It indicates the location of the
source code file within your project.
| | 02:26 | The package declaration is typically a
dot separated string, the beginning of
| | 02:30 | the package frequently is your
domain name in reverse order, so lynda.com
| | 02:36 | might become com.lynda.
| | 02:38 | And then the rest of the package
indicates what type of application it might be
| | 02:42 | within your organization.
| | 02:44 | The next line of code is
called the class declaration.
| | 02:47 | If you create a file called HelloWorld.
java it can contain one public class and
| | 02:54 | the name of the class must match the
name of the file, so the HelloWorld.java
| | 02:58 | file contains a public class named
HelloWorld and notice they match exactly.
| | 03:04 | Java is a case-sensitive language and
you must match these strings precisely.
| | 03:09 | Within the class there is
something called a main method.
| | 03:13 | When you run a Java application from
the command line Java will look for this
| | 03:18 | particular method and execute it automatically.
| | 03:21 | The name of the method or
function must be main lower case.
| | 03:25 | And the three keywords previous to
the function name public, static, and
| | 03:30 | void are also required.
| | 03:32 | I'll explain what they mean later on.
| | 03:35 | The main method must receive
something called an argument and it must be
| | 03:39 | an array of strings.
| | 03:41 | This allows you to pass an information to the
application as you run it from the command line.
| | 03:46 | We call that the args argument.
| | 03:49 | Finally within the main method,
you place your executable code.
| | 03:54 | This application simply outputs the
text Hello World to the command line using
| | 03:58 | the command System.out.println or print line.
| | 04:03 | Notice that this string
is ended with a semicolon.
| | 04:07 | The semicolon is like a period in English,
it means this is the end of the statement.
| | 04:12 | So System.out.println("Hello World") means
output the string Hello World to the command line.
| | 04:20 | So you create that source code file and you
place it somewhere in your project folder.
| | 04:26 | Now in this case I have declared a
package named com.lynda.javatraining;
| | 04:31 | and so I have to place the
source code file in an equivalent
| | 04:34 | subfolder structure.
| | 04:36 | If HelloWorld is the name of my project
folder, then com\lynda\javatraining is
| | 04:42 | my package folder, matching the dot
separated package as declared in the source code.
| | 04:49 | The name of the file as I have
indicated before is HelloWorld.java.
| | 04:54 | The .java extension is required
in all of your source code files.
| | 04:59 | To actually compile that file, I
would start at the project directory
| | 05:03 | HelloWorld, I would execute the javac
command and I'd reference the Java source
| | 05:08 | code file HelloWorld.
| | 05:10 | Notice that I am prefixing the name of
the file with a slash separated syntax,
| | 05:15 | com\lynda\javatraining\ and
then the name of the file.
| | 05:20 | This screenshot comes from Windows, so
I am using backslashes, but if you were
| | 05:24 | working on Mac you would use forward slashes.
| | 05:27 | After compilation you end up with a new
file, the original source code file was
| | 05:32 | HelloWorld.java, the resulting
compiled file is HelloWorld.class.
| | 05:38 | The .class file is your bytecode file,
and because this is an application that
| | 05:42 | only has the single class, that .class
file comprises your entire application.
| | 05:48 | So in fact when you are delivering the
application you don't have to deliver the
| | 05:52 | .java file, you only deliver the classes.
| | 05:56 | Now to run the application from the
command line I would use the java command.
| | 06:01 | I would once again start in the
project directory HelloWorld and I'd call the
| | 06:05 | class using dot separated syntax,
just like the package was declared in the
| | 06:10 | source code, com.lynda.javatraining.HelloWorld.
| | 06:16 | And notice that when I run the
application I am not referencing the file
| | 06:20 | extension .class, I am only
referencing the class name, HelloWorld.
| | 06:26 | The application runs and the
resulting output appears in the console.
| | 06:31 | So that's a look at basic Java syntax
and how you would compile and run a very
| | 06:36 | simple application from the command line.
| | 06:38 | Now throughout the rest of the course,
I'll be showing you how to do this in the
| | 06:42 | Integrated Development
Environment called Eclipse.
| | 06:45 | And for the most part you'll be
protected from compiling and running directly
| | 06:49 | from the command line, but it's
important to know that if you want to work in
| | 06:52 | this way you certainly can.
| | 06:54 | So once you've learned how to
work in Java, where can you use it?
| | 06:58 | Well Java is implemented in many
environments and used for many different
| | 07:02 | kinds of applications.
| | 07:04 | You can use Java for Desktop
applications either actually installed on the
| | 07:08 | Desktop or delivered through browsers
as Java applets embedded in HTML pages.
| | 07:14 | These are called Graphical Java
applications and they use libraries called Swing
| | 07:19 | and AWT to build their visual presentation.
| | 07:23 | You can also use Java to build dynamic
Web applications, that is, applications
| | 07:28 | that are delivered to the browser as HTML,
dynamically generated at runtime on a server.
| | 07:34 | These are sometimes called J2EE
or simply Java Enterprise Edition
| | 07:38 | applications and they are executed
within server environments such as Tomcat
| | 07:43 | from Apache or JBoss.
| | 07:45 | The code is written using models
called servlets and JavaServer Pages.
| | 07:50 | It's exactly the same language as you
might use on the Desktop but it's simply
| | 07:54 | modeled a little bit differently.
| | 07:56 | And one of the most popular recent
uses of Java is on mobile devices.
| | 08:00 | The Google Android environment uses
its own compiler called Dalvik and tools
| | 08:06 | provided by Google that run in
Eclipse to build applications that run on
| | 08:10 | Android phones and tablets.
| | 08:12 | The BlackBerry Operating System also
uses Java, so you can use Java to write
| | 08:17 | applications that run on BlackBerry
phones, and you can use Java in many other
| | 08:21 | mobile environments as well.
| | 08:24 | You can in fact use Java to build all
sorts of applications, games, mobile apps,
| | 08:29 | cloud computing applications,
distributed systems, databases, websites embedded
| | 08:35 | systems, image management, enterprise
information management, and many more.
| | 08:39 | So now that you've had a sense of how
Java is architected its history, its
| | 08:44 | principles, its syntax and how you
compile and run Java applications, it's time
| | 08:50 | to get started with installing
Java and writing your own code.
| | Collapse this transcript |
| Choosing a development environment| 00:00 | One of the first things you should
do when you are working with Java is
| | 00:03 | to choose an editor.
| | 00:05 | A product you can use to create your
Java source code files and which if it's a
| | 00:09 | completely Integrated Development
Environment can also help you build and
| | 00:13 | compile your applications.
| | 00:15 | The truth is, Java source code files
are just text files, so you can really use
| | 00:20 | any Text Editor you are comfortable with.
| | 00:22 | If you know how to use older developer
editors such as Vi or Emacs or if you are
| | 00:28 | a Windows developer and you
love notepad, those will do fine.
| | 00:32 | But there are many Integrated
Development Environments or IDEs available
| | 00:36 | for Java developers.
| | 00:37 | One of the first questions you should
ask is, which operating system do you
| | 00:41 | want to develop on?
| | 00:42 | Java applications are designed
to be write once, run anywhere.
| | 00:46 | So once the application is built you
should be able to deploy it on multiple
| | 00:50 | operating systems, but you as a
developer probably have your favorite operating
| | 00:54 | system that you like to work on.
| | 00:56 | So perhaps you are looking for an
editor that's specifically designed for Mac
| | 00:59 | OS X or maybe you are a Windows developer and
you have no plans ever to work on Mac or Linux.
| | 01:06 | But you will find in the world of
Java that many of the best development
| | 01:09 | products out there are cross-
platform and work on all operating systems
| | 01:14 | including Windows, Mac,
Linux and other variants of UNIX.
| | 01:19 | Another question you should ask is,
am I willing to pay a license fee?
| | 01:23 | Many of the best development
environments are completely free, including
| | 01:27 | Eclipse and NetBeans, but when you
start looking at some of the paid options
| | 01:32 | you might find advanced features that
are worthwhile, especially if you are
| | 01:36 | going to be working in a team
development environment where you're building
| | 01:39 | very large scale applications.
| | 01:42 | I think that if you are a new Java
developer you'll find that one of the free
| | 01:46 | IDEs does everything you need
when you are getting started.
| | 01:49 | And later on when you start building
very large scale applications it's worth
| | 01:53 | checking out some of the paid options.
| | 01:55 | Here are some of the options that are
available exclusively on Mac OS X. The
| | 02:00 | first one might be a bit surprising, it's Xcode.
| | 02:04 | We know Xcode as the primary
development environment for building Mac and iOS
| | 02:09 | applications, Xcode is completely free
and available from the Mac App Store and
| | 02:15 | it does have rudimentary Java support.
| | 02:18 | It's best for small scale projects though.
| | 02:20 | It doesn't have a lot of the
capabilities that development environments that are
| | 02:24 | designed for Java have.
| | 02:26 | And also because Apple has been pulling
back from support for Java over the last
| | 02:30 | couple of years, for example the
latest version of Mac OS X Lion is delivered
| | 02:36 | without a Java runtime environment
already installed, we don't know how much
| | 02:40 | support there will be for Java in the future.
| | 02:43 | But if you are already comfortable
with Xcode and know how to navigate around
| | 02:46 | it, it's worth checking out.
| | 02:49 | Other options that are unique to Mac
OS X are two products that are related
| | 02:53 | called BBEdit and TextWrangler.
| | 02:55 | These products are both from the same
company and they support syntax coloring,
| | 03:00 | function scanning, and other tasks
that are common to programmers, editors.
| | 03:05 | Neither of these tools is a
specialist IDE for Java, that is, they weren't
| | 03:09 | designed specifically for use with
Java, but again if you are already
| | 03:13 | comfortable with these tools and you
like products that really take seriously a
| | 03:18 | Mac style interface these are worth looking at.
| | 03:21 | BBEdit is a commercial product
and requires a paid license, while
| | 03:25 | TextWrangler is free.
| | 03:27 | Both products are available from www.
barebones.com and at least TextWrangler is
| | 03:33 | available from the Mac App Store as well.
| | 03:36 | If you are a Windows developer and
you have no plans to work ever on Mac or
| | 03:40 | Linux, you can check out some of the
light-weight Java development environments
| | 03:44 | that are specifically built for Windows.
| | 03:46 | One of the most popular is called JCreator.
| | 03:50 | There are two editions, one free and
one paid, and it has a very similar
| | 03:54 | interface to a Text Editor called TextPad.
| | 03:57 | It has the same layout of panels, menus,
and configuration options, but both of
| | 04:02 | these products are
specifically designed for use with Java.
| | 04:05 | JCreator is a very light-weight
application, it starts up incredibly quickly
| | 04:11 | compared to products like Eclipse and NetBeans.
| | 04:14 | And both versions JCreator LE
and JCreator Pro are available
| | 04:19 | from www.jcreator.com.
| | 04:22 | And speaking of TextPad, you can also
use this very popular shareware product to
| | 04:27 | build small scale Java applications.
| | 04:30 | TextPad has the ability to hook into
the JDK commands, such as java and javac
| | 04:35 | the compiler to compile and
run small Java applications.
| | 04:40 | It's shareware, not free, but it's
pretty inexpensive, and it's available
| | 04:44 | from www.textpad.com.
| | 04:48 | So that's a look at products
that are unique to Mac and Windows.
| | 04:52 | But most of the Java developer
community uses cross-platform Java IDEs.
| | 04:57 | The whole idea of Java is portability.
| | 05:00 | The idea that you can build a single
application and then run it on multiple
| | 05:04 | platforms without recompiling and
being able to do the same thing, move
| | 05:08 | among operating systems and use basically the
same IDE is very appealing to Java developers.
| | 05:15 | So here are two free IDEs that work on
Mac, Windows, Linux, and other platforms.
| | 05:21 | NetBeans was originally created by Sun
Microsystems and is now owned and offered by Oracle.
| | 05:28 | In addition to Java, NetBeans has
editions that support C, C++, and PHP.
| | 05:34 | Some distributions of NetBeans have an
included Java Enterprise Edition server.
| | 05:39 | So if your goal is to build Java-based
Web applications, NetBeans gives you the
| | 05:43 | ability to get everything you need
in a single download and installation.
| | 05:48 | You can download NetBeans from netbeans.org.
| | 05:51 | Eclipse is one of my favorite cross-
platform IDEs for Java and is the IDE that
| | 05:56 | I'll be using throughout this course.
| | 05:59 | Eclipse is open source and completely free.
| | 06:02 | It was originally built as a Java
Development Environment By IBM, before IBM
| | 06:06 | gave it to the Eclipse Foundation.
| | 06:08 | But now Eclipse is also used for many
languages and development environments.
| | 06:13 | For example if your goal is to build
Android applications with Java, I highly
| | 06:18 | recommend Eclipse because the Android
developer tools from Google are also
| | 06:23 | delivered as an Eclipse plug-in.
| | 06:25 | So you can take your Eclipse
installation for Java, add-in the Android SDK tools
| | 06:30 | and you'll have everything you
need in one development environment.
| | 06:34 | You can download all the
different distributions of Eclipse
| | 06:37 | from www.eclipse.org.
| | 06:40 | And like NetBeans you'll see that
there are distributions available from many
| | 06:43 | operating systems including Windows, Mac,
Linux, and so on, and also support for
| | 06:49 | many programming languages.
| | 06:51 | Once you move out of the completely
free IDEs, you start getting into a set of
| | 06:56 | products that are really designed
for large scale team development.
| | 07:00 | IntelliJ Idea is the first one.
| | 07:03 | There is a free version known as
community and a paid edition known as
| | 07:06 | Ultimate of IntelliJ Idea.
| | 07:09 | IntelliJ Idea has its own support
for Android development, and again it's
| | 07:13 | cross-platform like Eclipse and
NetBeans, so you can install it for Windows,
| | 07:17 | Mac, or Linux, and you can take a
look at it at www.jetbrains.com/idea.
| | 07:24 | And finally there is JBuilder.
| | 07:27 | At one time JBuilder was the dominant
Java developing environment in the world.
| | 07:32 | That was in the late 90s though, and
since that time with the introduction of
| | 07:35 | Eclipse and NetBeans things
have evened out quite a bit.
| | 07:39 | But JBuilder remains a very
powerful Integrated Development
| | 07:42 | Environment primarily used by
large development teams on large scale
| | 07:46 | enterprise applications.
| | 07:49 | JBuilder was originally created by
Borland, and again it was designed for
| | 07:52 | enterprise-level development.
| | 07:55 | You can take a look at JBuilder at
www.embarcadero.com/products/jbuilder.
| | 08:03 | This survey of IDEs for Java gives you
a sense of the amount of variety that's
| | 08:08 | out there, and there are many programmers,
editors that I haven't mentioned that
| | 08:12 | could work fine for Java development.
| | 08:15 | I encourage you to look at these options
and other options you might find on the
| | 08:18 | Web and choose the development
environment that's best for you.
| | 08:22 | As you work through this course, I'll
encourage you though to use Eclipse, the
| | 08:26 | same IDE that I'll be demonstrating
the code with because it will let you
| | 08:30 | follow along and do the exercises using the
same look-and-feel as you see on the screen.
| | 08:35 | And once you get into building your
applications though, choose any of these
| | 08:39 | IDEs for your own Java development.
| | Collapse this transcript |
|
|
2. Installing the SoftwareInstalling Java on Windows| 00:00 | If you're working on Microsoft
Windows, the first step is to download and
| | 00:04 | install the Java Development Kit from Oracle.
| | 00:07 | You can get the Java Development
Kit from this URL java.oracle.com.
| | 00:13 | This link will take you take you to the
current homepage for the Java technology.
| | 00:18 | On this screen, look under Software
Downloads and locate the link for Java SE.
| | 00:23 | This is the Java SE Downloads
screen, take a look at the list of
| | 00:27 | available downloads.
| | 00:29 | The most recent version of
Java will be listed at the top.
| | 00:32 | As of the time of this recording, the
most recent version of Java was Java SE 7u1.
| | 00:39 | Notice that there are two different
download links one for JDK, the Java
| | 00:44 | Development Kit and one for JRE, the
Java Runtime Environment. You want the JDK.
| | 00:50 | It actually includes both downloads
in one package, you'll be able both to
| | 00:55 | develop Java applications and run them.
| | 00:58 | Now, even though Java 7 was
finalized for Windows as of the date of this
| | 01:02 | recording, there was not a similar
final version of Java 7 for Mac OS X. So for
| | 01:07 | this course, I'm primarily using Java 6
to make sure that both operating systems
| | 01:12 | can run all the code I'll be showing.
| | 01:15 | To get Java 6, scroll down a little
bit further and you'll see a link for the
| | 01:19 | most recent version of Java 6,
which as of this point is Update 29.
| | 01:24 | Click the Download link under JDK.
| | 01:28 | Here's a listing of all the installers
for the Java Development Kit version 6.
| | 01:33 | You'll need to accept the License
Agreement before you can download anything.
| | 01:36 | But then for Windows,
take a look at the options.
| | 01:39 | There are three versions.
| | 01:41 | Most developers will want either the 32-
bit which is Windows x86 or the 64-bit
| | 01:47 | versions, which is Windows x64.
| | 01:50 | If you're not sure whether you're
running 32 or 64-bit Windows you can find out
| | 01:54 | from the Control Panel.
| | 01:56 | Go to the Start menu, choose Control
Panel and if you're working on Windows
| | 02:00 | Vista or Windows 7, follow these steps.
| | 02:03 | Go to System and Security and then to System.
| | 02:07 | If you're working on Windows XP, you can
just click System in the Control Panel.
| | 02:12 | Take a look at the System type.
| | 02:14 | If it says 64-bit Operating System,
that's the version of Java you want and if
| | 02:19 | it says 32-bit that's the version you want.
| | 02:22 | Now that you know which version of
Windows you're running, go back to the Oracle
| | 02:26 | webpage and download the right
version of Java for your version of Windows.
| | 02:31 | I've downloaded the 64-
bit version to my desktop.
| | 02:35 | Now, I'm going to run the installer.
| | 02:37 | If you're working on Windows XP,
you can just double click it and if
| | 02:40 | you're working on Windows Vista or Windows 7,
right click and choose Run as administrator.
| | 02:46 | When you're prompted, click
Yes to allow the program to run.
| | 02:50 | The rest of the process
is pretty straightforward.
| | 02:52 | On this option screen, you're asked which
element of the Java Development Kit you want.
| | 02:57 | I recommend accepting
everything and clicking Next.
| | 03:01 | The first part of the installation
is copying over the files you need for
| | 03:04 | development that is the commands such
as java, javac, jar, javadoc and others.
| | 03:11 | Once this primary installation is done,
a secondary installation will pop-up and
| | 03:16 | that will be for the Java
Runtime Environment or JRE.
| | 03:20 | When you're prompted for the
installation of the JRE, once again click through
| | 03:23 | the process and allow the
installation to complete.
| | 03:28 | When you see this screen,
the installation is complete.
| | 03:31 | Click Finish and if you're prompted in a
web browser to register, you can either
| | 03:36 | choose to register or not.
| | 03:38 | I'm just going to close the browser.
| | 03:40 | Now, let me show you where Java is installed.
| | 03:43 | I'll go to Windows Explorer, from there
I'll go the C:\program files folder and
| | 03:49 | under there you'll see a folder named
Java and within that folder two subfolders
| | 03:54 | for the Development Kit and the JRE.
| | 03:57 | The jdk folder has a folder named bin
or b-i-n and this folder contains all of
| | 04:03 | the development applications.
| | 04:05 | Java, which is used to run
applications from the command line, javawm, which
| | 04:10 | is specifically designed to run applications
on Windows, javac the compiler and many others.
| | 04:17 | Now you're going to want to add this
folder to your system path to make it easy
| | 04:22 | to run applications from the command line.
| | 04:24 | So on Windows Vista or 7, I'm going to
click on the folder icon here and that
| | 04:29 | turns the folder structure into a
string I can copy to the clipboard.
| | 04:34 | Now I'll add that string to my system path.
| | 04:37 | I'll go back to the Control Panel again.
| | 04:39 | Now, you can set your environment
variable from a screen that's fairly well
| | 04:43 | buried in the Control Panel, but an
easy way to get there is to click into the
| | 04:47 | search box, this works only on Vista
and Windows 7 not on Windows XP, and type
| | 04:52 | in environment or some part of that string.
| | 04:56 | This will take you to links
for system environment variables.
| | 04:59 | I recommend setting the system
environment variables for the entire computer
| | 05:03 | not just your account.
| | 05:04 | I'll click the link and
that takes me to this screen.
| | 05:08 | If you're working on Windows XP, you
can just go to the Control Panel's System
| | 05:12 | Panel and you'll find a very similar option.
| | 05:16 | Click Environment Variables, scroll
down in the list of System variables
| | 05:20 | and locate the path.
| | 05:22 | Click and then edit.
| | 05:25 | Place the cursor at the end of the string.
| | 05:27 | Make sure that there is a semicolon at
the end so that it terminates whatever is
| | 05:31 | the last value in this variable.
| | 05:33 | Paste in the location of the bin folder at the
end and then for housekeeping add a semicolon.
| | 05:39 | Click OK, click OK and click OK again.
| | 05:44 | Now to test your path and to make sure
you're running the right version of Java,
| | 05:49 | go to a command window.
| | 05:51 | I'll go to the Start menu and type cmd.
| | 05:54 | If you're working on Windows XP, choose the
appropriate option to open a command window.
| | 06:00 | That opens up a command window on my system.
| | 06:03 | I'll first test Java the
applications that you run.
| | 06:05 | I'll type java-version and that tells
me that my runtime Java is 1.6.0.29 that
| | 06:15 | is Java 6 Update 29.
| | 06:18 | Now, I'll check my compiler, javac -
version, and once again I see that I'm
| | 06:25 | running the right version of Java.
| | 06:28 | If you can execute the runtime
command java and the compiler command
| | 06:32 | javac, you're ready.
| | 06:34 | You've installed Java on your
system and you're ready for the next step
| | 06:39 | installing a development environment.
| | Collapse this transcript |
| Installing Eclipse on Windows| 00:00 | Once you've installed and verified
your copy of Java, the next step is to
| | 00:04 | install an Integrated Development Environment.
| | 00:07 | While you can program and compile Java
applications directly from the command
| | 00:10 | line, an IDE such as Eclipse
will make things a whole lot easier.
| | 00:14 | I'll be using the Eclipse
IDE throughout this course.
| | 00:17 | You can download a free copy of
Eclipse from www.eclipse.org/downloads.
| | 00:25 | On this screen, you'll see a listing
of the various distributions of Eclipse.
| | 00:29 | I recommend that you use the
Eclipse IDE for Java Developers.
| | 00:33 | You'll also see a larger
distribution for Java EE or Enterprise
| | 00:37 | Edition Developers.
| | 00:38 | Because we won't be building
Enterprise web applications in this course, you
| | 00:42 | don't need all the tools that
are a part of that distribution.
| | 00:45 | Over on the right, you'll see that there
are 32-bit and 64-bit versions of Eclipse.
| | 00:50 | As with Java, make sure you know which
version of Windows you are running and
| | 00:54 | choose the matching version of Eclipse.
| | 00:56 | I've downloaded the 64-bit version of the
Eclipse IDE for Java Developers to my desktop.
| | 01:02 | Eclipse is delivered as an
achieve file in zip format.
| | 01:06 | To install it, you simply
extract the contents of the zip file.
| | 01:10 | I don't have any special zip utilities
installed on my system, so when I double
| | 01:14 | click on the zip file it just
opens it up in Windows Explorer.
| | 01:17 | Now, I am going to drag this off to the
right and dock that window on the right
| | 01:21 | side, that's one of my favorite little
Windows 7 tricks and then I am going to
| | 01:25 | drag and drop the eclipse
folder on to my desktop.
| | 01:28 | This is a fairly large file, so
it's going to take a few minutes for it
| | 01:32 | to extract completely.
| | 01:33 | Once it's extracted though the
installation is really complete.
| | 01:37 | You can either leave the eclipse
folder on your desktop or if you want to
| | 01:41 | follow the conventions of Windows you
might move that eclipse folder into your
| | 01:45 | Program Files directory.
| | 01:47 | It's completely up to you though, you can
run Eclipse from anywhere on your system.
| | 01:52 | Once the files are finished being
extracted, I'll move them into my
| | 01:55 | Program Files directory.
| | 01:57 | I'll open Windows Explorer
and go to C:program files.
| | 02:02 | Once again, I'll dock over to the right
and then I'll simply drag and drop this
| | 02:06 | eclipse folder and move it
into the Program Files folders.
| | 02:09 | If prompted for
administrator permission click Continue.
| | 02:12 | Now to run Eclipse, double click the
eclipse folder and then double click eclipse.exe.
| | 02:18 | Depending on your Windows
configuration, you might not see the .exe file
| | 02:21 | extension but you should see this graphic.
| | 02:24 | When I double click, I am
prompted to run the application.
| | 02:28 | For convenience, I'll uncheck the
option to ask before opening the file every
| | 02:31 | time and then I'll click Run.
| | 02:34 | When Eclipse opens for the first time
it will prompt you for something called a
| | 02:37 | workspace directory.
| | 02:39 | I'll talk more about workspace
directories in a later video, but for now you can
| | 02:43 | simply accept the default, which is
a new directory named workspace all
| | 02:47 | lowercase under your home directory.
| | 02:50 | I also recommend that you check this
option, Use this as the default and don't
| | 02:53 | ask again and that will let
Eclipse launch more easily later on.
| | 02:57 | I'll click okay and then after a few moments,
after Eclipse loads all of its resources;
| | 03:03 | it will open on the screen.
| | 03:04 | When you first open Eclipse,
you'll see this welcome screen.
| | 03:08 | You don't need it though so you can
just close that screen and you'll now see
| | 03:11 | the default Eclipse configuration.
| | 03:14 | If you've gotten this far, you are
ready to go onto the next step building Java applications.
| | Collapse this transcript |
| Exploring Java on Mac OS X Leopard and Snow Leopard| 00:00 | If you are working on older versions of
Mac OS X that is version prior to 10.7
| | 00:05 | Lion, Java should already
be installed on your system.
| | 00:09 | But you want to make sure it's installed
and you should make sure you know which
| | 00:12 | version is installed.
| | 00:13 | The easiest way to find out which
version of the Java you have is to go to the
| | 00:17 | Applications folder, then to
Utilities, and then to Java Preferences, an
| | 00:22 | application that lets you see
what you have on your system.
| | 00:25 | In the General tab of the Java
Preferences application I see that there is both
| | 00:29 | a 64 and a 32-bit version of
Java and they are both Java 6.
| | 00:34 | Notice that the internal Version is 1.
6 rather than just 6, but the marketing
| | 00:39 | version is version 6.
| | 00:40 | So I have Java Standard Edition version 6.
| | 00:44 | The version at the top of
the list is my default JDK.
| | 00:48 | And when I build my code whether it's
on the command line or in Eclipse or any
| | 00:52 | other IDE, this is the
version that I'll be using.
| | 00:55 | Now if you don't have this version of
Java you can go get the version you want.
| | 01:00 | Go to a browser and try one of these links.
| | 01:03 | If you are working on Snow
Leopard or 10.6 go to this page
| | 01:07 | support.apple.com/kb/DL1360.
| | 01:12 | There is a Download button there click
the button and follow the instructions to
| | 01:16 | download and install the most recent
version of Java for this version of Mac.
| | 01:21 | If your one version back from
there on Leopard or 10.5 try this page
| | 01:25 | support.apple.com/kb/DL924
again there is a Download link.
| | 01:32 | You may notice that the maintenance version on
this download is only version 15, that's fine.
| | 01:37 | As long as you are using any version of Java 6,
you'll be able to follow along with course.
| | 01:43 | Finally, if you want to be on the
bleeding-edge you can try Java 7 on Mac.
| | 01:47 | At the time of this recording the port
of Java 7 to Mac was not complete but it
| | 01:52 | was in Public Beta or Preview at Oracle.
| | 01:55 | To try it out go to this page jdk7.java.
net/macportpreview, you'll see that it's
| | 02:03 | clearly identified as a
preproduction developer preview release.
| | 02:07 | That means you shouldn't use it for
production application or depend on it for
| | 02:11 | robust mission critical applications,
but if you want to try it, just follow the
| | 02:16 | instructions on this page
for download and installation.
| | 02:19 | Either way, you should have either
Java 6 or Java 7 installed before you
| | 02:24 | continue with the rest of this course.
| | Collapse this transcript |
| Installing Java on Mac OS X Lion| 00:00 | If you are working on Mac OS X version
10.7 or Lion, you'll find that Java is
| | 00:05 | not installed by default on this
version of the operating system.
| | 00:09 | It's up to you to go get Java and install it.
| | 00:12 | This is pretty easy to do, just go
to the Apple website at this URL,
| | 00:16 | support.apple.com/kb/DL1421.
| | 00:23 | Click the Download link and follow
the prompts to download the software.
| | 00:28 | I've downloaded the installer to my desktop.
| | 00:30 | It's a dmg file and when you open it up
it shows a conventional installer package.
| | 00:36 | Run the installer and walk
through all the prompts to install Java.
| | 00:40 | There are no options to take care of,
so the installation is fairly automated.
| | 00:44 | This version of the installer is for
Java SE 6, 1.6.0.26, the latest version of
| | 00:51 | Java for Mac as of this recording.
| | 00:54 | Once you've completed the
installation the next step is to test it.
| | 00:58 | I recommend using Terminal for this.
| | 01:00 | I'll go to the Lion Launchpad
application which opens up my applications.
| | 01:04 | I'll go to Utilities and then to Terminal.
| | 01:08 | Now to test the installation of Java,
first type java, all lower case, then a
| | 01:13 | space and -version, press return and
you should see an output showing you which
| | 01:19 | version of Java is installed on your system.
| | 01:21 | Again I am running Java
6 maintenance release 26.
| | 01:25 | You should also test to make sure you
can get to the Java compiler type javac
| | 01:30 | space -version and once again you
should get a little bit of output.
| | 01:34 | This time just showing the version number.
| | 01:37 | If you can do this much you are in
great shape and you are ready to go to the
| | 01:41 | next step installing Eclipse, but before
you finish up this video, I'll show you
| | 01:46 | where Java is actually installed.
| | 01:48 | You'll need to know this location for certain
configurations tasks during this video course.
| | 01:54 | In Terminal from the command line
type cd space /System, make sure that you
| | 02:01 | are using an uppercase S because Mac OS X is
case sensitive, then /library, then /frameworks.
| | 02:10 | Press Return and the type ls Ja* and
that will show you a listing of everything
| | 02:18 | starting off with the word Java.
| | 02:20 | I am looking for the items at the
bottom of the listing under JavaVM.
| | 02:24 | Framework so I'll type cd then JavaV,
with an uppercase V, and I'll press tab
| | 02:32 | and let Terminal auto
complete the directory name.
| | 02:35 | I'll press Return then I'll issue the
Clear command to clear the screen and then
| | 02:39 | ls to see what's in here.
| | 02:41 | You'll see that there are directories
for Classes, Frameworks, JavaVM and so on.
| | 02:46 | The directory you are interested in is commands.
| | 02:50 | So I'll type cd space Commands and
return and then ls and there are all the Java
| | 02:56 | commands including Java, javac,
javadoc and many, many others.
| | 03:02 | Again you'll need to know this
particular directory location later on in the
| | 03:06 | course when you configure Eclipse to
tell it where certain tools are such as
| | 03:11 | the javadoc command.
| | 03:13 | So now you have installed Java, you've
tested it to make sure you can run both
| | 03:16 | the Java Virtual Machine and the
compiler and you've seen where the Java files
| | 03:21 | are installed and you are ready for
the next step in the process installing
| | 03:25 | Eclipse on your system.
| | Collapse this transcript |
| Installing Eclipse on Mac OS X| 00:00 | Once you have checked your version of
Java on Mac OS X, you are ready to install
| | 00:04 | Eclipse, the IDE I'll be
using throughout this course.
| | 00:08 | Go to the webpage, www.eclipse.org/downloads.
| | 00:13 | You'll see a number of
distributions of Eclipse are listed.
| | 00:16 | There is the one at the top for Java
Developers, that's the one I'll be using,
| | 00:19 | but there are many others available.
| | 00:21 | You'll need to install the version
of Eclipse for your copy of Mac OS X,
| | 00:25 | either 32 or 64-bit.
| | 00:28 | If you are not sure which version of
Mac you're using, go to the Apple Menu and
| | 00:33 | choose About This Mac.
| | 00:35 | On this dialog, click on More Info.
| | 00:38 | That opens the System Profiler Application.
| | 00:42 | Now, scroll down in the left
hand panel and click on Software.
| | 00:46 | Check the Property 64-bit Kernel and Extensions.
| | 00:50 | If it says Yes, then you're running 64-bit Mac.
| | 00:53 | If it says No, then you're running 32-
bit Mac, and that's the version of Eclipse
| | 00:58 | you'll want to download.
| | 00:59 | I'll click into Mac OS X 64-bit.
| | 01:04 | The file is delivered to you as a compressed
archive, with the file extension of tar.gz.
| | 01:10 | Now, I've already downloaded that file
to my Desktop, and to install Eclipse
| | 01:14 | there are just two steps.
| | 01:16 | First, extract the file.
| | 01:18 | If you don't have any special archive
utilities installed on your system, you
| | 01:22 | can extract this file
simply by double clicking it.
| | 01:25 | Mac will unarchive the file and place
the resulting folder on your Desktop.
| | 01:31 | The name of the resulting
folder is simply eclipse.
| | 01:34 | I'll double click into the folder and
show you that it contains the Eclipse
| | 01:37 | application, that's the version that has
an uppercase initial character, and the
| | 01:42 | graphic, and all of Eclipse's supporting files.
| | 01:45 | Now, technically, you've already
installed the application and you could start
| | 01:49 | using it, but I prefer to put Eclipse
where all of the other applications are on
| | 01:53 | my Mac, in the Applications folder.
| | 01:56 | So I'll click on the background and
then press Command+N, that opens a new
| | 02:00 | Finder window, and I'll see that
Applications is here in my Sidebar.
| | 02:05 | If you don't see Applications in
your Sidebar, just open up that folder.
| | 02:08 | Then, I'll click on the Eclipse
folder and drag and drop it on to the
| | 02:13 | Applications folder.
| | 02:14 | Then to get to Eclipse, I'll go to
Applications, I'll scroll down to the Es,
| | 02:18 | there it is, I'll click the
eclipse folder, and then double click the
| | 02:23 | Eclipse application.
| | 02:25 | If I am prompted to make sure I want to open
a downloaded application, I'll click Open.
| | 02:30 | When Eclipse opens for the first time,
it will ask you where it wants to put
| | 02:34 | something called a workspace.
| | 02:36 | I'll describe how workspaces work later,
but for now, just accept the default,
| | 02:41 | which will be Documents/workspace
under your Home folder, and click OK.
| | 02:46 | It will take a few more moments for
Eclipse to load up all of its tools and then
| | 02:50 | it will open to this Welcome Screen.
| | 02:53 | Close the Welcome Screen and you'll
be in the Java Development Environment.
| | 02:57 | If you have gotten this far, you are
ready to start writing code in Java.
| | 03:02 | And in the next chapter, I'll show you
how to write a Hello World application
| | 03:06 | and show you what basic Java syntax looks like.
| | Collapse this transcript |
|
|
3. Getting StartedCreating a Hello World application| 00:00 | Now it's time for that traditional first
programing task: building an application
| | 00:04 | that says Hello World.
| | 00:06 | If you don't already have
Eclipse open, you should open it now.
| | 00:10 | I'm going to show you a little trick on
Windows and you can do something similar
| | 00:14 | on Mac OS X. I am going to create a
shortcut on my Desktop to make it easier to
| | 00:18 | start Eclipse in the future.
| | 00:20 | I'll go to the Eclipse folder under
Program files, and if you are working on
| | 00:24 | Mac, go to \applications\eclipse and locate
the Eclipse command with the little graphic.
| | 00:31 | Now I am going to right click on it.
| | 00:33 | And on Windows I'll create a
shortcut and on Mac create an alias.
| | 00:38 | I'll then drag that shortcut or alias out to
the Desktop and then I am going to rename it.
| | 00:44 | On Windows, I'll press F2, on Mac I'll
press Enter, and I'll simply call it Eclipse.
| | 00:51 | And now I'll be able to start up Eclipse
easily from my Desktop whenever I need it.
| | 00:56 | Now, double click the shortcut or alias
and that starts up Eclipse on my system.
| | 01:02 | Before you create the Hello World
application, you should set up your workspace.
| | 01:08 | A workspace is a folder that
tracks all of your Java projects.
| | 01:12 | It contains all of your user
configurations, pointers to your projects
| | 01:16 | regardless of whether they are actually
physically in the workspace folder, and
| | 01:21 | adds other capabilities to
your Java development environment.
| | 01:24 | To switch your workspace, go to
the Menu and choose File, Switch
| | 01:28 | Workspace>Other, it will
show you your current workspace.
| | 01:33 | I am going to change my
workspace to my Exercise Files folder.
| | 01:37 | If you have access to the Exercise Files
for this course you can do the same, or
| | 01:42 | you can create your own Exercise Files folder.
| | 01:46 | I'll Browse, I'll go to my Desktop,
and from there I will go to Exercise
| | 01:51 | Files, and click OK.
| | 01:54 | Now, when you click OK from this screen,
Eclipse is going to close and then reopen.
| | 01:59 | This allows Eclipse to let go of
any file locks it may already have.
| | 02:04 | And when it opens it will be ready to
get started building your applications.
| | 02:08 | I'll maximize Eclipse and once again
close the Welcome Screen, and now I am
| | 02:12 | ready to create my first application.
| | 02:15 | When you create Java applications in
Eclipse, they are always inside Java project.
| | 02:20 | So the first thing to do is to create a project.
| | 02:23 | From the Menu choose File>New>Java Project.
| | 02:28 | Give your project a name.
| | 02:30 | I'll name it HelloWorld.
| | 02:32 | I recommend creating your
project names without any spaces or
| | 02:36 | special characters.
| | 02:37 | The default location for your project
will be a folder of the same name under
| | 02:42 | your Workspace folder, in my case
under the Exercise Files folder.
| | 02:47 | If you prefer, you can uncheck the
option, Use default location and place the
| | 02:51 | project anywhere you like.
| | 02:53 | For the JRE, you can choose either a
specific JRE, or I recommend using the default JRE.
| | 03:01 | This will give your project
maximum portability between systems.
| | 03:05 | So for example, if you say Use default
JRE and your system currently has JRE
| | 03:10 | 6.0, and then you take that same
project and move it to a system where the
| | 03:14 | default JRE is JRE 7.0, the project will
still compile and run just fine and you
| | 03:21 | won't have to go into your Java
project settings and change the environment,
| | 03:25 | accept all the other
default settings and click Next.
| | 03:28 | On this screen you are
asked for Java build settings.
| | 03:32 | The default setting is to create your
source code files in a folder named SRC
| | 03:38 | under the project folder.
| | 03:39 | And down at the bottom it shows that the
output folder, that is the folder where
| | 03:44 | you will be creating your output
binary files or class files, is named bin.
| | 03:48 | So your files aren't all
stored in one single folder.
| | 03:52 | Accept the default and click Finish.
| | 03:56 | Your project starts out empty, that is,
there aren't any Java code files in it.
| | 04:00 | You have to create the applications explicitly.
| | 04:03 | Every Java application is built inside a class.
| | 04:07 | This makes it very different from
other programming environments such as
| | 04:10 | say Perl or Python, where an application
can be as a little as a single line of code.
| | 04:17 | In Java, everything is an object, and
an object is created from a class, so you
| | 04:22 | have to define a class.
| | 04:23 | The good news is Eclipse
makes this pretty simple to do.
| | 04:27 | Right-click on your source
folder and choose New>Class.
| | 04:31 | This is the new Java Class wizard.
| | 04:35 | The Source folder is set explicitly
to HelloWorld/src, that is the project
| | 04:41 | folder and the SRC subfolder.
| | 04:43 | For now, leave the Package blank.
| | 04:46 | You'll see a warning when you do that,
Eclipse thinks that you should put every
| | 04:49 | class in a subfolder or package of
some kind, but to keep things simple for
| | 04:54 | your Hello World application we're going to
leave it in the default Package or the project route.
| | 05:00 | Give the class a name of HelloWorld,
you could also name this class Main or
| | 05:05 | anything else you want, but to follow
good Java conventions, the first character
| | 05:10 | of the class name must be uppercase.
| | 05:13 | If you create a class name with a
lowercase initial character it will still
| | 05:16 | work, but it will violate
conventions that are very strongly held in the
| | 05:20 | Java development world.
| | 05:23 | For the Modifiers, accept the default of public.
| | 05:26 | Don't check the checkboxes for abstract
or final, again, we'll talk about those
| | 05:30 | later in the course, and leave the
Superclass set to Java.lang.Object.
| | 05:36 | In fact, there is only one
other change to make here.
| | 05:39 | To make this a valid startup class, check
the option labeled public static void main.
| | 05:47 | This will create a method or function
that will be called automatically when you
| | 05:51 | start up the class by the
Java Virtual Machine. That's it.
| | 05:55 | Click Finish.
| | 05:58 | Once the class has been
created, it will open in an editor.
| | 06:02 | Now, to make this a little easier
to read, I am going change my font.
| | 06:05 | I'll go to my Preferences dialog,
which on Windows you can get to through
| | 06:10 | Window>Preferences, and on Mac you
can get to through Eclipse>Preferences.
| | 06:15 | In the Preferences dialog, I'll click
on General>Appearance>Colors and Fonts,
| | 06:22 | and then in the Colors and Fonts list
I'll choose Basic, and scroll down to the
| | 06:27 | bottom of that list and choose
Text Font, and then I'll click Edit.
| | 06:31 | I am just going to expand the size
of my Font to 14 pixels and click OK,
| | 06:38 | and click OK again.
| | 06:40 | And that should make the code
easier to read on the screen.
| | 06:42 | I am going to clean up the code a
little bit, removing things I don't need.
| | 06:47 | I don't need this commenting section,
so I am just going to select and delete
| | 06:51 | it, and I don't need this TODO comment either.
| | 06:54 | This is added to the main method by
Eclipse when you generate the code.
| | 06:58 | You can either select and delete it or
you can use this little icon over on the
| | 07:03 | left with the checkbox.
| | 07:04 | I'll click the icon, and from the Task List
I'll choose Remove task tag, double clicking.
| | 07:12 | I'll press tab once and now I am
ready to add some executable code.
| | 07:16 | Here is the code to
output a string to the console.
| | 07:20 | Start with System with an uppercase S.
System is a Java class and it's a part of
| | 07:26 | the core Java Class Library that's
included with your installation of Java.
| | 07:31 | Now type a period and you will see a
list of all of the properties and objects
| | 07:36 | that are a part of the
system class. Choose out;
| | 07:39 | you can either type it
or simply double click it.
| | 07:42 | Out represents an object which
implements something called a
| | 07:46 | PrintStream interface.
| | 07:48 | A PrintStream object allows you to
output text to some sort of environment.
| | 07:53 | In this case, it will output to the console.
| | 07:56 | Type another dot or period, and now you
will see a list of all of the functions
| | 08:01 | that are a part of the PrintStream named out.
| | 08:03 | I am going to choose one called Println.
| | 08:06 | There is a Print and a Println;
| | 08:08 | the Println function or method will
output something to the screen and add a
| | 08:12 | line feed at the end.
| | 08:14 | I'll type in an opening parenthesis
and then a double quote and notice that
| | 08:19 | Eclipse is closing the parenthesis and
the quotes as I type, and then I'll type
| | 08:24 | in the string "Hello World!"
| | 08:26 | I'll move the curser to the end
of the line and put in a semicolon.
| | 08:31 | In Java, the semicolon is like a
period in English, it completes the
| | 08:35 | statement, and it's required.
| | 08:38 | In some C style languages, such as
ActionScript, if you don't put in the
| | 08:42 | semicolon you will be okay.
| | 08:44 | In Java you have to put the
semicolon in or the compiler will complain.
| | 08:49 | That's my finished Hello World application.
| | 08:51 | I'll save my changes by pressing Ctrl
+ S on Windows or command S on Mac.
| | 08:56 | Now, I am going to run the
application for the first time.
| | 09:00 | To run an application, go to the
Toolbar and look for the Run button, it's a
| | 09:05 | little arrow pointing to the right.
| | 09:07 | Click the Down Arrow next to the Run
button and choose Run Configurations.
| | 09:12 | In the Run Configurations screen
choose Java Application, and then up on the
| | 09:16 | Toolbar click the Plus button.
| | 09:18 | This will create a new Run
Configuration for this application.
| | 09:23 | The name of the Run Configuration will
match the name of the class, HelloWorld.
| | 09:27 | There are many options for the Run
Configuration, but you don't need any of them for now.
| | 09:31 | Just go down to the bottom of
the dialog box and click Run.
| | 09:35 | If all of your code works okay, you
should see a rectangular area down at the
| | 09:39 | bottom of the screen called the Console
View appear, and it should contain the
| | 09:43 | output of your application, Hello World!
| | 09:46 | Now, once you've created the Run
Configuration for the first time on a
| | 09:50 | particular application, you don't need
to go through the whole process again.
| | 09:54 | So I am going to add a couple of
exclamation marks here so that I can just
| | 09:59 | modify the application in some way.
| | 10:01 | I'll save the changes by pressing,
once again, Ctrl+S or Command+S, and this
| | 10:07 | time to run the application I don't
need to pull down the list and go into the
| | 10:10 | Configuration screen, I just
need to click the Run button.
| | 10:14 | And down at the bottom in
the Console I see the output.
| | 10:18 | So that's your HelloWorld Java application.
| | 10:20 | As I've previously mentioned, Java
is a little more complex than certain
| | 10:24 | scripting languages that allow you to
say Hello World with a single line of code.
| | 10:29 | In Java, all code must be wrapped in
class definitions and code that you want to
| | 10:34 | execute must be wrapped
inside a function of some kind.
| | 10:38 | This main function is called
automatically by the Java Virtual Machine.
| | 10:43 | It must have the words public, static,
and void at the beginning, and it must
| | 10:48 | accept this value between the parenthesis, String,
open and closed bracket, and the name of a variable,
| | 10:55 | which is traditionally named args.
| | 10:57 | I'll talk more about that main method
and specifically about how those values
| | 11:02 | are being passed into the function,
known as arguments, in a later video.
| | Collapse this transcript |
| Exploring the Eclipse IDE| 00:00 | Before we continue on with learning
about the Java programming language, I'd
| | 00:04 | like to give you a tutorial on how
to navigate around the Eclipse IDE.
| | 00:09 | Eclipse has its own vocabulary, how to
refer to various areas of the Eclipse
| | 00:14 | interface and how to configure it.
| | 00:16 | I am going to start with showing
you how to import existing projects.
| | 00:21 | If you have access to the Exercise
Files for this course, you'll see that they
| | 00:25 | are stored in Chapters.
| | 00:26 | For example, the projects for the
current chapter Getting Started are in this
| | 00:30 | folder, 03_GettingStarted.
| | 00:34 | Each of these folders
constitutes an Eclipse project.
| | 00:38 | I'll double click into one
of them named ExploreEclipse.
| | 00:41 | You'll see that it contains a source folder;
| | 00:44 | that's where your Java
files go, and a bin folder;
| | 00:47 | that's where the compiled classes are placed.
| | 00:50 | There are also two files
named .classpath and .project.
| | 00:55 | If you are working on Windows, you
should see them in Windows Explorer.
| | 00:59 | If you are working on a Mac, you
won't see the files with the dot prefix
| | 01:03 | displayed in Finder, but they are there.
| | 01:05 | These are XML files that are used
to configure the current project.
| | 01:10 | You can actually work with these files
outside of Eclipse very easily, but I've
| | 01:14 | configured them to be importable into
Eclipse so you can get started with each
| | 01:19 | lesson very quickly.
| | 01:20 | Here is how you would
import that project into Eclipse.
| | 01:24 | From the Eclipse Menu, go to File>Import.
| | 01:28 | In the Import dialog, go to General,
and then Existing Projects into
| | 01:33 | Workspace, and click Next.
| | 01:36 | You can import projects from two formats;
| | 01:38 | an exploded project, where you can see
the actual files on disk, that's the kind
| | 01:43 | of projects that I am using;
| | 01:45 | and archived files that are in ZIP format.
| | 01:47 | I won't be using those during this course.
| | 01:50 | So I am going to choose a root directory
of an existing project. I'll click Browse.
| | 01:55 | I'll navigate to my Exercise Files, 03_
GettingStarted folder, and I'll chose
| | 02:01 | ExploreEclipse, and click OK.
| | 02:03 | Eclipse detects that there is a
project in that folder and it displays the
| | 02:07 | project and checks it by default.
| | 02:10 | All I am going to need to do is click Finish.
| | 02:12 | But before I do, I'll show you
that there is an option labeled Copy
| | 02:16 | projects into workspace.
| | 02:18 | If you leave that option unselected,
you'll be importing the existing project
| | 02:23 | into the workspace so that it's
displayed in the Package Explorer on the left
| | 02:27 | side of the Eclipse UI, but you'll
still be working with the original code.
| | 02:31 | If you check this option, you're making
a copy of the project, and the project
| | 02:36 | will be copied into the root
folder of the workspace itself.
| | 02:39 | I'll be leaving this option
unchecked throughout this course so that I am
| | 02:43 | working with the actual files that I am
delivering in the Exercise Files bundle.
| | 02:47 | I'll click Finish, and that imports the project.
| | 02:52 | I can now open the project, open its
source folder, its default package, and
| | 02:58 | there is the code, HelloWorld.java.
| | 03:01 | Now, notice I now have two projects opened
and they both have classes named HelloWorld.
| | 03:06 | How do I know which one I am looking at?
| | 03:08 | Here is a little trick, if you move
the cursor over the tab, you'll see the
| | 03:14 | entire path, starting with the
project name, so this file is for the
| | 03:18 | ExploreEclipse project.
| | 03:20 | I'll open the class from the
HelloWorld project and move the cursor over that
| | 03:24 | tab and show that the pop-
up help shows HelloWorld.
| | 03:28 | So when you have multiple classes of the
same name, sometimes with more than one
| | 03:32 | project, sometimes within different
directories or packages within the same
| | 03:36 | project, you can easily find out
which one you are working with.
| | 03:40 | Now, I typically try to keep
only one project open at a time.
| | 03:44 | So I am going to go back to my original
HelloWorld project, I'll right click on
| | 03:49 | it and choose Close Project.
| | 03:51 | And now I'm only left with the
HelloWorld.java file from ExploreEclipse.
| | 03:57 | Here are some important
terminologies as you work with Eclipse.
| | 04:00 | Each of the rectangular areas is called a View.
| | 04:03 | You might think of those as panels if
you've worked say with Adobe or Microsoft
| | 04:07 | software, but Eclipse calls them Views.
| | 04:10 | By default, there is a Package
Explorer View, down at the bottom there is
| | 04:15 | Problems View for displaying code
problems, a Javadoc View, a Declaration,
| | 04:20 | a Console, and so on.
| | 04:23 | Over on the right there is
something called the Task List View.
| | 04:26 | This is a part of a plug-in called
Mylyn, that's delivered automatically with
| | 04:31 | this distribution of Eclipse.
| | 04:33 | We won't be using this plug-in during
this course, so I am just going to get rid
| | 04:36 | of it by clicking the Close icon.
| | 04:38 | The other view that appears on the
right side by default is called the Outline
| | 04:42 | View, this one is very useful because
it lets you navigate around in your code
| | 04:46 | without having to scroll up and down.
| | 04:48 | As your code gets more complex and you
have a lot more of it, it's a lot easier
| | 04:53 | to find the code by using the Outline.
| | 04:56 | Even though this is a very simple class,
I can demonstrate this by clicking on
| | 04:59 | the main method, and you'll see that,
that method name is highlighted and the
| | 05:04 | cursor moves to that location in the code.
| | 05:06 | So we'll keep the Outline View open.
| | 05:09 | As you work with your code and you
have wider lines, you might want to expand
| | 05:13 | the Editor so that it's Full Screen.
| | 05:16 | To do this just double click on the tab at
the top of the Editor and that will maximize it.
| | 05:22 | Double click again and it will
restore to its original size.
| | 05:25 | I'll also show you that you can expand
any of the views, not just the Editor.
| | 05:30 | I'll maximize the Package
Explorer and restore it;
| | 05:35 | I'll maximize the Problems
View and restore it, and so on.
| | 05:39 | Every view behaves exactly the same.
| | 05:41 | Another concept that's important to
know about in Eclipse is Perspectives.
| | 05:46 | A Perspective in Eclipse is a
particular arrangement of views.
| | 05:50 | So the Java Perspective, which is the
default Perspective when you first open
| | 05:54 | this Eclipse distribution, has the
Package Explorer on the left, the Editor in
| | 05:59 | the center, the Problems, Javadoc, and
Declaration View at the bottom and so on.
| | 06:04 | You can create your own custom Perspectives.
| | 06:07 | So for example, I have the Console View
open now, because I've run an application;
| | 06:12 | it's not typically open when you
first start the Java Perspective.
| | 06:16 | I have also closed the Task List View.
| | 06:20 | Now I am going to save this
as my own custom Perspective.
| | 06:23 | I'll go to the Menu and choose Window>
Save Perspective As, and I'll call this
| | 06:29 | CustomForJava, and click OK.
| | 06:33 | I can now switch between different Perspectives.
| | 06:36 | I can go to the Menu and choose Window>
Open Perspective, and I'll see a couple
| | 06:42 | of default Perspectives here;
| | 06:43 | one called Debug and
another one called Java Browsing.
| | 06:47 | I'll click Other and I'll see a whole
bunch of different Perspectives listed.
| | 06:51 | Java was the default, I'll choose
that, and you'll see that the original
| | 06:56 | Perspective or layout
returns, including the Task List.
| | 07:00 | But up in the upper right hand
corner I now see my CustomForJava
| | 07:04 | Perspective displayed.
| | 07:06 | You can actually move the cursor to the
left of the Perspectives and drag this
| | 07:10 | out, so you can see as many
Perspectives as buttons as you have available.
| | 07:15 | And you can easily now switch between
them by clicking the appropriate button.
| | 07:19 | I'll typically be using this
CustomForJava Perspective throughout the course,
| | 07:23 | but you can create your own Perspective
and layout the application however you like.
| | 07:28 | I'll show you one more trick.
| | 07:30 | You can detach any of the views and have
them float above the rest of the Eclipse UI.
| | 07:35 | This is particularly useful if you
have more than one monitor and you want to
| | 07:40 | move one of the views off to the second monitor.
| | 07:42 | To do this, you right click on the
tab for the View and choose Detached.
| | 07:47 | Now, you can move the view around,
you can expand it, and if you have that
| | 07:52 | second monitor, you can move
it off to the second monitor.
| | 07:55 | To reattach it, right click on
the tab and deselect Detached.
| | 08:00 | The view might drop into an area you don't want.
| | 08:03 | For example, the Outline View
just dropped into my bottom dock.
| | 08:08 | But you can click on the tab
and drag it wherever you want.
| | 08:11 | So now I've placed it back
in its original location.
| | 08:15 | And if at any point you've really
messed up your views in a way that doesn't
| | 08:18 | work for you, for example, I am just
sort of randomly moving things around now
| | 08:22 | to really mess up my system, you
can always reset a Perspective.
| | 08:28 | Go to the Menu and choose Window>Reset
Perspective, and click Yes to confirm.
| | 08:35 | And your original Perspective will return.
| | 08:37 | So that's a look at how to navigate
around the Eclipse user interface.
| | 08:41 | I've shown how to use Views and
Perspectives, how to create your own custom
| | 08:45 | Perspective, and how to detach views
and move them around if you prefer, and
| | 08:50 | finally how to reset a Perspective
if you don't like the way things have ended up.
| | Collapse this transcript |
| Compiling and running from the command line| 00:00 | Throughout this course I'll be using
the Eclipse IDE to program, compile, and
| | 00:05 | run my Java applications.
| | 00:08 | But it's important to know that you
can also compile and run from the command
| | 00:11 | line and there are things you can see
on the command line a little bit more
| | 00:15 | easily than in the IDE.
| | 00:16 | I'm going to use an existing project.
| | 00:19 | I'll import the project from the
Exercise Files folders using the Import command
| | 00:25 | and selecting the root directory under Exercise
| | 00:28 | Files>03_GettingStarted>CommandLine.
| | 00:32 | I'll complete the Import process.
| | 00:36 | I'll open the application that's in the
default package of the project, and this
| | 00:40 | time the name of the class is
Main rather than HelloWorld.
| | 00:44 | You can name this Main class anything
you want, the only real requirement is
| | 00:49 | that the initial character be uppercase;
| | 00:51 | in this case the letter M, but you can
name it anything you want as long as you
| | 00:55 | follow Java naming conventions.
| | 00:57 | You can't use any spaces or special
characters and that initial character really
| | 01:01 | should be uppercase.
| | 01:03 | Once again, this is an
incredibly simple application;
| | 01:06 | it's outputting a string to the command line.
| | 01:08 | With the application open, I'll click
the Run button, the application runs, and
| | 01:13 | the console displays the outputted string.
| | 01:16 | Now let's go to a command window.
| | 01:18 | On Windows 7 and Windows Vista, click
the Start Menu and type cmd and press
| | 01:24 | Return, that will open up a command window.
| | 01:27 | If you're working on Mac, go to the
Applications folder, to the Utility
| | 01:32 | subfolder, and open the Terminal application.
| | 01:35 | In either Windows or Mac, you
should start off at your Home Directory,
| | 01:39 | Users\, and your username.
| | 01:42 | If you're working on Windows XP, you
should start off at the Documents and
| | 01:46 | Settings folder and then your username.
| | 01:48 | Now, change to the
Desktop folder, type cd Desktop.
| | 01:54 | On either Mac or Windows you can
type the beginning of a folder name and
| | 01:57 | then press the Tab key.
| | 01:59 | So now, I'm going to move to the
Exercise Files folder by typing cd and then
| | 02:05 | Ex, and then press Tab.
| | 02:08 | If you're working on Windows, the case doesn't
matter, but if you're working on Mac, it does;
| | 02:13 | Mac is case sensitive.
| | 02:15 | So now I'm in the Exercise Files folder,
and I'll move down a directory into the
| | 02:20 | Chapter 03 folder, typing cd 03,
pressing Tab, and now I'll adding a slash.
| | 02:27 | If you're working on Windows, use a
backslash, and if you're working on Mac use
| | 02:31 | a forward slash, and type the
beginning of the project name, com, press Tab
| | 02:36 | again, and then press Enter or Return
and you're in the CommandLine folder.
| | 02:41 | Type dir on Windows or ls on Mac and you'll
see a listing of the files in the directory.
| | 02:48 | You should see two files starting with the dot;
| | 02:50 | the classpath and the project files,
and a folder named bin and one named src.
| | 02:56 | List the contents of the src folder.
| | 02:59 | Type dir on Windows or ls on Mac, then a
space, and src, and you should see that
| | 03:06 | it contains the one Java file, Main.java.
| | 03:09 | Now switch to that directory, type
cd src and press Enter or Return.
| | 03:15 | So now, I'm going to show you how to
compile the application from the command line.
| | 03:20 | First I'll clear the screen, type cls on
Windows or clear on Mac and press Enter or Return.
| | 03:27 | To compile an application use the javac command.
| | 03:31 | I'll type javac, all one word, and then
a space, and then the name of the Java
| | 03:36 | file, including the file extension, Main.java.
| | 03:41 | Regardless of whether you're working on
Mac or Windows, this is case sensitive.
| | 03:45 | Even though Windows is a non case
sensitive file system for the most part, Java
| | 03:50 | is a highly case sensitive language, so
type the name of the file exactly as it
| | 03:54 | exists, with the uppercase M.
Then press Enter or Return.
| | 03:59 | If you don't see any output, that's good news.
| | 04:02 | Now, list the contents of the directory
again and you should see that the class
| | 04:06 | file was created in the same
directory as the source code file.
| | 04:10 | Now, to run the application, type java
space, and then the name of the file, but
| | 04:16 | without the dot class extension, and
press Enter or Return and the application
| | 04:21 | should execute and the string
should be output to the command line.
| | 04:25 | Notice that when you execute the
application, you're referring to the class as a
| | 04:29 | class, not as a file.
| | 04:32 | That's why you don't
include the dot class extension.
| | 04:34 | When you compile, you're dealing with the file;
| | 04:37 | when you run, you're dealing with the class.
| | 04:40 | Now, when you compile in Eclipse, you
may have noticed that you're creating
| | 04:44 | the class file in a different directory, not
in the same directory as the source code file.
| | 04:49 | You can do the same thing from the command line.
| | 04:52 | The javac command has a whole
bunch of different options available.
| | 04:55 | You can see those options by simply
typing javac, without passing any values,
| | 05:00 | such as filenames, just type javac and
press Enter or Return, and you'll see a
| | 05:05 | listing of all of the different options.
| | 05:07 | I'm going to use this one, -d,
specifying where to place generated class files.
| | 05:13 | So I'm going to clear my screen
again, cls on Windows or Clear on Mac.
| | 05:18 | Then I'll type javac.
| | 05:19 | I'll once again follow that with the
name of the file, Main.java, but then I'll
| | 05:25 | type -d ..\bin, using a backslash
for Windows or a forward slash for Mac.
| | 05:34 | The result will be that the class
file is generated in the bin folder.
| | 05:38 | I'll type cd ..\bin, I'll list the
contents of the directory, and I'll see the
| | 05:46 | new copy of Main.class.
| | 05:48 | Now, because I've changed my current
directory to bin, I can run the class from
| | 05:53 | here, with java Main.
| | 05:57 | Let's switch back to the
source folder, cd ..\src.
| | 06:03 | And I'm going to show you one
incredibly valuable thing that running from the
| | 06:06 | command line will let you do.
| | 06:07 | I'll once again clear my screen.
| | 06:10 | Now, this time when I compile I'll use
the verbose parameter, -verbose means
| | 06:16 | tell the compiler to tell me
what it's doing in the background.
| | 06:19 | When you have issues with your Java
code that you can't solve in Eclipse,
| | 06:23 | sometimes seeing what the Java
compiler is doing can be useful.
| | 06:27 | Here is the syntax, javac, then the
name of the file, Main.java, and then after
| | 06:33 | a space, -verbose, all lower case.
| | 06:37 | Press Enter or Return and you'll see
that the class is being compiled, but you
| | 06:43 | will see a whole listing of
what's going on in the background.
| | 06:46 | Up at the top it says parsing started
Main.java and then parsing completed.
| | 06:52 | So it takes a moment first to read your
file and figure out what it's supposed to do.
| | 06:57 | Now it looks for supporting files, the
search path for class files is called the
| | 07:02 | classpath, and by default it includes
all of the jar files and classes that are
| | 07:09 | a part of the core Java Class Library.
| | 07:11 | Those are the files that
are included with the JDK.
| | 07:14 | Next, it starts loading classes that it needs.
| | 07:18 | I've asked to use the String class and
the System class and also the PrintStream
| | 07:23 | class, which has its own set of dependencies.
| | 07:26 | So the compiler goes through all of
its archived files and finds the classes
| | 07:31 | that it needs to build this program.
| | 07:34 | Not just my class, which is called Main,
but all of the supporting classes as well.
| | 07:39 | Finally, it finishes the compilation
and writes Main.class to the file system,
| | 07:44 | and tells you how long the whole thing took;
| | 07:47 | less than a second.
| | 07:48 | So that's a look at some of the things
you can do working from the command line.
| | 07:52 | You can do many of these things also
in Eclipse, by adding parameters in your
| | 07:56 | run configuration, and I will show you
some of those options in the next video.
| | Collapse this transcript |
| Passing arguments to the application| 00:00 | When you create a Main class, that is
a class that you want to start up when
| | 00:04 | the application begins.
| | 00:06 | It always has a main method when you are
running Java from the command line or the console.
| | 00:11 | The syntax for this can differ
from one platform to another.
| | 00:14 | For example, you don't use a main
method in a Java Servlet, you use other
| | 00:18 | kinds of methods, but when you are running
from the command line, it's always called main.
| | 00:23 | The signature or syntax of the
main method always looks like this:
| | 00:28 | it has the keywords public, static, and void.
| | 00:32 | Public means that the method
can be called from anywhere.
| | 00:36 | Static means that you don't have
to create an instance of the class.
| | 00:40 | And void means that you are not
returning anything from the class.
| | 00:44 | Now, I'll talk more about these
keywords in later videos, but for now what
| | 00:48 | you need to know is that these three
keywords are required as part of the
| | 00:53 | main method declaration.
| | 00:55 | The other thing that the main method has to
have is this syntax, String, open/closed bracket,
| | 01:02 | and then the name of the variable,
which by default is set to args by
| | 01:06 | Eclipse, but could be anything.
| | 01:08 | This is a value that's passed in
by the Java Virtual Machine as the
| | 01:13 | application starts up.
| | 01:15 | The brackets means that the argument is
an array, an ordered collection of values.
| | 01:21 | And these are the command line
arguments or values that are passed into the
| | 01:25 | application when it starts up.
| | 01:27 | Now, you can pass arguments in
from Eclipse or from the command line.
| | 01:31 | It will make most sense if we
start from the command line though.
| | 01:35 | So open up a command window;
| | 01:38 | on Windows use the cmd command and on
Mac use terminal, and then change to bin
| | 01:44 | folder underneath the project
arguments that I've imported into Eclipse.
| | 01:48 | I'll type cd Desktop\Exercise Files
\03_GettingStarted\Arguments\bin.
| | 01:59 | List the contents of the directory
using dir on windows or ls on Mac, and you
| | 02:04 | should see that there is a
class there called Main.class.
| | 02:08 | Now, I am going to run the application.
| | 02:10 | First I'll clear my screen.
| | 02:12 | Then I'll type java Main.
| | 02:15 | And I don't see any output, that's
because my source code for the moment doesn't
| | 02:20 | have anything in the main method.
| | 02:22 | I'll switch back to the command window
using Alt+Tab on Windows or Command+Tab
| | 02:26 | on Mac, and this time I'll
type java Main arg1 arg2.
| | 02:34 | Again, there is no output, but let's
add some code to the application to detect
| | 02:39 | and report the arguments.
| | 02:41 | I'll go back to the main method.
| | 02:43 | The args variable is an array, and in
Java every array has a property called
| | 02:49 | length, which returns numeric value
indicating how many items there are in the array.
| | 02:54 | So I am going to add a little
bit of output that looks like this.
| | 02:58 | System.out.println, and then I'll put two
values together, one string and one number.
| | 03:06 | The string will be Number of args:
| | 03:09 | ,
then I'll move the cursor after
the last double quote and put in a Plus
| | 03:16 | operator and then args.length.
| | 03:20 | The length property is numeric.
| | 03:22 | When you take a string and a numeric
value and put them together using the plus
| | 03:26 | operator, that's called concatenation,
and in Java the numeric value will be
| | 03:31 | automatically converted to a string.
| | 03:33 | I'll talk about the
mechanics of that in a later video.
| | 03:38 | I'll finish the statement with the
semicolon at the end and I'll Save my changes.
| | 03:42 | Now, by default when you Save your
changes to your code, Eclipse automatically
| | 03:47 | recompiles the application for you.
| | 03:50 | This is because under the
Project Menu there is an option labeled
| | 03:53 | Build Automatically.
| | 03:54 | It's checked by default.
| | 03:56 | If you want to you can uncheck that
option and only compile or build when you
| | 04:01 | say so, but I'll keep it on, so
whenever I Save my changes the .class files
| | 04:06 | are recreated for me.
| | 04:09 | So now I can switch back to the command
window and I'll repeat the same command
| | 04:14 | by pressing the Up Arrow and then
either Enter or Return, and I should get the
| | 04:19 | output, Number of args: 2.
| | 04:21 | So now I know that I am receiving the
arguments from the command line and that I
| | 04:26 | have exactly the number that I typed in.
| | 04:28 | Let's go back to the code
and add a little bit more.
| | 04:31 | Place the cursor after that initial
statement and press Enter or Return a couple
| | 04:35 | of times to make a little bit
of blank space in your code.
| | 04:38 | Now, I am going to add a little bit of
code that loops through the arguments and
| | 04:42 | report the value of each argument in turn.
| | 04:45 | This takes a little bit more complex
code, but the good news is that Eclipse
| | 04:49 | will write the code for you.
| | 04:51 | Try this, type for, the word for, then
hold down the Ctrl key and press Space.
| | 04:58 | This keyboard shortcut is the
same on both Windows and Mac.
| | 05:02 | It brings up a list of available options.
| | 05:04 | Choose the first option, for - iterate
over array by pressing Enter or Return,
| | 05:10 | and Eclipse adds a bunch of code
that will loop through the array.
| | 05:14 | Now, I am not going to describe the
exact syntax of this code right now, we'll
| | 05:18 | save that for later, but all you
need to know is that when you use a for
| | 05:22 | command and you provide all this
information, you are looping through the
| | 05:26 | contents of the declared array, in
this case args, and you can deal with each
| | 05:31 | item of the array in turn.
| | 05:34 | I'll click into the for loop,
between the braces, and once again I'll use
| | 05:39 | System.out.println and then I'll pass in
the value of the current argument using
| | 05:47 | the syntax args, open bracket, i, closed bracket,
and I'll remember to put in my semicolon at the end.
| | 05:55 | i is a variable that was declared
inside the for loop, when I said int i = 0,
| | 06:01 | it's initial value is 0, and each time
through the loop it's incremented by 1.
| | 06:06 | The first item in the array is item 0,
the second one is item 1, and so on.
| | 06:11 | I'll press Command+S or Ctrl+S to save
my changes, switch back to the command
| | 06:16 | line, and pressing the Up
Arrow run the application again.
| | 06:20 | And now I see the total number of
arguments and I see the value of each argument
| | 06:25 | output one at a time.
| | 06:27 | When you pass arguments from the
command line, each argument is delimited and
| | 06:31 | separated from the other by a space
character, but if you want to include a
| | 06:35 | space character and a value,
just wrap the value inside quotes.
| | 06:39 | So I'll press the Up Arrow to bring
that command back again, but I'll move the
| | 06:44 | cursor over and add quotes
around the two words, arg1 and arg2.
| | 06:49 | Then I'll run the application again,
and this time I am told I only have one
| | 06:54 | argument, and the value of the
argument is the entire string.
| | 06:58 | So that's how you pass in the
arguments from the command line.
| | 07:01 | How would you do the same
thing directly in Eclipse?
| | 07:05 | I'll go back to Eclipse and
I'll go into my Run Configurations.
| | 07:08 | I'll go to the Toolbar, pull down the
Run Menu and choose Run Configurations.
| | 07:13 | I'll add a new Run Configuration by
clicking Java Application and clicking Plus,
| | 07:20 | and the new name is going to be Main (1).
| | 07:23 | And over here I'll click on the Arguments tab.
| | 07:26 | I can pass in as many arguments as I want.
| | 07:29 | I'll list these arguments one per line, so
this will be arg1 and arg2 and arg3 and arg4.
| | 07:39 | Then I'll click the Run button, and
down here in the Console View I'll expand
| | 07:44 | the Console so we can see all the output.
| | 07:46 | I see Number of args:
| | 07:47 | 4 and then each of the arguments listed
one at a time as the code loops through
| | 07:53 | and deals with each item in turn.
| | 07:55 | So that's the purpose of the args
parameter that's passed into the main method.
| | 08:00 | It allows you to receive and process
values that are passed into your Java
| | 08:04 | application at runtime, either on
the command line working in the command
| | 08:08 | application in Windows, or in terminal
on Mac, or from within Eclipse from a Run
| | 08:14 | Configuration that's set up for this purpose.
| | Collapse this transcript |
| Using the Java API documentation| 00:00 | As you've seen so far in this course,
when you work in Java you are highly
| | 00:04 | dependent on the classes that are
a part of the Java Class Library.
| | 00:08 | You can find documentation about these
classes in the API documentation that's
| | 00:13 | hosted on the Oracle website.
| | 00:15 | One way to get to that
documentation is simply through a browser.
| | 00:19 | You can download the documentation
locally, but by using the version that's on
| | 00:23 | the Oracle website, you'll be sure you
are looking at the most recent version.
| | 00:27 | I am going to go to Google
and search for Java 6 API docs.
| | 00:33 | You can also look for Version 7 if
that's the version of Java you want to use.
| | 00:38 | This link takes you to the documentation.
| | 00:41 | You'll see that there are literally
thousands of classes to choose from, shown
| | 00:45 | in this list in the lower left hand corner.
| | 00:48 | You can filter the list if you know the
package or group that a class is a member of.
| | 00:52 | For example, one of the most commonly
used packages in Java is called java.lang.
| | 00:59 | A package is a group of classes that
have common characteristics or work
| | 01:04 | together in some way.
| | 01:05 | I'll click on java.lang and I'll see a
list of all sorts of classes that you'll
| | 01:10 | use frequently in your Java programming.
| | 01:13 | So for example, here is the String class.
| | 01:16 | If I click on the link, it shows me
all the documentation about the String
| | 01:20 | class, the class that represents a string value.
| | 01:24 | I've also used the System class so
far, and that's also in java.lang.
| | 01:28 | Now, you can also get to this
documentation easily through Eclipse.
| | 01:33 | You'll still need to be connected to
the Internet, because you'll be referring
| | 01:36 | to the same files up on the Oracle
website, but you'll be able to get to what
| | 01:40 | you want much more quickly if
you know a couple of little tricks.
| | 01:43 | So I am going to return to Eclipse, and
let's say, for example, that I want to
| | 01:48 | learn about the String class.
| | 01:49 | I am going to move the cursor over the
word String and after a moment Eclipse
| | 01:54 | pops up a little bit of documentation.
| | 01:57 | Notice in the lower right hand corner of
the pop-up window it says press F2 for focus.
| | 02:03 | So I'll press F2 and now I can expand and
scroll through this set of documentation.
| | 02:10 | And not all of the documentation that
shows up in this window will contain links
| | 02:13 | to get to the full docs for a particular class.
| | 02:16 | So here is another way to do it.
| | 02:18 | I am going to double click
the word String to select it.
| | 02:20 | Then I'll go to the Menu
and choose Help>Dynamic Help.
| | 02:26 | I see a new view appear on
the right, the Help View.
| | 02:30 | And I see a link,
javadoc for 'java.lang.String'.
| | 02:35 | When I click the link, that takes
me to the full documentation for
| | 02:39 | that particular class.
| | 02:40 | I'll double click the Tab of the Help
View and now I can scroll through and read
| | 02:45 | everything about the String class;
| | 02:47 | all of the different methods,
properties, constructive methods, and
| | 02:51 | everything else about it.
| | 02:52 | I'll close the Help View and
return to the main Perspective.
| | 02:56 | Finally, I'll also show you that when
you are working with a property of a
| | 03:00 | class, and that property is an
instance of a particular Java class, you can
| | 03:05 | frequently get to the
Javadocs for that class very simply.
| | 03:09 | Just move the cursor over the
property name and wait for a moment until the
| | 03:13 | pop-up window appears.
| | 03:15 | Then press F2 to give it focus.
| | 03:18 | You can once again expand and scroll
through the contents, and you'll see that
| | 03:22 | the out property of System is an
instance of a class called java.io.PrintStream.
| | 03:29 | When you click the link, that takes you
directly to the documentation for that class.
| | 03:34 | And you can once again expand to Full
Screen and read everything you want about
| | 03:39 | the class and how to use it.
| | 03:41 | So that's a look at how to get
to the Java API documentation.
| | 03:45 | Again, you can get to the complete
documentation set through the browser;
| | 03:48 | you'll be looking at
documentation from the Oracle website.
| | 03:51 | Or you can look at the documentation
directly from within Eclipse, by using the
| | 03:56 | dynamic Help feature or by using the
F2 pop-up window that gives you direct
| | 04:01 | access to the documentation for the
classes that you are working with.
| | Collapse this transcript |
| Memory management and garbage collection| 00:00 | One of the great charms of the Java
programing language is that even though
| | 00:04 | it's a compiled language, it manages
memory for you, unlike languages like C,
| | 00:11 | C++, Pascal, and others.
| | 00:13 | You as the programmer don't have to
explicitly allocate and de-allocate memory
| | 00:18 | whenever you create an object.
| | 00:20 | The Garbage Collector is a major
feature of the Java Virtual Machine.
| | 00:23 | I am going to describe how the Garbage
Collector works and how little attention
| | 00:28 | you as the programmer need to give it.
| | 00:30 | When you create a variable that
references a complex object, the object itself
| | 00:35 | is stored in an area of
memory called heap memory.
| | 00:38 | There are two types of memory; stack and heap.
| | 00:42 | The stack memory is somewhat faster;
| | 00:44 | heap a little bit slower,
but heap is more dynamic.
| | 00:47 | When you create primitive variables,
depending on their context, they might be
| | 00:52 | stored in stack or heap, but
complex objects are always stored in heap.
| | 00:57 | As long as any variable references an
object in memory, that object will be
| | 01:02 | retained, it won't be
eligible for garbage collection.
| | 01:06 | So if you create a variable and it
points to a string, a date, an array, a
| | 01:11 | collection, or any other complex
object, as long as that variable can be
| | 01:16 | addressed in your code,
the object will be available.
| | 01:19 | When all references to the object
expire, that is when you can't get to
| | 01:24 | the object through your code anymore,
then that object is eligible for
| | 01:27 | garbage collection.
| | 01:29 | So when do references expire?
| | 01:31 | There are two models that you can look at.
| | 01:34 | First of all, when you declare a
variable that's local to a function or to a
| | 01:38 | code block, as soon as the function
or code block is done executing, that
| | 01:42 | variable is no longer available to you,
and so it has expired and is eligible
| | 01:47 | for garbage collection.
| | 01:49 | Within this function there are two scopes.
| | 01:51 | Variables declared directly within the
function are available as long as the
| | 01:55 | function is executing.
| | 01:57 | So the variable in function would be
available until the function is done, and
| | 02:02 | then it would expire.
| | 02:03 | I've spoken previously about the fact that
in Java, scope is also defined by code blocks.
| | 02:09 | So in the second part of the code, in
the for loop, I am declaring an integer as
| | 02:14 | a part of the for loop, the name of the
variable as i, and as soon as that for
| | 02:18 | loop is done executing, that variable
is no longer in scope and it's eligible
| | 02:23 | for garbage collection.
| | 02:25 | For variables that are more persistent,
such as fields within objects, you can
| | 02:30 | explicitly expire them by
setting their value to null, N-U-L-L.
| | 02:35 | So for example, here is string named
expireMe, and if I want to make it eligible
| | 02:41 | for garbage collection, I
simply set its value to null.
| | 02:44 | The object in memory can't be reached
in my code anymore and therefore it's
| | 02:49 | eligible for garbage collection.
| | 02:51 | So when does garbage collection happen?
| | 02:53 | The Garbage Collector runs in its own
thread, so it doesn't affect your applications.
| | 02:58 | As long as the system on which your
application is running has adequate
| | 03:01 | resources, you shouldn't notice
that the Collector is running.
| | 03:05 | And the Garbage Collector
has incredible autonomy.
| | 03:08 | The Java Virtual Machine runs the
Garbage Collector when it thinks it needs
| | 03:11 | to, and when the Garbage Collector
identifies an object that no longer has any
| | 03:15 | references, it has the option of either
destroying it and reclaiming the memory or not.
| | 03:21 | It has its own algorithm, its own
logic, for figuring out how to manage the
| | 03:25 | memory, and it's not up to you.
| | 03:28 | You as a programmer cannot
force garbage collection in Java.
| | 03:31 | There are methods available in the
language, such as System.gc() and
| | 03:36 | Runtime.gc(), gc stands for Garbage Collector.
| | 03:40 | These are methods that send
messages to the JVM, that say it might be a
| | 03:44 | good idea to collect garbage right now, but
there is no guarantee that it will happen.
| | 03:49 | And in fact, many Java developers
recommend not using these functions.
| | 03:53 | It can mislead you into thinking that
you are getting all your memory back right
| | 03:57 | away, but that's not
necessarily what's going to happen.
| | 04:00 | If you're running a complex
application and you are challenging the available
| | 04:05 | memory on the system, you will know,
because the Java Virtual Machine will
| | 04:09 | throw an error called OutOfMemoryError,
and you will see these errors happen in
| | 04:13 | more complex applications where an
application is running on low memory devices or systems.
| | 04:19 | You can manage the memory of the
Java Virtual Machine by setting certain
| | 04:23 | parameters when you start up an application.
| | 04:26 | You can also tune your application by
minimizing the number of objects that you create.
| | 04:31 | As you've seen in many of the examples
in this course, there are different ways
| | 04:35 | of architecting Java code, so that you
can create a whole bunch of objects, or
| | 04:40 | you can reuse objects
that you've already created.
| | 04:42 | In general, it's better to reuse.
| | 04:45 | If you're concerned about memory usage,
you can use these methods to find out
| | 04:49 | how much memory is available:
| | 04:51 | Runtime.maxMemory(), Runtime.
totalMemory(), and Runtime.freeMemory().
| | 04:57 | Take a look at the Java docs for
these methods to find out what information
| | 05:00 | they are giving you.
| | 05:01 | And you can use command line options to
manage the amount of available heap memory.
| | 05:07 | You can manage the memory in three areas;
| | 05:10 | in the initial heap size, in the
maximum heap size, and in the heap size for
| | 05:15 | what are called young generation objects;
| | 05:18 | objects that have just been created.
| | 05:20 | If you want more information about
memory management, take a look at the
| | 05:24 | documentation for the Java
programing language on the Oracle website.
| | 05:29 | You will find that there is an
enormous amount of information available.
| | 05:32 | But when you're writing your first
simple Java applications just know that the
| | 05:37 | Garbage Collector is highly automated
and as long as you are not running out of
| | 05:41 | memory, you might not need to worry about it.
| | Collapse this transcript |
|
|
4. Using Primitive Data TypesEverything is an object| 00:00 | As you learn how to program in
Java, keep this idea always in mind,
| | 00:04 | everything is an object.
| | 00:06 | As you design your applications,
you'll be placing your code inside class
| | 00:10 | definitions and wrapping that code
inside functions known as methods.
| | 00:15 | Let's take a look at a very
simple application the Hello World!
| | 00:18 | application I've shown previously.
| | 00:20 | This time I've given the starting
class a different name SimpleApplication.
| | 00:25 | Notice that the main method
though looks the same as before.
| | 00:28 | That syntax is required, and as
stated previously, the executable code is
| | 00:34 | inside the main method.
| | 00:36 | It outputs the string
"Hello World!" to the console.
| | 00:38 | You can diagram your Java
applications using a syntax known as UML or
| | 00:44 | Unified Modeling Language.
| | 00:46 | This diagram shows that the name of
the class is SimpleApplication and that
| | 00:50 | it has a single method or function
named main and it returns void which means
| | 00:55 | it returns nothing.
| | 00:56 | It doesn't return any value at all.
| | 00:58 | Now, from this simple class, you might not
get the idea that everything is an object.
| | 01:03 | So let's expand the
application a little bit to two classes.
| | 01:07 | In this version of the application
there are two classes, the starting class is
| | 01:10 | still called SimpleApplication.
| | 01:12 | It's the starting class because it's
the one with the main method, and as the
| | 01:16 | application starts up, the main method
is called and the code in that method
| | 01:21 | creates an instance of
another class called Welcomer.
| | 01:24 | That class is shown at
the bottom of this screen.
| | 01:27 | Shift your attention
down to the welcome request.
| | 01:29 | It declares a variable named
welcome outside of any methods.
| | 01:33 | We call those either
instance variables or fields.
| | 01:37 | In this case, there is an instance
variable named welcome, it's a string,
| | 01:42 | and it's private to the class which
means that it can only be read by the
| | 01:45 | code within that class.
| | 01:47 | Its value is Hello.
| | 01:49 | When, the function sayHello is called
from that class, that class is responsible
| | 01:53 | for outputting the string to the console.
| | 01:55 | From the main application we create an
instance of that class using the syntax
| | 02:00 | Welcomer, that's the uppercase
version, that's the data type and then the
| | 02:04 | lowercase version is the name of the
variable and we say that it's equal to the
| | 02:08 | new instance of the Welcomer class
that's an object and the object can have
| | 02:14 | methods and properties.
| | 02:16 | We call the object sayHello method and the
result is to output the string to the command line.
| | 02:21 | Once again, you can diagram this
application using UML, in this case there are
| | 02:26 | two classes SimpleApplication and Welcomer.
| | 02:29 | This first class simply has the main method;
| | 02:31 | the second class has both an instance
variable or a field and a method named sayHello.
| | 02:37 | Once again sayHello returns void or
nothing, but it takes the action of
| | 02:42 | outputting a string to the console.
| | 02:44 | In Java, we say that everything is
an object because it's very common to
| | 02:48 | create an instance of class to execute some code
and that code will be wrapped inside the class.
| | 02:54 | As we actually get into coding some
classes, I'll describe what's an object,
| | 02:59 | what's a variable, and what's a field.
| | 03:01 | Here is another way in which
Java sees everything as objects.
| | 03:06 | You can declare a String variable by
declaring the data type String and then
| | 03:10 | the variable name, in this case the
variable name is welcome and then you can
| | 03:13 | say that that variable has a value of a
string wrapped in double codes, but in
| | 03:19 | fact, this is shorthand.
| | 03:21 | Here is the bit of code
that's the longhand version.
| | 03:24 | We declare the data type, we say what
the variable name is, but now we say that
| | 03:28 | we're creating a new instance of the String
class and we pass in the string that we want.
| | 03:33 | This is the longhand version and
these two bits of code are exactly
| | 03:37 | functionally identical.
| | 03:39 | They do the same thing.
| | 03:40 | They create an instance of the
String class and so welcome is an object.
| | 03:45 | But you can go further with this idea,
because within a string object there is
| | 03:49 | actually an array of individual
objects, one for each character.
| | 03:53 | So you can say that welcome is a String,
Hello or you can say that welcome is an
| | 03:58 | array of six object, H-e-l-l-o-!
| | 04:03 | And here is a bit of code
that breaks it down even further.
| | 04:06 | I'll start off with an array of characters.
char, bracket, bracket means create an array of
| | 04:12 | characters. The name of the array is
chars, C-H-A-R-S, and then the following
| | 04:17 | syntax with the individual characters
each wrapped in single quotes and then all
| | 04:22 | then all six characters wrapped
inside braces, means create an array.
| | 04:26 | I can take that array of characters and
wrap them inside a new string called s
| | 04:31 | and now once again I have either an
array of six objects or a single object the
| | 04:37 | String s. When you start seeing
everything as an object, you see that you can
| | 04:41 | break things down to their
smallest components in Java;
| | 04:45 | a String is really an array of characters.
| | 04:47 | A primitive numeric value is an
individual value, but a complex object can
| | 04:53 | reference many objects.
| | 04:55 | By breaking things down into small
pieces in Java, it makes it easy to find the
| | 04:59 | code that you want to expand on or fix.
| | 05:03 | The output of this code would be simply Hello!
| | 05:06 | Because the String class is a complex
object, it can encapsulate or offer all
| | 05:11 | sorts of functionality and in fact
the String class, which in longhand is
| | 05:15 | java.lang.String includes many, many methods.
| | 05:20 | This is a short list of just a few of the
methods that are a part of the String class.
| | 05:24 | The charAt method lets you pass in a
numeric value and get back the character
| | 05:29 | in the position in the array that's a
part of the String class, you can use
| | 05:32 | compareTo to compare one String to
another, the concat to concatenate Strings
| | 05:37 | together and so on.
| | 05:39 | We'll be looking at these and many
more methods of the String class later on,
| | 05:43 | but my point is that a string is not
simply a string, it's an instance of a
| | 05:47 | class and that gives you access to
all the functionality that's built into
| | 05:52 | that class as a part of the Java
Programming Language and its core runtime,
| | 05:57 | the Java Class Library.
| | Collapse this transcript |
| Declaring and initializing variables| 00:00 | As with all good programming languages,
Java supports the use of variables to
| | 00:05 | store data in memory.
| | 00:06 | There are two major types of variables in
Java known as primitives and complex objects.
| | 00:12 | Primitive variables are stored in the
fastest possible memory, but there is a
| | 00:16 | very small number of data
types that you can store this way.
| | 00:19 | They include numeric values such as
integers and floating decimals, single
| | 00:24 | characters not complete strings, and
Boolean values, variables that equate to
| | 00:29 | either true or false.
| | 00:31 | These values can be stored as primitive
values and so they are placed in memory
| | 00:36 | and they can be accessed very, very fast.
| | 00:39 | Everything else that you might want to
store in memory in a Java application is
| | 00:43 | going to be represented as a complex object.
| | 00:46 | You have to clear a complex
object as an instance of a Java class.
| | 00:51 | Here are some data types that you might
think of as simple values depending on
| | 00:54 | what languages you might have used
before, but in Java, are complex.
| | 00:59 | These include strings.
| | 01:01 | Any string value longer than a single
character must be stored as a complex
| | 01:06 | object and not as a primitive.
| | 01:08 | Date values which can be interpreted as
numeric values, the number of ticks from
| | 01:14 | a particular date, but in terms of Java
memory management are stored as complex
| | 01:19 | objects and everything else
that you might want to work with.
| | 01:23 | As I have mentioned previously, pretty much
everything in Java is an object of some kind.
| | 01:29 | So how do you actually
declare a variable in your code?
| | 01:32 | The syntax looks very similar
regardless of whether you are working with
| | 01:36 | a primitive or a complex object, but
there is a significant syntactical difference.
| | 01:41 | Let's look at primitives first.
| | 01:43 | You declare your variables in three parts.
| | 01:46 | The first part is the data type.
| | 01:48 | Every variable that you declare in
Java has to be declared with its data type
| | 01:53 | and once the data type is
set, it can't be changed.
| | 01:57 | This is how the Java virtual machine
determines how much memory needs to be allocated.
| | 02:02 | The second part is the variable name.
| | 02:05 | Variable names in Java always start
with the lower case initial character which
| | 02:09 | can be an alphabetical value or
an underscore, but not a numeric.
| | 02:13 | These two parts are required.
| | 02:15 | The third part is optional and it's
the initial value of the variable.
| | 02:19 | Here is a classic primitive
variable declaration int newVariable = 10.
| | 02:26 | The first part is the data type, int
stands for integer, so you are declaring
| | 02:31 | the variables in integer and you will only be
allocating enough memory to store an integer.
| | 02:36 | You can't just magically change this
variable at runtime and turn it into say
| | 02:40 | a double or a float.
| | 02:43 | It's always going to be an integer.
| | 02:44 | The second part of the
variable declaration is the name.
| | 02:48 | The name of the variable can't have any
spaces or other special characters in it
| | 02:53 | and the initial character has to be
either alphabetical or an underscore
| | 02:57 | character, it can't be a number.
| | 02:59 | The length of the variable name is up
to you, but I recommend that you name the
| | 03:03 | variables so that they mean
something to you as a developer.
| | 03:06 | You'll see variable named i or x in
varied limited scopes, but if a variable
| | 03:11 | is going to stick around and be useful in
your application, give it a name that matters.
| | 03:16 | The last part of the declaration is optional.
| | 03:19 | This is this assignment of the initial value.
| | 03:22 | You use the equals operator which is
the assignment operator and you pass in a
| | 03:26 | value that's compatible with
the data type that you declared.
| | 03:30 | The value 10, in this
context, is a literal integer.
| | 03:34 | So I am assigning the value of 10
to the integer and while I can change
| | 03:38 | the value of new variable later on the
value I assign later also has to be an integer.
| | 03:44 | If you leave the assignment off, then the
primitive variable will have its default value.
| | 03:49 | For numeric, that's always zero.
| | 03:52 | For Booleans, it's false.
| | 03:54 | Now let's take a look at how
you declare a complex object.
| | 03:57 | The declaration of a variable as a complex
object once again is an instance of a class.
| | 04:03 | As with primitives, you
declare them in three parts;
| | 04:06 | the required data type and required
variable name and then the optional
| | 04:10 | assignment of the initial value.
| | 04:12 | When you set the value of a complex
object you use the new keyword and a
| | 04:17 | particular kind of function or method
called the constructor method of the class.
| | 04:22 | The name of the constructor
method matches the name of the class.
| | 04:25 | So if you are declaring something is
a string, then you are going to use
| | 04:29 | a method name String.
| | 04:30 | Here is what the code looks like.
| | 04:32 | Once again it will have the data
type and the variable name and then
| | 04:36 | optionally the initialization.
| | 04:38 | The first part of this
declaration is the data type.
| | 04:41 | I am referring to a class.
| | 04:43 | How do I know this is a
class and not a primitive?
| | 04:46 | Well, primitive data types
are always all lower case.
| | 04:49 | So int double float Boolean and so on,
they will be spelled all lowercase.
| | 04:55 | When you see a data type within an
initial uppercase character, now you are
| | 04:59 | talking about a class and you know
you are working with a complex object.
| | 05:03 | The variable name once again goes
second and the conventions for naming complex
| | 05:08 | object variables, is the same as for primitives.
| | 05:11 | The initial character must be an
alphabetical character or an underscore,
| | 05:15 | you can't use numbers for the first character
and by very strong convention it's lowercase.
| | 05:20 | You can use uppercase characters in
the middle, a syntax, we sometimes call
| | 05:24 | camel case to make it more readable.
| | 05:27 | The optional assignment looks like this.
| | 05:29 | As with primitives you use the equals
assignment operator, but now because you
| | 05:34 | are creating an instance of a class,
you use the new keyword and you call the
| | 05:38 | constructor method of the class
which matches the name of the class.
| | 05:43 | Some constructor methods are called
without passing any values in and some
| | 05:47 | constructor methods are called and
you have to pass values in and in some
| | 05:50 | cases it's optional.
| | 05:52 | You'll look at the API documentation for
the class you want to use to figure out
| | 05:56 | what the right syntax is.
| | 05:58 | For complex object variables, if you
eliminate the assignment, the variable name
| | 06:03 | will exist, but it won't point to
anything in memory and we say that that
| | 06:07 | variable has a value of null, n-u-l-
l and I'll show how to deal with null
| | 06:13 | values, later in the course.
| | 06:15 | When you need to clear a variable, it's
important to know what its scope and lifetime is.
| | 06:20 | You can either declare a variable inside
a function or method or you can declare
| | 06:24 | it outside the function as a part of the class.
| | 06:27 | When you declare the variable inside
the function, the variable is local to the
| | 06:31 | function and when the function is
finished executing, the variable goes away.
| | 06:36 | It's no longer available.
| | 06:38 | We call it being dereferenced.
| | 06:40 | Here is an example of a string variable
which is declared inside a function or
| | 06:45 | method called doSomething.
| | 06:47 | The data type is String.
| | 06:49 | The name of the variable is sayHello
and it's an instance of this String class
| | 06:53 | with the value Hello!.
| | 06:55 | This code works fine because I am
referencing a variable that was declared
| | 06:58 | inside the same function in which I am
trying to output it, but let's take a
| | 07:03 | look at a bit of code that doesn't work so well.
| | 07:05 | In the function, doSomethingElse, I
am once again declaring a variable and
| | 07:09 | giving it an initial value of Hello!
| | 07:12 | But then I try to reference that
variable in code that's outside the function.
| | 07:17 | Because the variable was declared
inside the function, it is not available to
| | 07:21 | code outside the function, it can only
be referenced inside the function and
| | 07:26 | when you type this code and try to
save your application, you'll get a
| | 07:29 | Compile-time error!!.
| | 07:31 | If you are working in an Eclipse you'll
see something in the Problems view that
| | 07:34 | says I don't know what that
variable is, it's not in scope.
| | 07:38 | There are times when you want
variables to be available to more than one
| | 07:42 | function or method at the same time and
there are a few different ways of doing this.
| | 07:46 | One of the most popular is to use
something called a class variable known
| | 07:50 | officially in Java as a field.
| | 07:53 | When you declare a variable outside of
the function, it belongs to the whole
| | 07:57 | class and it can be referenced
by any function within the class.
| | 08:01 | Here is an example.
| | 08:02 | I am declaring a class called MyClass.
| | 08:05 | Notice that this time I
don't have a main method.
| | 08:07 | So this is not a class that's
starting up the whole application.
| | 08:10 | Within the class, I am declaring a
variable and giving it a data type of String,
| | 08:15 | a name of sayHello and
once again an initial value.
| | 08:18 | The function doSomething can reference
that variable because the function and
| | 08:23 | the variable are both members of the class.
| | 08:27 | As long as the method and the
variable are both part of the same class, the
| | 08:30 | method can reference the
variable and use its value.
| | 08:34 | So once again this kind of variable
is officially called a field in Java.
| | 08:39 | You will also hear it referred to
sometimes as a class variable, but the two
| | 08:43 | phrases mean the same thing,
class variable and field.
| | 08:46 | And if you look at the documentation
for the classes in the Java Class Library,
| | 08:51 | you'll see that this type of variable is
referred to as a field in the API docs.
| | 08:57 | So that's a brief look at how to
declare variables and a little bit about the
| | 09:01 | differences between
primitives and complex objects.
| | 09:05 | In the next video, we'll do some
exercises in Eclipse where we declare some
| | 09:09 | variables and output their values
using the System.out.println syntax.
| | Collapse this transcript |
| Working with numbers| 00:00 | In Java, you can represent numbers as
either primitive values or as complex objects.
| | 00:05 | I am going to start by showing you how
you represent them as primitives and then
| | 00:09 | show, how to convert them
into complex objects when needed.
| | 00:12 | A primitive data type is a simple value.
| | 00:15 | It represents only a single value and not many.
| | 00:18 | That's one of the big differences
between primitive values and complex objects.
| | 00:22 | A primitive always points to a single value.
| | 00:25 | Primitive data types are stored in the
fastest available memory, whereas complex
| | 00:29 | objects are stored in heap memory.
| | 00:32 | When you are running an application, you won't
see significant differences, but they do exist.
| | 00:37 | Primitives can be used to represent
numeric, logical, or single character values.
| | 00:42 | They can't be used to represent strings,
dates or other things that have to be
| | 00:46 | represented as complete objects.
| | 00:48 | Most of your numeric values
will be declared as primitives.
| | 00:51 | You will only need to use complex
objects where you need to do conversions or
| | 00:56 | you need to guarantee precision when
doing certain kinds of calculations.
| | 01:00 | When you declare a primitive data type,
you spell the data type in all lowercase.
| | 01:05 | So for example int, i-n-t or
byte would be spelled all lowercase.
| | 01:10 | There are also classes with these names, but
they will have an uppercase initial character.
| | 01:14 | Here are the numeric primitive data types.
| | 01:17 | The byte data type takes 8-bits and can
represent numbers starting at -128 and
| | 01:23 | going to a maximum of 127.
| | 01:26 | The short integer takes 16-bits and has
much greater range and the most commonly
| | 01:32 | used integer data type int takes 32-bit
to memory and has a minimum and maximum
| | 01:38 | of over 2 million in each direction.
| | 01:40 | There is also a long integer.
| | 01:42 | It takes twice the memory that an int
does and should only be used when you are
| | 01:46 | representing very large numbers.
| | 01:48 | Then there are two primitives
that can represent floating values.
| | 01:52 | The float takes 32-bits
and the double takes 64-bits.
| | 01:56 | You'll see developers represent
currency values frequently with doubles, but as
| | 02:01 | I'll explain later typically, you
will want to use a special class called
| | 02:04 | BigDecimal for that sort of purpose.
| | 02:07 | When you use primitives, you can set
their values directly using literal
| | 02:11 | representation of numbers.
| | 02:13 | For the first three primitive data
types, byte, short, and int, the syntax of
| | 02:18 | the number is pretty conventional.
| | 02:20 | It's just a numeric value without any quotes.
| | 02:23 | You can't include string values
such as currency symbols or commas.
| | 02:27 | When you get into the larger numbers,
the long, the float, and the double, the
| | 02:32 | syntax is a little different.
| | 02:34 | For long values, a literal numeric should
be followed with the letter l, for long.
| | 02:40 | You can use either an upper or
lowercase l, but because the lowercase usually
| | 02:44 | looks a lot like a 1, typically
developers will use the uppercase L. The float
| | 02:49 | value takes a lowercase f and the
double value, a lowercase d. Again, you could
| | 02:54 | use uppercase, but most
developers use lowercase for these.
| | 02:58 | If you don't put in those additional
alphabetical characters, usually things
| | 03:01 | will still work out okay, but what's
happening internally, may surprise you.
| | 03:06 | If you don't put in that additional
alphabetical character into your code, the
| | 03:09 | value will be cast, based on a set of
rules, that Java follows, for example the
| | 03:14 | 100 would be initially be cast a byte
and then it would be up cast to the long.
| | 03:19 | So you are actually taking more
memory than necessary creating two values
| | 03:23 | where only one is needed.
| | 03:25 | So it's recommended that if you are
explicitly using a literal to represent a
| | 03:29 | long, a float or a double
then use these characters.
| | 03:34 | In addition to the primitive data
types for numbers, there are also a set of
| | 03:38 | helper classes that are
part of the Java Class Library.
| | 03:41 | Each of these helper classes
includes tools for converting and
| | 03:44 | outputting numeric values.
| | 03:47 | Here is a listing of the data types
on the left and their matching helper
| | 03:50 | classes on the right.
| | 03:52 | For the most part the names match,
byte is byte, short is short and so on and
| | 03:57 | the only difference is the initial character.
| | 03:59 | The primitive data type is all lowercase.
| | 04:02 | The class name has an
initial uppercase character.
| | 04:04 | The only difference is in the integer
where the primitive Data Type is int and
| | 04:10 | the name of the Helper Class is Integer
with an uppercase I. The helper classes
| | 04:15 | have all sorts of great tools in them and
they are always available to your Java code.
| | 04:20 | Here is an example.
| | 04:21 | The Double class provides methods
and other tools for converting and
| | 04:25 | managing double values.
| | 04:27 | Let's say you started off with a
literal doubleValue of 156.5d and you assigned
| | 04:33 | that to a primitive variable of doubleValue.
| | 04:36 | Well, in order to convert it, the
first step would be to create an instance
| | 04:40 | of the Double class.
| | 04:42 | This would be the syntax.
| | 04:43 | The data type has Double with an
uppercase D, which means the helper class
| | 04:48 | and not the primitive.
| | 04:49 | I am constructing an instance of the
Double class and passing in the primitive value.
| | 04:54 | Now I can convert that value using a
set of methods called byteValue, intValue,
| | 05:00 | floatValue and toString.
| | 05:03 | These are instance methods or
class methods of the Double class.
| | 05:07 | We'll learn more about what that means
in later videos, but for now just take
| | 05:11 | it to mean that you can call these methods
whenever you create an instance of the class.
| | 05:16 | Because a doubleValue you can have
more precision than say a byte or an int,
| | 05:20 | calling this syntax will
result in truncating the value.
| | 05:24 | So the result of myIntValue would be simply 156.
| | 05:28 | The result of myByteValue though
because 156 exceeds the available range of a
| | 05:33 | byte, would wrap around and you would
actually end up with a negative number.
| | 05:38 | I'll show you examples of
these in some of the codes samples.
| | 05:41 | When you declare a number, using a
primitive data type, if you don't set the
| | 05:46 | value initially, it defaults to zero.
| | 05:49 | So for example, here I am declaring a
variable called myInt and I am setting it
| | 05:53 | using the int data type.
| | 05:55 | I am not including the equals assignment
operator or an initial value and so the
| | 06:00 | result is that myInt is initially assigned as 0.
| | 06:05 | You'll see that this is true
of all the primitive numerics.
| | 06:08 | Now when you get into complex
objects instances of classes, the rules are
| | 06:12 | different, but we'll talk about that later.
| | 06:15 | There is one other major issue to know
about when you are working with numbers.
| | 06:19 | If your application requires numeric
precision, when you are doing calculations
| | 06:23 | or rounding, you shouldn't
use primitives for this purpose.
| | 06:26 | The problem is that primitive values
are stored in memory in a way that can't
| | 06:30 | guarantee that precision.
| | 06:32 | Instead, you should use a class
called BigDecimal especially when you are
| | 06:36 | working with currency values and you
need to do certain kinds of math, the
| | 06:40 | BigDecimal class can help
you guarantee that precision.
| | 06:43 | Here is an example of what can go wrong.
| | 06:46 | Let's say that you are starting off
with a primitive value, in this case
| | 06:49 | a literal of 1115.37.
| | 06:50 | I am going to create an instance of the
BigDecimal class called payment and I am
| | 06:57 | constructing it directly from that
literal value and then I am going to output
| | 07:02 | that value as a string.
| | 07:03 | You might think you would see the value
1115.37 as a string, but in fact you are
| | 07:09 | going to see something like this.
| | 07:11 | The exact value is going to vary
depending on your system, your processor and
| | 07:15 | other variables, but internally the
number is stored in a very surprising way.
| | 07:20 | So when you are working with currency
values, it's strongly recommend that you
| | 07:24 | construct your big decimals based on strings.
| | 07:28 | This guarantees that you are talking about
exactly the value you think you are talking about.
| | 07:33 | Let's say for example that you start off
with a double value once again of 1115.37.
| | 07:39 | Before you create your instance of
BigDecimal, you should first get a string
| | 07:43 | representation of the number.
| | 07:45 | This guarantees that any additional
decimal values are truncated and you are
| | 07:50 | only working with the value you want.
| | 07:52 | So the second line of code uses the
Double class's toString method and converts
| | 07:56 | to a value called ds, data-typed as a string.
| | 08:00 | Now I construct the instances of
BigDecimal based on the string and then output
| | 08:05 | the value and now I get what I expect.
| | 08:07 | We'll talk more about the BigDecimal
class in a later video in the series.
| | 08:12 | So that's a look at
representing numeric values in Java.
| | 08:15 | For most purposes, the primitive data
types do a great job, but in many cases,
| | 08:20 | you want to use the numeric helper
classes that are part of the class library
| | 08:24 | and specifically when you are
working with currency values and doing
| | 08:28 | calculations and rounding, you
should look at the big decimal class.
| | Collapse this transcript |
| Converting numeric values| 00:00 | There will be times in your
applications when you need to convert values from
| | 00:04 | one data type to another.
| | 00:06 | It's important to understand how
data types are converted especially when
| | 00:09 | working with primitives.
| | 00:11 | Here are the primitive numeric
data types arranged in order from the
| | 00:14 | greatest memory usage and the
largest ranges to the smallest memory usage
| | 00:19 | again the smallest ranges.
| | 00:21 | So the double takes 64-bits and can
handle the greatest precession or as the
| | 00:26 | byte has the smallest range.
| | 00:28 | When you convert a value from say a byte
to a short, a short to an int or an int
| | 00:32 | to a long, we call that converting
upward, you're taking a value that fits
| | 00:37 | easily into the next value upward.
| | 00:39 | You can do this sort of
conversion with very simple syntax.
| | 00:43 | Here I'm declaring an integer value
of 120 and then passing that value to a
| | 00:47 | new variable data typed as a double, the
value of 120 can fit easily in either data type.
| | 00:54 | And so the result is that you have a
value of 120, the double version would have
| | 00:58 | the decimal value of 0, the integer
value would be truncated but they would
| | 01:02 | fundamentally have the same value.
| | 01:04 | We call this sort of numeric conversion
implicit you can simply assign a value
| | 01:09 | from one variable to another without any
special notation and because all of the
| | 01:14 | conversion is reliable that is the
values will fit in both variables easily you
| | 01:18 | don't have to say anything
specific in your code about it.
| | 01:21 | When you're converting values in the
other direction though you can run into
| | 01:25 | some trouble and so Java requires
you to be explicit in these sorts of
| | 01:29 | conversions, once again here is my
listing of the numeric data types, but now
| | 01:34 | I'm indicating through the arrows that
I'm going to do the conversions in the
| | 01:38 | other direction from a double
to a float or a float to a long.
| | 01:42 | We call these downward conversions.
| | 01:44 | Here is an example, I'm starting with
the double value of 3.99 and then I try
| | 01:49 | to convert the value to an integer by
simply assigning the value to the new variable.
| | 01:54 | You won't even be able to compile this
code because Java knows that you're in
| | 01:58 | danger of loosing data.
| | 02:00 | So if you add this code to your Java
class and try to save and compile you'll
| | 02:04 | get a compile-time error.
| | 02:06 | The compiler will tell you that those two
data types aren't compatible with each other.
| | 02:11 | So you instead have to explicitly tell
the compiler that you know what you're
| | 02:15 | doing and you do this by adding the
target data type before the original value
| | 02:20 | wrapped in parenthesis, here is
the added syntax this means take the
| | 02:24 | doubleValue and cast or convert the value to
an integer and then you can pass the value over.
| | 02:30 | You're still in danger of loosing data;
| | 02:32 | the value of 3.99 which fits fine in a
doubleValue doesn't fit in an integer
| | 02:38 | value, because integers
can't have fractional amounts.
| | 02:41 | So when you do this you're going to
truncate the value, it's going to end up as
| | 02:44 | the value 3, but you've told the Java
compiler that that's what you want to do
| | 02:49 | and so the compiler will let you do it.
| | 02:51 | The double value will still be 3
.99, but the integer will be 3.
| | 02:56 | So the lesson to take from this is that
when you converting downward you have to
| | 03:00 | be explicit in your code and you have
to know that you might change the data.
| | 03:05 | The dangers of downward conversion
aren't limited to simply truncating and
| | 03:08 | loosing values you could actually
change values pretty dramatically.
| | 03:12 | Let's take an example where you
start off with an integer and you want to
| | 03:15 | convert it to a byte.
| | 03:17 | Well, the ranges of integers
and bytes are very different;
| | 03:20 | integers can handle values in the
two millions both positive and negative
| | 03:25 | whereas bytes can only handle
values from negative 128 to positive 127.
| | 03:31 | So what happens if you start off with
an integer say if 128 that exceeds the
| | 03:36 | range of the byte and then you
explicitly tell Java I want to turn this into a
| | 03:40 | byte what is it going to do.
| | 03:42 | Well it's going to take the value that
exceeds the range of the target data type
| | 03:47 | the byte and it's going to wrap
around and assign an opposite value.
| | 03:52 | So if you start off with a positive
you end up with a negative, the result of
| | 03:56 | this code would be a Value of b of -128.
| | 04:01 | Remember the range of a byte goes
from negative 128 to positive 127.
| | 04:07 | I'm trying to assign a value that
exceeds that range by 1, so it wraps around
| | 04:12 | by 1 and becomes negative 128, the
smallest possible number instead of the
| | 04:17 | greatest possible number.
| | 04:18 | You'll see this sort of conversion
this wrapping around whenever you try to
| | 04:22 | convert a value downward
from one data type to another.
| | 04:26 | Finally, in the discussion of
converting numeric values it's worth mentioning
| | 04:30 | that there are two possible ways of doing it.
| | 04:33 | When you're converting between
primitive data types you can either use this
| | 04:37 | casting syntax that I've shown or you
can use those helper classes, the double
| | 04:41 | class, the byte class,
the integer class and so on.
| | 04:45 | The simple casting syntax uses the
target data type wrapped in parenthesis right
| | 04:51 | before the original value.
| | 04:52 | So here I have a double value, a
primitive double starting off a 3.99, I
| | 04:57 | explicitly convert that to an integer
using the casting syntax and now I can
| | 05:02 | assign that to an int.
| | 05:03 | Again I'm going to truncate values, I'm
going to loose data but it's going to work.
| | 05:07 | So use the helper class approach, the
first step is to create an instance of the
| | 05:12 | helper class wrapped around the primitive value.
| | 05:15 | So here I'm starting once again with
a primitive and then I'm creating an
| | 05:19 | instance of the double class wrapped around
the primitive, I'm calling that double0bj.
| | 05:24 | Once I have that reference that
complex object I can then call any of its
| | 05:29 | method, so now I'm going to call the
intValue method, it's going to return an
| | 05:34 | integer and I can assign
that to the primitive int.
| | 05:37 | Either of the syntax styles will work fine.
| | 05:39 | There is a minor advantage to the
simple casting syntax clearly it takes less
| | 05:44 | code, but also you're not
adding another object to memory.
| | 05:48 | When you use the helper class method you
are creating an instance of that double
| | 05:51 | class that you really don't need.
| | 05:53 | So for the most part the simple casting
syntax is preferred and the only time I
| | 05:58 | would recommend using the helper class
approach is when you want to store that
| | 06:02 | data for the longer term and
do multiple things with it.
| | 06:06 | Convert it to an integer and
a byte and a float and so on.
| | 06:10 | So that to look at issues around converting
numeric values from one data type to another.
| | 06:15 | You can use either the casting of the
helper class method syntax and always be
| | 06:20 | aware of what happens when you try
to cast from one data type to another.
| | 06:24 | When you are converting the data
upward through the data types all the
| | 06:27 | conversions are implicit and safe,
when you're converting downward beware of
| | 06:32 | loosing data, wrapping values around,
and also note that you have to be explicit
| | 06:37 | in your instructions to the compiler.
| | Collapse this transcript |
| Understanding operators| 00:00 | Every programming language supports
operators, characters or sets of characters
| | 00:05 | that execute particular operation.
| | 00:07 | Java remember is C-style language and
it uses the same set of operators as
| | 00:12 | most such languages.
| | 00:14 | If you already know JavaScript or
ActionScript you will find that the operators
| | 00:18 | in Java are almost identical.
| | 00:20 | Here are some of the types of
operators I'll discuss in this video.
| | 00:23 | Assignment operators let you set values.
| | 00:26 | There is a Simple Assignment
Operator and then there were more Complex
| | 00:29 | Assignment Operators that let you
assignment and math in a single statement.
| | 00:34 | There are equality and relational operators
that let you compare values to each other.
| | 00:39 | There are mathematical operators
that let you execute common mathematical
| | 00:42 | process, Conditional operators that
let you define complex conditional
| | 00:46 | processes, and the ternary operator
which is a special operator I'll describe in
| | 00:51 | a later video when I
discuss conditional processing.
| | 00:55 | The most common operator that
you'll find yourself using is the
| | 00:58 | Assignment operator.
| | 00:59 | The single equals character
is the assignment operator.
| | 01:03 | You put the variable you're assigning to
on the left and the value on the right.
| | 01:07 | You can assign a literal value or a
value return from a method or a reference
| | 01:11 | to a complex object.
| | 01:13 | Regardless of what you're assigning the
single equals operator always is used.
| | 01:17 | The simple math operators are the same
as in JavaScript and ActionScript, the
| | 01:22 | plus operators is used for math.
| | 01:24 | So if I start with the value of 10 and I
increment it by 5 with the + operator I
| | 01:28 | get a value of 15, the - character
is the traditional minus operator, the
| | 01:34 | asterisk is used for multiplication
and the forward slash is division.
| | 01:39 | There is another single character
operator worth knowing about the modulus
| | 01:42 | or remainder operator.
| | 01:43 | Java uses the % character for this.
| | 01:46 | If you take a value of 10 and you take the
modulus of 5 that returns a reminder of 0.
| | 01:53 | So those are the five primary math operators.
| | 01:56 | You can combine these math
operators with assignment too.
| | 02:00 | Once again starting with an initial
value of 10, let's take look at how you can
| | 02:04 | increment and decrement values. The ++;
| | 02:07 | operator means add one, so
adding 1 to 10 gives you 11, the - -;
| | 02:12 | operator goes in the other direction
decrementing by one and that would give you a result of 9.
| | 02:17 | Here is how you can combine math
operators with assignment, += means take the
| | 02:23 | current value of this variable and add
whatever is on the right side. So intValue +=5;
| | 02:29 | would be 15. intValue -=5;
| | 02:31 | would be 5, *= 5;
| | 02:33 | equals 50 and /= 5;
| | 02:36 | would result an intValue having a value of 2.
| | 02:39 | Be aware that when you use the /= you
need to make sure that you're assigning a
| | 02:44 | value that matches the data
type of the original variable.
| | 02:48 | When you use the increment and
decrement operators you can place them either
| | 02:51 | before or after the variable name, the
operational result will be a little bit
| | 02:56 | different depending on the
position of the operator.
| | 02:58 | Once again starting with the value of
10, a Postfix operator looks like this
| | 03:03 | intValue ++, when you place the ++
operator after the variable you're saying
| | 03:09 | first evaluate the variable and then
execute the mathematical operation, because
| | 03:14 | I've wrapped this inside a print line
command I'm going to be outputting a value
| | 03:18 | and changing it's value, but you need
to know that with this Postfix syntax the
| | 03:23 | evaluation happens first and only
after that does the math happen.
| | 03:28 | The result would be an output of 10,
but then after the statement is complete
| | 03:33 | the new value of the variable would be 11.
| | 03:35 | If you move the ++ operator before the
variable name that's called a Prefix or a
| | 03:40 | Unary operation, this would mean do
the math then evaluate the variable.
| | 03:46 | And in this case the output and
the new value would be the same.
| | 03:49 | Java's relational operators, that is the
operators as you used to compare values
| | 03:54 | to each other look exactly as you would expect.
| | 03:57 | You have >, <, >= and <= values.
| | 04:02 | There is also a special operator called
instanceof it's all lower case and all one word.
| | 04:07 | You use the isntanceof operator to
determine whether a variable is a member
| | 04:11 | of particular class.
| | 04:13 | Here is an example I declare a variable with a
data type of String and I set it to some value.
| | 04:19 | Now, I want to test that variable
and ask whether it's an instance of
| | 04:23 | a particular class.
| | 04:25 | Typically when you use the instanceof
operator you refer to the class by its
| | 04:29 | fully qualified strength, its
package, and its class name.
| | 04:32 | The String class is a member of the
java.lang package, so the complete
| | 04:36 | evaluation of (s instanceof java.lang.
String) means is s a String and if so then
| | 04:45 | I would output the String
that's in the middle of if clause.
| | 04:48 | One very important thing to know about
comparisons is that you can't use the
| | 04:52 | traditional comparison or relational
operators when you're working with Strings.
| | 04:56 | Let's take a look at this code, there
are two Strings named s1 and s2, they have
| | 05:01 | identical values of "Hello";
| | 05:03 | and now I put in some conditional code,
I ask the question if (s1 ==s2) then
| | 05:10 | output ("They match");
| | 05:11 | and otherwise output ("No match!);.
| | 05:13 | In some languages such as JavaScript
you would get a match because in those
| | 05:18 | languages they're comparing the values
of the Strings, but in Java a String is a
| | 05:23 | complex object and with complex objects
the double equal operator is comparing
| | 05:28 | whether they're the same object, not
whether they have the same value and so
| | 05:33 | this evaluation would
result in the output No match!.
| | 05:36 | If you want to compare two Strings you
instead need to use a special method or
| | 05:41 | function of the String class.
| | 05:42 | Here is the correct example, once again
I'm declaring two Strings named s1 and
| | 05:47 | s2, now I'm going to use the equals
function or method of the String class and
| | 05:52 | I'm asking whether the values of these
two variables match, not whether there
| | 05:56 | the same object and this
time the output is They match!
| | 06:00 | With primitive variables you can use
that double equal operator and you'll be
| | 06:04 | able to match the values to each
other, but with complex objects like the
| | 06:08 | String you frequently have to use a method of
the class to determine whether the values match.
| | 06:14 | Speaking of equality, here is how you
compare values when you're working with primitives.
| | 06:18 | The equality operator is double equal sign.
| | 06:21 | Be sure you're using double equals not
single equals, if you use single equals
| | 06:25 | you'll be assigning the
value and not comparing it.
| | 06:28 | The inequality operator is an
exclamation mark and the equal sign.
| | 06:33 | So this syntax is asking if
this value is not equal to that.
| | 06:37 | And finally you can also use the
exclamation mark on it's own to reverse the
| | 06:41 | value of a Boolean Expression.
| | 06:43 | A Boolean Expression evaluates to
either true or false, when you apply the
| | 06:48 | exclamation mark before
it that reverses the value.
| | 06:51 | If it's started as true it becomes false
and if it started as false it becomes true.
| | 06:57 | You'll hear some developers refer to the
exclamation mark as the bang character B-A-N-G.
| | 07:03 | And so if they were reading this code it
would be if bang this then do something
| | 07:10 | regardless of what you call it bang or
the exclamation it reverses the logic,
| | 07:15 | changing a Boolean value from
true to false or vice versa.
| | 07:19 | Here are some conditional operators that
you can use in complex logical operators.
| | 07:24 | The double ampersand is Conditional AND.
| | 07:27 | In this code the output would only
happen if both this and that are true.
| | 07:32 | You can also do a Conditional OR using
the double pipe character, in this code
| | 07:37 | the output is going to happen if
either of those variables equates to true.
| | 07:42 | I'll show you more about how to combine
these conditional operators with various
| | 07:46 | types of conditional expressions in
later videos, but you should now have a good
| | 07:50 | sense of the kinds of operators that
are available in Java and how similar they
| | 07:55 | are to other C-style languages.
| | Collapse this transcript |
| Working with character values| 00:00 | Java allows you to represent strings
in one of two ways as complex objects or
| | 00:05 | as single character.
| | 00:06 | When you are working with single
characters you can work with either a primitive
| | 00:10 | data type or with a
wrapper class for the data type.
| | 00:13 | I am working in a project named
characters which you can find in the 04 chapter
| | 00:17 | of the exercise files.
| | 00:19 | In order to declare variable that uses
the primitive card data type you start
| | 00:23 | off with the keyword car or char.
| | 00:26 | You don't spell out the whole word
character, it just those first four letters
| | 00:30 | then you assign a variable name as
usual and then you can either assign
| | 00:33 | something that returns a character
or you can assign a literal character.
| | 00:38 | Literal character values are wrapped
in single quotes, never double quotes.
| | 00:42 | I am going to set the value of this
character to a numeric value of one
| | 00:46 | because I want to show you that when
you pass in a numeric value but rapid in
| | 00:50 | those quotes it's no longer really a number
and it can't easily be turned into a number.
| | 00:55 | It can be converted to another variable
that's a number, but this variable will
| | 00:59 | always be a character.
| | 01:00 | Now I am going to copy and paste this
line of code a couple of times and I am
| | 01:04 | going to rename the second 2 variable as c2
and c3 and change their values to 2 and 3.
| | 01:11 | Now I am going to output
those values to the console.
| | 01:14 | System.out.print and then
I'll pass the values c1.
| | 01:19 | notice I am using print and not
println because I want to output this but not
| | 01:24 | pass in a line feed at the end.
| | 01:26 | Now I'll copy and paste that line of
code a couple of times, and I will output
| | 01:31 | c2 and c3 and I'll change
the last one to println.
| | 01:35 | I'll save the changes and run the
application and there is the result.
| | 01:40 | 1, 2, 3 three characters
output right next to each other.
| | 01:44 | You can also set a character
variable using a Unicode literal.
| | 01:48 | Unicode is a way of describing
individual characters in the alphabet
| | 01:52 | using numeric codes.
| | 01:54 | You can look up the numeric codes for
Unicode on the website Unicode.org, that's
| | 01:58 | u-n-i-c-o-d-e.o-r-g.
| | 02:02 | I have looking up the value of the
currency symbol the dollar sign and I found
| | 02:06 | that it's a four digit number of 0024,
here is how you could use that code to
| | 02:11 | set a char variable in Java.
| | 02:13 | I once again start off with the char data
type and I'll name this variable dollar.
| | 02:18 | To set the literal value with Unicode
start with the pair of single quotes as
| | 02:22 | before but prefix the four digit
numeric with \u, then I'll pass in 0024.
| | 02:29 | Next I'll add another system.out.
print at the beginning of the string and I
| | 02:33 | will output dollar.
| | 02:34 | I will save the changes and run the
application and there is the result.
| | 02:38 | The dollar sign followed by the 1, 2 and 3.
| | 02:42 | Again these are four individual
characters not a single string but from the
| | 02:46 | application users point of
view it looks like just a string.
| | 02:49 | As all with primitive data types there
is a wrapper class available that you can
| | 02:53 | use to accomplish all sorts of things.
| | 02:55 | The name of the wrapper
class for char is character.
| | 02:58 | Now I've already brought up the
documentation for this class it's a member of
| | 03:02 | the Java.link package and is
always available to your code.
| | 03:06 | I'll go to the list of methods that are
part of the character class and show you
| | 03:10 | that there are all sorts of tools
for analyzing or changing values.
| | 03:14 | I'll go to the bottom of this
listing and show you that there is a method
| | 03:17 | called two uppercase.
| | 03:19 | It's marked as static which means I
call it from the class not from an
| | 03:22 | instance of the class.
| | 03:24 | We'll talk about static properties and
methods later on, but for now whenever
| | 03:28 | you see the world static just note that
you call it from the class name not from
| | 03:32 | an instantiated copy of the class.
| | 03:34 | You pass in and instance of the char variable.
| | 03:37 | So now I'll go back to my code and I
am going to go down to the bottom of the
| | 03:41 | code and add some more characters.
| | 03:44 | I'll start off with char a1=a char a2=
b and char a3=c.Now I'll make a copy of
| | 03:56 | these three print commands, copy them
downward and I'll change the values that
| | 04:01 | are being output to a1, a2, and a3.
| | 04:04 | I'll save the changes and run the
application and show that I am getting a, b,
| | 04:10 | c. now I'll use the two
uppercase method of the character class.
| | 04:14 | For each of these values I'll place
the cursor inside the print method and
| | 04:18 | call Character.toUppercase and I wrap the
method called around the value that I am outputting.
| | 04:26 | I'll make a copy of that line of code
that will be easier than we typing all
| | 04:29 | that a couple of times then I'll
paste it in a couple of times, change the
| | 04:34 | variables and change print to
print line for the last command.
| | 04:39 | I'll save my changes and run the
application and now I am outputting the
| | 04:43 | uppercase versions of those character values.
| | 04:45 | Notice I am not changing the original values,
I am only modifying them as I output them.
| | 04:50 | So the original lowercase
versions are still available.
| | 04:54 | So that's a look at how to use the char also
sometimes pronounced char, char, or char data type.
| | 05:01 | Once again it represents a single
alphanumeric character the literal value is
| | 05:05 | always wrapped in single quotes never
double quotes and in your literal values
| | 05:09 | you can use either the real
character or the Unicode equivalent.
| | Collapse this transcript |
| Working with boolean values| 00:00 | True and false values are
stored in Boolean variables in Java.
| | 00:04 | You can either use primitive data
types or the matching wrapper class also
| | 00:08 | spelled Boolean with an uppercase B. I
am working in a project named Booleans
| | 00:12 | which you can find in
Chapter 04 of the Exercise Files.
| | 00:16 | I'll declare two variables.
| | 00:18 | For primitive data types, use
the keyword boolean, all lowercase.
| | 00:22 | My first variable will be names
b1 and will have a value of true.
| | 00:27 | The second variable will be b2
and it will have a value of false.
| | 00:32 | These are the only two possible
literal values for Booleans variables.
| | 00:36 | Unlike in many languages such as
JavaScript, you can't just replace the Boolean
| | 00:40 | keywords true and false with say numeric values.
| | 00:44 | There is no built-in logic that says 0
is false and any other number is true.
| | 00:49 | So you have to use the words true or false.
| | 00:51 | They are spelled in all lowercase and
don't get any quotes or other notation.
| | 00:55 | If you try to output these values to
the console, they will be translated as
| | 00:59 | their equivalent strings.
| | 01:00 | So I'll add this code System.out.println ("
The value of b1 is-- and then I'll append b1.
| | 01:08 | Then I'll make a copy of that and paste
it and I'll run the application and I'll
| | 01:14 | see that the value of b1 is
true and the value of b2 is false.
| | 01:19 | You can reverse the value of a Boolean
variable by prepending the exclamation
| | 01:23 | mark or bang symbol.
| | 01:25 | So for example I'll create a new variable.
| | 01:27 | I'll call it b3 and I'll use
the reverse value of b1 using !b1.
| | 01:35 | Then I'll make a copy of my
println command and I'll paste it in.
| | 01:40 | I'll change to the b3 variable and I'll
run the application and I see that the
| | 01:45 | result of reversing b1 which
started as true is now false.
| | 01:50 | If you want to evaluate numbers as
Booleans, you have to write the code
| | 01:54 | yourself, but it's actually a
pretty small amount of code.
| | 01:57 | Let's create an integer value
named i and set it to a value of 1.
| | 02:02 | Now again in many languages the #1
would have an equivalent value of true, but
| | 02:06 | that equivalents doesn't exist
already in Java, so we have to code it.
| | 02:10 | So I'll create a variable named
boolean b4 and I'll use this logic.
| | 02:15 | I'll create a pair of parenthesis and
in there I'll use the expression, i != 0.
| | 02:21 | So the expression comparing the value
of the integer to the value 0 is wrapped
| | 02:26 | inside parenthesis that forces it to
be evaluated first and then the Boolean
| | 02:30 | result which results from asking the
question do these values match is returned
| | 02:34 | to my boolean variable.
| | 02:35 | Then I'll once again use a println
command, I'll put the value of b4 and because
| | 02:42 | i does not equal 0, I
should get a value of true.
| | 02:47 | If I change the value of int i to
0 then the value of b4 is false.
| | 02:53 | So this simple expression is a very easy
way to take care of the situation where
| | 02:57 | you want to translate a
numeric value to a Boolean value.
| | 03:01 | Finally, just as with the other
primitive data types there is a wrapper class.
| | 03:05 | It's named Boolean with an uppercase B
and as with all the data type wrapper
| | 03:10 | classes, it's a member of the
package java.lang which means it always
| | 03:14 | available to your code.
| | 03:16 | The Boolean class has a fairly
small set of supporting methods.
| | 03:19 | I'll show you how to use this one, parseBoolean.
| | 03:22 | The parseBoolean method accepts a String
value and translates it into a real Boolean.
| | 03:26 | So let's go back to Eclipse and at the
bottom of the code, I am going to declare
| | 03:31 | a String, I'll just name is s
and I'll give a value of true.
| | 03:37 | Then I'll create a boolean variable,
I'll call it b5 and I'll call that parsing
| | 03:42 | method from the Boolean class, Boolean.
parseBoolean and I'll pass in the value
| | 03:47 | of s. And finally, I'll once again copy
and paste System.out.println and change
| | 03:55 | to output the value of b5 and show
you that the result is a value of true.
| | 04:02 | Now the logic that's going
on here is pretty interesting.
| | 04:04 | The parseBoolean method is non-case sensitive.
| | 04:07 | So I can actually spell the word true
with upper or lower case characters, even
| | 04:11 | though the true keyword
in Java is all lowercase.
| | 04:14 | I'll make that change and show you
that evaluation still returns true.
| | 04:19 | And if I change the value of s2, false,
either upper or lowercase, I'll get the
| | 04:25 | value false, so far as expected.
| | 04:27 | But what happens if you pass in a value
that's neither true nor false? I'll pass in xyz.
| | 04:33 | When I run the application
now, I don't get an error.
| | 04:36 | Instead, I get back a value of false.
| | 04:39 | The logic that this method is using is
if it's not true then it must be false.
| | 04:43 | So any version of the word true will return
true and any other string will return false.
| | 04:50 | So that's a look at some of the
rules around Booleans in Java.
| | 04:53 | Once again, you start off with the
keywords true and false which are the only
| | 04:57 | available literals for a Boolean variable.
| | 05:00 | You can reverse a Boolean variable,
using the != operator and you can use the
| | 05:05 | Boolean wrapper class to parse strings
as Booleans and accomplish other tasks
| | 05:09 | that are common to true and false values.
| | Collapse this transcript |
| Outputting primitive values as strings| 00:00 | No matter what kind of value you are
working within Java, you can typically
| | 00:04 | output that value as a string, simply
by concatenating it to some other value.
| | 00:08 | To demonstrate this, I have declared
eight variables, one each of the primitive
| | 00:12 | data types, character, Boolean, byte and so on.
| | 00:16 | Each of these is using a
literal value as its initial value.
| | 00:19 | Now I'll place the cursor after the
declarations and use System.out.println and
| | 00:25 | first I'll output the character.
| | 00:28 | I'll save and run the application and I
get the letter z, that's pretty expected.
| | 00:33 | Now one of the great things that Java
does for you is that when you want to
| | 00:36 | translate something into a string,
it's usually fairly automatic.
| | 00:40 | I am going to copy and then paste
this line seven times and I'll change the
| | 00:45 | values that I am outputting in each of
these lines using the Boolean, the byte,
| | 00:50 | the short, the integer, the
long, the float, and the double.
| | 00:55 | I'll save and run the
application again and there is the result.
| | 00:59 | Notice that all the values are
output almost exactly as they were set.
| | 01:03 | The one exception is the double which
had so many digits before the decimal that
| | 01:07 | Java automatically translated it for me.
| | 01:10 | When you output values using the out
object's print or println commands, these
| | 01:15 | are usually automatically translated to strings.
| | 01:17 | But the same translation happens
whenever you concatenate values.
| | 01:20 | Let' take one of these values, the
short and I am going to output the short
| | 01:24 | value, concatenate it to a string.
| | 01:26 | I'll use System.out.println ("The
value of s is -- and then I'll use the plus
| | 01:35 | operator and the value s. I'll save
the changes and run the application and I
| | 01:40 | get what you would expect,
The value of s is 32000.
| | 01:43 | Now, in some languages, it matters when
you are concatenating whether the first
| | 01:48 | value is a string or whether
the first value is a number.
| | 01:51 | In some languages, if the first
value is a number, then the plus operator
| | 01:55 | will be used for math, but if the
first value is a string then it will be
| | 01:59 | used for concatenation.
| | 02:00 | So let's test that in Java.
| | 02:02 | I'll take this println command and copy
and paste it and I'll reverse the order.
| | 02:06 | Instead of starting with the string,
I'll start with the numeric value, s + "
| | 02:11 | is the value of s. In some languages,
this would cause an error because the
| | 02:16 | first value was a number and the plus
operator should be seen as a mathematical
| | 02:20 | plus rather than as a string
concatenation plus, but in Java, the rule is that
| | 02:25 | if there is even one string involved then
the whole thing will be turned into a string.
| | 02:29 | I'll run the application and
I'll see that that works as well.
| | 02:33 | You can also combine math
and string concatenation.
| | 02:36 | If an expression starts with a
mathematical operation, such as 2+2, the math
| | 02:41 | will be executed first.
| | 02:42 | The result will then be converted to a string
and concatenated to the rest of the expression.
| | 02:47 | If you put the math at the end of the
expression though, everything will be
| | 02:50 | treated as a string.
| | 02:52 | Finally, complex objects are also
translated to strings automatically.
| | 02:56 | If you declare a string and then
output a string, that's pretty simple.
| | 03:00 | You are just getting the value of the
string object, but what about dates.
| | 03:04 | I'll create a new Date object.
| | 03:06 | I'll use the Date class and a variable
name of myDate = new Date and then I'll
| | 03:12 | use System.out.println ("The new
date is -- and then I'll output myDate.
| | 03:21 | If you see any errors, that means that
you have to include a special notation at
| | 03:26 | the top of the screen called a package.
| | 03:28 | The Date class is member of a
package that has to be explicitly imported.
| | 03:32 | I'll talk about class importing later,
but for now, all you need to do is place
| | 03:36 | the cursor after the data
type Date and press Ctrl+Space.
| | 03:41 | Then, choose this version of the Date
class, Date in java.util, double click
| | 03:47 | it and at the top of the screen, you'll
see a statement added import java.util.date.
| | 03:54 | That's an instruction to the compiler
that says, when I refer to the Date class,
| | 03:59 | this is the version I mean.
| | 04:00 | Now I'll save my changes and run the
application and I get a long string, the
| | 04:05 | string representation of
the current date and time.
| | 04:09 | So how is this happening?
| | 04:11 | Well, every complex class in Java
has a special method called toString.
| | 04:15 | Let's look at the
documentation for the Date class.
| | 04:18 | I'll double-click date
and then go to Dynamic Help.
| | 04:22 | I'll click on Javadoc for java.util.
date and maximize that screen, I'll click
| | 04:28 | the Method list, scroll down
and here is the toString method.
| | 04:33 | Every class has this toString method
and the implementation of the method is
| | 04:37 | going to be different from one class to another.
| | 04:40 | When you pass a complex object
into System.out.println or otherwise
| | 04:45 | concatenate the object to an existing
string, Java automatically looks for
| | 04:49 | this method, toString, executes it,
takes the return value, and that's what
| | 04:55 | will become a part of the string.
| | 04:57 | You'll see in later videos when you
create your own complex classes that you
| | 05:01 | can use this model pretty effectively for
debugging and other tools in your application.
| | 05:06 | When you create your own custom classes
and you give them a toString method, you
| | 05:10 | will be able to take instances of
those classes, pass them into these methods
| | 05:14 | that require strings and the
translation will happen automatically.
| | 05:18 | So that's a look at how values are
translated from their native data types
| | 05:22 | into strings in Java.
| | 05:24 | Again, primitives translate
automatically, but complex objects depend on the
| | 05:28 | toString method which is
implemented differently for each class.
| | Collapse this transcript |
| Creating a simple calculator application| 00:00 | It's time to put some of what we've
talked about to work in a real application.
| | 00:04 | This is going to be a very tiny
almost trivial application that does little
| | 00:07 | bit of calculation.
| | 00:09 | It will accept input from the command
line and then evaluate values that the
| | 00:13 | user types in as numbers and add them
together, not too complicated, but it will
| | 00:18 | require setting variables, converting
values, and doing a few other things that
| | 00:22 | I have taught how to do in this chapter.
| | 00:24 | I'm working in a project named
SimpleCalc that's available in the Exercise Files.
| | 00:28 | The calculative class in this project
has a main method that in turn makes a
| | 00:32 | call to a method called getInput, the
getInput method is down here, the purpose
| | 00:37 | of getInput method is to allow the user to
type a value in and then return it as a string.
| | 00:43 | I'm not going to talk right now about
the different classes that are used, the
| | 00:46 | BufferedReader and the
InputStreamReader, and in fact, for this lesson I'm
| | 00:51 | recommending using this
method as a bit of black box.
| | 00:54 | Just call the method knowing you'll get
back a String value and to make things
| | 00:58 | less complicated I'm going to collapse
the code by clicking on the little minus
| | 01:01 | icon right next to the method name.
| | 01:04 | And that leaves me with a very small view of
my code showing the details of the main method.
| | 01:09 | and the fact that there is a
getInput method that returns a String.
| | 01:12 | The application in its current state
calls the getInput method once and returns
| | 01:16 | the value as a variable called s1 and
then outputs that value to the console.
| | 01:21 | I'll run the application.
| | 01:23 | The value I pass into the method
enter a value is displayed as a prompt,
| | 01:27 | I'll type in a value, some value and press
Enter and that value is echoed to the console.
| | 01:34 | So I know that the input
method is working correctly.
| | 01:37 | Now the goal of this application is to
receive two numeric values, so I'm going
| | 01:42 | to change the prompt on this first call
to getInput and I'll change the prompt
| | 01:45 | to Enter a numeric value, then I'm going
to copy and paste that line of code and
| | 01:51 | I'll change the variable
that's being returned to s2.
| | 01:55 | I don't need this output for the
moment so I'm just going to commented out by
| | 01:58 | pressing Ctrl+/ on Windows or Command+/ on Mac.
| | 02:02 | Now the next step is to convert these
Strings to numeric values, I want my two
| | 02:06 | Strings to turn into two double values.
| | 02:09 | So I'm going to declare a double value
called d1 and I'm going to convert the
| | 02:14 | String to a double value using this
method of the double wrapper class,
| | 02:19 | Double.parseDouble and I'll parse in s1.
| | 02:22 | Then I'll do the same thing
for the second value double d2=
| | 02:27 | Double.parsedouble(s2).
| | 02:30 | And so now I have two numeric values.
| | 02:33 | Now I'm going to add the two values
together, I'll create a third double value
| | 02:38 | called result and now add d1+d2;
| | 02:42 | Now because I cast the numeric values
as doubles originally, they'll correctly
| | 02:46 | add together and create a third double.
| | 02:48 | And then finally, I'll uncomment this
command, System.out.println and I'll
| | 02:54 | change the output to "The
answer is" and I'll append result.
| | 02:59 | So now I'm asking the user to enter a
two values both numbers as long as they
| | 03:04 | can be parsed as double values, the
mathematical operation should work.
| | 03:08 | I'll run the application;
| | 03:10 | I'll click into the console and
type in an initial value of 10 and a
| | 03:14 | second value of 25.5.
| | 03:15 | I'm using a fractional value because I
know I cast these values as doubles and
| | 03:21 | they can accept that.
| | 03:22 | I'll press Enter and there is the result,
The answer is 35.5.Now, let's take a
| | 03:28 | look at what happens if the user types
in a non-numeric value, I'll click the
| | 03:32 | Run button again and this
time I'll type in a value of xyz.
| | 03:37 | So far so good nothing bad is happened
and that's because I haven't tried to
| | 03:41 | parse the String as a number yet, I've
just gone to the next line that asks for
| | 03:45 | another String, so I'll type abc, now
when I press Enter the parsing will begin
| | 03:52 | and I'll get an error, because xyz
can't be translated as a numeric value,
| | 03:57 | specifically as a double
value, I get an exception called
| | 04:00 | java.lang.NumberFormatException.
| | 04:03 | Now, I haven't shown you the tools you
need to handle this exception yet, so for
| | 04:07 | now this simple calculative will only
work if the user types in correct values,
| | 04:12 | that is String values that can be
parsed and turned into numbers without
| | 04:17 | creating exceptions, but if the
users does what they are supposed to do
| | 04:20 | directly, then the application will work.
| | 04:22 | In later chapters I'll show you more
about Strings and more specifically about
| | 04:27 | Error Handling, so that you can easily
capture this kind of problem and tell the
| | 04:31 | user what kind of input you need.
| | Collapse this transcript |
|
|
5. Exploring Syntax and FlowWriting conditional code| 00:00 | Java supports a number of constructs
that allow you to easily control the flow
| | 00:05 | of your application.
| | 00:06 | Conditional Blocks, Switch
Statements, Loops, and so on.
| | 00:11 | I'm going to start in this chapter
by showing you how to build a basic
| | 00:14 | conditional statement using the keyword if.
| | 00:17 | I am working in a project named
Conditional that's part of the Chapter 05
| | 00:22 | Exercise Files, but it just has an
empty class with the basic Main method.
| | 00:26 | I'll place the cursor inside the
Main method and I am going to start by
| | 00:30 | declaring an integer variable.
| | 00:32 | I'll give it a data type of int and a
name of monthNumber and I'll set it to a
| | 00:38 | value initially of 3.
| | 00:40 | Now I am going to evaluate that
numeric value and ask the question, does this
| | 00:45 | month number fall in the range of 1 to 3.
| | 00:48 | In Java the conditional
blocks starts with the keyword if.
| | 00:51 | You then place a Boolean condition that
is a condition that evaluates to true or
| | 00:56 | false inside of set of parenthesis, and
then within the pair of braces, you put
| | 01:01 | in the code you want to
execute if the condition is true.
| | 01:05 | Now rather than hand coding all that,
Eclipse will the model the code for you.
| | 01:09 | After typing the word if, without any
spaces after it press Ctrl+Spacebar and
| | 01:15 | you will get a list of available code templates.
| | 01:17 | Choose the first item in the list, if
statement, an Eclipse fills out the rest
| | 01:22 | of the conditional block, the required
parenthesis around the Boolean condition
| | 01:27 | and the braces in which you
will place the executable code.
| | 01:30 | Now the question I want to ask is does
the month number fall between 1 and 3.
| | 01:34 | So I am going to put in
a complex condition here.
| | 01:37 | I'll start off with a Boolean
expression of monthNumber>=1, and then I'll use
| | 01:43 | the double ampersand which is the
conditional end and I'll complete the
| | 01:47 | expression with monthNumber <=3
| | 01:51 | Notice that as I type there is a little
rectangle that's wrapping the condition.
| | 01:56 | When I am done typing in the condition
I can press the tab key and the cursor
| | 02:00 | will drop between the braces and I
can start writing the executable code.
| | 02:05 | Within the if clause,
I'll use System.out.println.
| | 02:10 | and I'll out put the
string "You're in Quarter 1."
| | 02:13 | I'll save the changes and Run the
application and I should see the output
| | 02:18 | "You're in Quarter 1", so it's working.
| | 02:20 | Now once you've used an if clause,
you can also use one or more else-ifs.
| | 02:26 | The structure of else-if is the same as an
if, but it can only follow in an initial if.
| | 02:31 | So I am going to make a copy of this
code block and I'll paste it in to place,
| | 02:36 | and I'll prefix the next one with else.
| | 02:39 | I'll change the numbers that I am
evaluating to 4 and 6 and I'll change the
| | 02:46 | Quarter output to Quarter 2.
| | 02:47 | I'll Run the code again and I am in
still Quarter 1, but then I'll change the
| | 02:53 | month number at the top of the code to
month number 5 and Run it again, and I am
| | 02:58 | told you are in Quarter 2.
| | 03:00 | Now again, you can have as many else-
ifs as you want, and then optionally you
| | 03:04 | can have an else, which is the catcher,
the code that will execute if none of
| | 03:07 | the previous conditions are true.
| | 03:09 | The else looks like this, it doesn't
take any parenthesis or conditions, but it
| | 03:14 | does take its own code block, and here
I'll output of string saying, "You are
| | 03:18 | not in the first half of the year!"
| | 03:19 | Now that code is getting a little wide,
so let me maximize my code editor and we
| | 03:24 | can see all three conditions.
| | 03:26 | One for Quarter 1, one for Quarter 2,
and finally, one for all of the other
| | 03:31 | possible numeric values.
| | 03:33 | I'll Save and Run the application and
I am still in Quarter 2, but now I'll
| | 03:38 | change the monthNumber variable to say
number 8 for August and Run again and I
| | 03:44 | get the output "You're not in
the first half of the year!"
| | 03:47 | So that's basically the
structure of an if statement.
| | 03:49 | Now when you are comparing values and
you are working with primitive data types,
| | 03:53 | you can use these mathematically
quality operators >=, <= and so on.
| | 04:00 | But as I previously described, if you
are working with strings, you have to use
| | 04:05 | methods of the String class to do comparisons.
| | 04:08 | Let's create another class.
| | 04:10 | I'll go to my package explorer to the
default package, I'll right click and
| | 04:15 | create a New class, and
I'll name this CompareStrings.
| | 04:19 | It's going to be its own little application,
so I'll check the main method and click finish.
| | 04:24 | I am going to get ride of all these
extra comments that Eclipse puts in, and now
| | 04:29 | within the Main method I'll declare a
String variable named month and I'll give
| | 04:34 | it an initial value of "February".
| | 04:37 | Now I am going to compare that
string value to another string.
| | 04:41 | So, once again I'll put in an if
clause typing the word if and pressing
| | 04:45 | control space and pressing Enter or
Return and then I'll look for the string
| | 04:49 | February like this.
| | 04:51 | if month.equals("February") then I say,
System.out.println ("It's the second month!").
| | 05:01 | I'll Save and Run this
application and I get the output.
| | 05:04 | The mechanism of comparing values
will shift from one data type to another.
| | 05:09 | For primitive values, you can use
the mathematical equality operators.
| | 05:14 | For Strings you have to use methods of
the String class like equals or contains,
| | 05:18 | but the structure of the if, else-if,
and else statements will stay the same.
| | 05:24 | Regardless of the data type that you are
comparing, you can use the if, else-if,
| | 05:28 | and else clauses to determine whether
you would want to execute particular code,
| | 05:32 | all depending on the current condition.
| | Collapse this transcript |
| Using the switch statement| 00:00 | There are many times in applications
where you have a variable and you want to
| | 00:04 | check that variable
against a set of finite values.
| | 00:08 | You could model this code using an if
statement, and a whole set of else-ifs or
| | 00:12 | you could do it a little
more elegantly with a switch.
| | 00:15 | I'll show you how to use a switch in
Java in this project, Switch, which you can
| | 00:19 | find in Chapter 5 of the Exercise Files.
| | 00:22 | The project has a few different classes,
I'm working with the SwitchWithInts,
| | 00:27 | this application already has the
getInput method that I've used in a previous
| | 00:30 | video, it accepts a value typed in at
the command line and returns a String.
| | 00:35 | I'll start in this application by
receiving a value and converting it to an integer.
| | 00:40 | I'll place the cursor inside the main
method and declare a String named input,
| | 00:45 | then I'll fill in its value by calling
the getInput method, I'll pass a prompt
| | 00:50 | into the getInput method of
Enter a number between 1 and 12:
| | 00:56 | Next I'll convert the String to an
integer, I'll declare an int variable called
| | 01:01 | month and I'll convert it using the
Integer class's parseInt (input) method,
| | 01:06 | I'll pass in the input, and now I
should have an integer to work with.
| | 01:12 | Now, I'm doing this because in Java
up through version 6.0 you can use the
| | 01:18 | switch statement only with integers, shorts,
bytes, and a special class called Enums.
| | 01:24 | In Java 7.0 you can actually use
switches with strings, but I have my copy
| | 01:28 | of Eclipse setup on Java 6.0 right now, so
I'll stick with what works with that version.
| | 01:34 | The next step is to create the
structure of a switch statement, just as with if
| | 01:39 | statement Eclipse will help you, type
the word switch and press Ctrl+Space and
| | 01:44 | then press Enter or Return to choose the
first item in the list and that creates
| | 01:48 | the basic structure.
| | 01:49 | The switch syntax looks like this, after
the keyword switch you put in a pair of
| | 01:53 | parenthesis and then you pass in
the variable that you're evaluating.
| | 01:58 | I'm evaluating the variable month.
| | 02:00 | Next you have one or more case
statements, each case statement takes a value,
| | 02:06 | the value must be an integer or an
enumeration or Enum, I'll describe those
| | 02:10 | later, but for now, I'm going
to use the literal value of 1.
| | 02:15 | Then after the case statement, but
before the word break, you put in your
| | 02:19 | executable code, this code will only
execute if the value in the case statement
| | 02:24 | matches the variable in the switch command.
| | 02:27 | I'll output a bit of text System.out.println,
and I will output ("The month is January");
| | 02:35 | so I making an equivalence between
the number 1 and the month January.
| | 02:39 | Now, I'm going to copy and paste this
case statement, including the three lines
| | 02:43 | from case to break, I'll copy and then
paste twice, close up the code a bit,
| | 02:48 | I'll change the values I'm
evaluating to 2 and 3, and I'll change their
| | 02:53 | equivalent months to February and March.
| | 02:57 | So my application is now at a
point where it should work correctly.
| | 03:01 | I'll run the application, in the
console view I'll click in and then type the
| | 03:06 | number 1, and I get the month as January.
| | 03:08 | I'll run it again and type in 2 pressing
Enter or Return and I get the month as February.
| | 03:15 | And finally, I'll test a value that's
not one of those numbers like 6, and press
| | 03:21 | Enter or Return and nothing happens.
| | 03:23 | Well, that's because I haven't
filled in this bit of code, the default.
| | 03:28 | The keyword default means execute this
code if none of the previous cases return
| | 03:34 | true, so here I'll put in System.out.
println and then I'll output the String
| | 03:40 | ("You chose another month").
| | 03:43 | I'll Run and once again I'll type in 6,
and this time I get the default behavior.
| | 03:50 | So that's the basic of a switch statement.
| | 03:53 | Let's also talk about the break keyword.
| | 03:55 | The break keyword is used to
breakout of a code block in Java.
| | 04:00 | Right now our code block is everything
from this opening brace to this closing brace.
| | 04:05 | When you say break, it means
jump to the end of the code block.
| | 04:08 | You need break statement in cases,
because if you don't have them, the code will
| | 04:13 | just keep executing throughout
the rest of the switch statement.
| | 04:16 | I'm going to comment out each of these
break statements, so you can see the behavior.
| | 04:20 | I'll place the cursor on the line and
then press Ctrl+/ on Windows or Command+/
| | 04:25 | on Mac, and that will add double
slash comments to each of these lines.
| | 04:29 | Now I'll Save my changes, Run the
application, and I'll type the number 2 and I
| | 04:35 | get not just the month as February,
but I also get all of the other code
| | 04:39 | executing for the rest of the switch statement.
| | 04:42 | This code model works the same as it does in
JavaScript, C++, and other C-Style languages.
| | 04:48 | The rules are straight forward as soon
as you get a match between the variable
| | 04:53 | and the value in a case statement the
code will start executing and it would
| | 04:56 | keep executing for the rest of the code block.
| | 04:59 | If you don't want that to happen, and
you really never do, then you have to put
| | 05:03 | those break statements into each case.
| | 05:06 | So I'm going to get rid of those
comments, all I need to do is move the
| | 05:09 | cursor to each line and press Ctrl+/ or Command
+/ and now the code is back in its working state.
| | 05:16 | In Java, through version 6.0, you can
use switch statement for integers or for a
| | 05:22 | special class called Enums, and again,
as I mentioned before, in Java 7.0 you
| | 05:26 | can use switch statements on Strings,
but I'm working in Java 6.0 here, so I'm
| | 05:30 | going to stick to integers and Enums.
| | 05:33 | Let's take a look at how Enums work.
| | 05:35 | An Enum is short for Enumeration,
it's a way of providing a set of possible
| | 05:42 | values, in older version of the Java,
previous to version 5.0, you had to create
| | 05:47 | your own enumerations using a
particular code model, but now they're native to
| | 05:51 | language and have been for
the last couple of versions.
| | 05:54 | Here is how you create enumeration.
| | 05:56 | I'll go to my default package in
the project and choose New Enum.
| | 06:00 | An Enum is a kind of a class, so you
have a very similar wizard as for a new
| | 06:07 | class, but without all the options.
| | 06:10 | I'll give this Enum a type of Month,
I won't use a package I'll just ignore
| | 06:15 | that warning that the use of the default
package is discouraged, and I'll click Finish.
| | 06:20 | Now within the Enum I'm going to type
in the names of the constants that I want
| | 06:25 | to use, JANUARY, FEBRUARY, MARCH,
notice that after I saved the file Eclipse
| | 06:32 | automatically evaluates and
recognizes that those are constants of the Enum
| | 06:36 | class and it color codes them appropriately.
| | 06:39 | Now I'll switch to the application
SwitchWithEnums.java, this is a shortened
| | 06:44 | version of that previous application;
| | 06:46 | it has an integer variable with the value of 1.
| | 06:49 | I'm going to copy out that version
of the month declaration and I'm going
| | 06:53 | to change it to an instance of the month
class or a month Enum that looks like this.
| | 06:58 | When I type in Month.Eclipse gives me
a listing of the possible values and
| | 07:04 | you'll see that the values that I put
into the Enum class, JANUARY, FEBRUARY,
| | 07:08 | and MARCH, are proposed.
| | 07:10 | I'll choose FEBRUARY.
| | 07:12 | Now I'm going to change my switch
statement a bit, the switch statement itself
| | 07:15 | stays the same, because I reused the
variable name month, but now, instead of
| | 07:20 | evaluating integers, I'm evaluating
constants of the Enum, and it will look like
| | 07:24 | this, case JANUARY, notice that within
the switch statement I don't have to use
| | 07:29 | the month dot prefix and I'll change
the string from the month as JANUARY to
| | 07:34 | ("It's the first month").
| | 07:35 | I'll change 2 to FEBRUARY and I'm just
pressing Ctrl+Space to auto fill that
| | 07:41 | value and I'll change this String to (
It's the second month) and I'll change 3
| | 07:46 | to MARCH and the output
String to ("It's the third month").
| | 07:50 | The advantage of using an enumeration
is that you can explicitly say these are
| | 07:55 | the only possible values, when you
say something as an integer, you're not
| | 07:59 | limiting yourself to 1 through 12, you
have literally millions of possibilities.
| | 08:04 | The advantage of the Enum is that
you're limiting the possibilities, and making
| | 08:07 | it very clear what's possible in this situation.
| | 08:09 | So now I'll Run the application
and I get (It's the second month).
| | 08:14 | I'll talk more about enumeration at a
later point of the course, but you can see
| | 08:18 | how useful they might be for
various situations in your applications.
| | 08:21 | Finally, I'll show you what the code
would look like if Strings were supported
| | 08:25 | in the switch statement.
| | 08:27 | As I've mentioned, I can't do this
right now, because I'm working in Java 6.0,
| | 08:31 | but if you're working in Java 7.0, one
of the improvements to the language is
| | 08:35 | the ability to use Strings in switch statement,
and this is what the code would look like.
| | 08:39 | The purpose of switch statement is to
make conditional logic a little more
| | 08:43 | elegant and to prevent the need from
multiple else-if statements that make the
| | 08:48 | code harder to read.
| | Collapse this transcript |
| Repeating code blocks with loops| 00:00 | The Java language includes a number
of syntax styles that allow you to loop
| | 00:04 | through the contents of arrays
and other types of data collections.
| | 00:09 | I'll demonstrate four approaches to
looping in this project named Loops.
| | 00:13 | The main class in this project has a set
of code that's commented out currently,
| | 00:17 | it declares a static variable,
an array of strings called months.
| | 00:22 | I'm going to loop through this data and
output these strings a number of times
| | 00:25 | using a different syntax style each time.
| | 00:28 | I'll start by uncommenting this code.
| | 00:31 | I'll select the commented code and then
press Ctrl+/ on Windows or Command+/ on
| | 00:36 | Mac and that removes the double slash
comments at the beginnings of the lines.
| | 00:40 | Then I'll place the
cursor inside the main method.
| | 00:43 | The first type of loop I'll show
you uses a numeric counter variable.
| | 00:48 | It's a conventional for loop and the
syntax looks exactly the same as it would
| | 00:52 | in JavaScript and other similar languages.
| | 00:56 | I'll start by typing in the word
for, and then pressing Ctrl+Space.
| | 01:01 | Eclipse gives me a number of
choices and I'll choose the first one, for
| | 01:05 | iterate over array.
| | 01:07 | This sort of loop uses a temporary
variable, sometimes called a counter variable.
| | 01:13 | When you generate the code using
Eclipse, it will name the variable i for
| | 01:17 | integer and it will datatype it as an int.
| | 01:20 | Now if you're doing with a fairly
small amount of data, you could change the
| | 01:24 | data type to a short or even a byte,
but typically ints are used in this case.
| | 01:29 | When you're looping through an array,
you should set the initial value of the
| | 01:32 | counter variable i as 0.
| | 01:34 | This is because in Java arrays are 0-based.
| | 01:38 | The first item is item 0.
| | 01:40 | The second is item 1 and so on.
| | 01:42 | Then in order to make sure that you hit
every item in the array, you add a comparison.
| | 01:48 | You look at the counter variable I,
and you compare it to the length of the
| | 01:53 | array, as long as i is less than the length,
you'll execute any code within the for-loop.
| | 01:58 | But when i matches or exceeds the length,
you'll stop, and again, that's because
| | 02:03 | of the 0-based array.
| | 02:06 | Say you have an array of 10 items, if
the length is 10 and i starts at 0, then
| | 02:11 | you can keep executing code
as long as i is less than 10.
| | 02:15 | When it actually is 10, it's
exceeded the available items in the array.
| | 02:19 | The third part of the for
construct is the increment.
| | 02:23 | Most commonly, you'll see this, i++,
meaning, increment the value by 1, but you
| | 02:28 | can put in any operation you want here.
| | 02:30 | You could use i--, you could say i+ = 5 and
then you would be stepping by 5, and so on.
| | 02:37 | So now I'll place the cursor inside the
for-loop, and put in System.out.println
| | 02:43 | and I'm ready to output something.
| | 02:45 | Now when Eclipse generated the code,
it thought I might want to output the
| | 02:49 | values from args, but instead I'm
going to output the values for months and
| | 02:54 | that's the array that I declared at the top.
| | 02:56 | And in the print line command I'll output months,
open bracket, i, closed bracket, and now I'm going to be
| | 03:03 | outputting the string at
that position of the array.
| | 03:06 | I'll Save and Run the
code and there is the result.
| | 03:10 | Now to make this a little bit easier
to see, I'm going to detach the console
| | 03:13 | right-click and choose Detached, move
it up onto the screen and expand it, and
| | 03:17 | now I have a lot more room to
see the output from my application.
| | 03:21 | So that's a for loop with the counter variable.
| | 03:23 | Here's another approach to using a for loop.
| | 03:26 | This is called a for-each, but
unlike some C Style languages, you don't
| | 03:30 | actually use the word each.
| | 03:32 | Here is how it actually looks.
| | 03:34 | Once again I'll type in the word for,
and press Ctrl+Space and I'll for-each
| | 03:39 | from the list of choices and
here's how Eclipse models it.
| | 03:42 | Within the for-loop it declares a
variable by default of type string, and
| | 03:47 | it gives it a name.
| | 03:48 | I'm going to change the name from string
to month and then it asks what array or
| | 03:53 | collection you want to loop through.
| | 03:55 | I'm going to be looping through months.
| | 03:57 | So in English this would be read as,
for-each month in the month's array, but
| | 04:03 | you declared in Java using a data type
variable before the colon and the array
| | 04:08 | or collection you are
looping through after the colon.
| | 04:11 | Now I can refer directly to the variable month.
| | 04:14 | So I am going to go make a copy of
this code, System.out.println, I'll paste
| | 04:19 | it in, but now I don't need refer to
the collection anymore, I'm already doing
| | 04:23 | the iteration, I'll just refer to the
variable that's created temporarily each
| | 04:27 | time through the loop.
| | 04:28 | I'll go up to my original for loop and
comment it out and I'll Save and Run the
| | 04:33 | application, and once again there is my output.
| | 04:37 | In most cases with the arrays, you
can use either of these two approaches.
| | 04:41 | The only real advantage to using the
counter variable, as opposed to the
| | 04:45 | for-each syntax is that you're
creating new counter variables, rather
| | 04:49 | than complex objects.
| | 04:51 | Whereas, with the for-each,
particularly with the strings and other complex
| | 04:54 | objects, you are creating a new
object on each time through the loop.
| | 04:57 | In most environments it really won't
matter, and you should use the syntax that
| | 05:01 | you're most comfortable with.
| | 05:04 | I'll comment this version out, and
now we'll move to the while loop.
| | 05:08 | There are two forms of the while
loop, the while loop where you put the
| | 05:12 | condition at the front and the while loop
where you put the condition at the back.
| | 05:15 | Before you create a while loop, you
should declare a variable and give it an
| | 05:20 | initial value, unlike the for-construct,
the while construct does not do the
| | 05:25 | variable tracking for you.
| | 05:26 | So I'll create a variable called
counter, and set it to a value of 0.
| | 05:31 | Now I'll type in the word of while and
I'll press Ctrl+Space and I'll choose
| | 05:36 | while loop with condition.
| | 05:38 | The while loop with condition takes a
look at a Boolean expression and asks
| | 05:43 | should I keep on looping?
| | 05:44 | I'm going to set my condition as counter
<months.length, and then I'll move the
| | 05:49 | cursor into the while loop, I'll paste
in that code, and I'll change the name of
| | 05:54 | the variable I'm looking at from I, to
counter, because that's what I declared
| | 05:58 | it as earlier, but again, the while loop
isn't going to increment that value for
| | 06:03 | me, I have to do it myself.
| | 06:06 | So I'll place the cursor after the
print line command and increment the
| | 06:10 | value with counter++;
| | 06:12 | I'll save and run the code.
| | 06:14 | And once again it does exactly the
same thing as the for-loops, but with a
| | 06:18 | slightly different syntax.
| | 06:20 | Finally, there is the do-while loop.
| | 06:22 | For the do-while loop you place
the condition at the end of the loop.
| | 06:26 | I'm going to make a copy of this code
and I'll paste it down at the bottom.
| | 06:32 | I'll comment out the original
and now let's create a do-loop.
| | 06:36 | I'll take this while command and
I'll move it after the code block.
| | 06:40 | Then I'll the place the cursor at the
beginning of the code block and put in the
| | 06:44 | word do, and after the while
command, I'll finish with a semicolon.
| | 06:49 | So now I'm saying start by outputting
the value and then increment the value and
| | 06:55 | then do the evaluation rather than
doing the evaluation at the beginning.
| | 06:59 | Take a look at what happens.
| | 07:01 | It still works exactly the same.
| | 07:03 | So these are the four possible
syntax styles that you can use for looping
| | 07:07 | through arrays and other collections.
| | 07:10 | You can use the counter for loops, you
can use for-each syntax, you can use a
| | 07:14 | simple while-loop or you
can use a do-while loop.
| | 07:19 | In many cases it's just a matter of
program or preference, which syntax you
| | 07:23 | like, or are most comfortable with.
| | 07:25 | You will find that there are
differences in what problems you can solve between
| | 07:29 | say a while and do-while, but
for the most part it's your choice.
| | Collapse this transcript |
| Creating reusable code with methods| 00:00 | Nearly all programming languages
support the concept of a function.
| | 00:04 | A function is a set of code that's
wrapped up and then given a name, so that it
| | 00:08 | can be called easily from
other parts of the application.
| | 00:11 | In Java, we have special name
for a function called a method.
| | 00:15 | The term method comes from object-
oriented vocabulary and refers to a function
| | 00:20 | that's a member of a class.
| | 00:22 | There are some programming languages in
which you can create global functions.
| | 00:26 | Functions that are available to the
entire execution environment without having
| | 00:29 | to say where they come from.
| | 00:31 | That's not the case in Java.
| | 00:33 | In Java, every function is a member of a
class, and so we always use the term method.
| | 00:39 | I have described the use of the main method
in applications that run from the console.
| | 00:44 | As you start up an application from the
command line, the Java Virtual Machine
| | 00:47 | looks for a method called main, which
has these characteristics, public, static,
| | 00:53 | and void, and accepts an
argument that's an array of strings.
| | 00:57 | You can create as many of your own
custom methods as you want to, but again,
| | 01:01 | every method must be defined within a class.
| | 01:05 | I am going to define my own custom
method and describe each part of the
| | 01:08 | declaration as I go along.
| | 01:09 | When you declare a method, the first
thing you typically provide is called
| | 01:13 | the access modifier.
| | 01:15 | You can use one of three terms,
public, private, or protected.
| | 01:19 | Public means that the method is
available to the entire application or at least
| | 01:23 | to any part of the application
that can see the class itself.
| | 01:26 | So if the class is public and the method is
public, then it can be called from anywhere.
| | 01:30 | Private is the opposite.
| | 01:32 | The method is only
available to code within this class.
| | 01:36 | Protected has to do with inheritance.
| | 01:38 | A protected method is available to the
current class and to any of its sub classes.
| | 01:42 | And there is one other kind of access,
which happens when you don't declare an
| | 01:46 | access modifier at all.
| | 01:47 | It is sometimes called protected
package, and it means that a method is
| | 01:52 | available to the current class and to
any other classes in the same package
| | 01:56 | or group of classes.
| | 01:58 | I recommend always setting access
modifiers though, because it makes your
| | 02:01 | code easier to read.
| | 02:03 | The next characteristic of a
method is whether it's static or not.
| | 02:07 | If you want the method to be
static, you put in the word static.
| | 02:10 | And if you don't, you don't.
| | 02:11 | When do you want a method to be static?
| | 02:13 | Well, the term static means that the
method is something we call a class method,
| | 02:17 | as opposed to an instance method.
| | 02:19 | A class method is called directly from
the class definition, whereas an instance
| | 02:24 | method is called from an
instance of the class or an object.
| | 02:27 | If you are not sure whether to make a
method static or not, try not putting in,
| | 02:32 | and see if you can call the method.
| | 02:33 | For example, in order to call a method
from the main method, which is static,
| | 02:37 | the called method must be static as well.
| | 02:40 | Static methods can call static methods,
instance methods can call instance
| | 02:43 | methods, without having a
say where they are coming from.
| | 02:46 | But for a static method to call a
non static method, it must create an
| | 02:50 | instance of the object.
| | 02:51 | I want to call this method every easily,
so I'll make it static and then I'll be
| | 02:55 | able to call it from the static main method.
| | 02:57 | Next, you declare the return type.
| | 03:00 | The term void means I am not returning anything.
| | 03:03 | Unlike some languages, Java
requires a declared return type.
| | 03:08 | Now you type in the name of
the method you want to create.
| | 03:10 | I'll name my method doSomething, it's
important to follow the right conventions
| | 03:14 | when you name your methods and variables.
| | 03:16 | You follow the same convention as for variables.
| | 03:19 | The initial character must be
lowercase or other java developers will think
| | 03:23 | you don't know what you are doing, and it
must be an alphabetical character, not numeric.
| | 03:27 | You can also use underscores,
but that's fairly in frequent.
| | 03:30 | The rest of the method name can use
camel case, such as I am doing here which
| | 03:34 | means using uppercase characters
to make the string more readable.
| | 03:37 | At the end of the method name you
always add opening and closing parenthesis.
| | 03:41 | This is where you would declare arguments
that can passed into the function or method.
| | 03:46 | After the parenthesis,
you add up pair of braces.
| | 03:48 | In Eclipse, if you type in the
opening brace and press Enter or Return, the
| | 03:52 | closing brace will be created for you.
| | 03:55 | Now I've declared this method as
void, meaning I am not going to return
| | 03:58 | anything, but I can do something within
the method, and I'll output something to
| | 04:02 | the console saying ("This
method has been called.")
| | 04:07 | Now I'll go to the main method
and I'll call the new custom method.
| | 04:10 | I'll type do and then press Ctrl+Space to see
what's available and there is my new method.
| | 04:16 | Eclipse is constantly scanning your
code to determine what's available to the
| | 04:20 | code and if it can't call a particular
method, say because you are in a static
| | 04:24 | context and the method you are trying
to call isn't static, it won't show it in
| | 04:27 | the list of choices.
| | 04:29 | I'll press Enter or Return to choose
the method and add the semicolon at the
| | 04:32 | end of the statement, and I'll Save and
Run the application, and there is the output.
| | 04:37 | Now it's very common to create a bunch
of code in a general context and then
| | 04:42 | want to be able to wrap that up and
turn it into its own method later on.
| | 04:45 | We call this sort of changed to your code,
refactoring, and it is something that
| | 04:49 | Eclipse can help you with.
| | 04:51 | I am going to create a little bit of code here.
| | 04:53 | I'll create an int variable called top and
give it a value of 10, and then I'll add for-loop.
| | 04:58 | I'll type '-for, press Ctrl+Space and then
Enter or Return to iterate over the array.
| | 05:04 | I'll press tab and I'll change the
value that I am iterating on from
| | 05:08 | args.length to top and then within the
for-loop output System.out.println, and
| | 05:16 | then the value is, and then I'll
append i. I'll Save and Run the application
| | 05:22 | and there is my finished code.
| | 05:24 | Okay, let's take this code and
wrap it up in its own method.
| | 05:28 | I am going to select the code that I
want to put in to its own method, and then
| | 05:31 | I'll go to the menu and
choose Refractor>Extract Method.
| | 05:36 | The Extract Method dialog asks me
what I'd like to name this new method and
| | 05:39 | I'll call it loopMe.
| | 05:41 | It will propose what we call a method signature.
| | 05:44 | The combination of the characteristics
private, static and void, and the method name.
| | 05:50 | I can change my access modifier up here
or I can accept the proposal of private.
| | 05:55 | I'll accept the proposal.
| | 05:57 | I'll click OK and Eclipse takes all
of that code and moves it off into its
| | 06:01 | own separate method.
| | 06:03 | It also adds a call to the method right here.
| | 06:06 | So I'll Save the changes and Run the
application again, and I'll see that the
| | 06:10 | application is doing exactly the same
thing as before, but now I have wrapped
| | 06:15 | up all that custom code into its own method,
so it can be called many times in the future.
| | 06:20 | So that's a look at the
basic of creating methods.
| | 06:22 | Now in future videos I'll show you how
to create methods that accept arguments
| | 06:27 | or parameters and also methods
that know how to return values.
| | Collapse this transcript |
| Declaring methods with arguments| 00:00 | When you declare own custom methods in
your Java code, you can declare them with
| | 00:05 | arguments, parameters, or values that
they can receive and these methods can
| | 00:09 | return values as well.
| | 00:11 | I am starting in a version of my
calculator application that's in a project
| | 00:15 | called MethodWithArgs.
| | 00:17 | This application already has a custom
method that I previously used in other exercises.
| | 00:22 | The name of the method is getInput.
| | 00:25 | It's designed to receive a single
argument, a string with a name of prompt and
| | 00:30 | it's designed to return a string as well.
| | 00:32 | All of the complex code is
encapsulated within the method.
| | 00:36 | So, when I call the method, all I need
to do is pass the name and a value that I
| | 00:41 | want to display on the screen, the prompt.
| | 00:43 | Now you can create your own custom
methods incredibly easily in Eclipse.
| | 00:47 | Let's say that you have some custom
code and it's either 3 line or 10 lines or
| | 00:51 | 100 lines of code, and you want to
take that code out of the main method and
| | 00:55 | make it its own custom method.
| | 00:57 | Eclipse calls this extracting a
method and here is how you do it.
| | 01:01 | I am going to take these three lines of
code, I am declaring two double values
| | 01:05 | that are being parsed from strings.
| | 01:07 | And then I am adding the two values together.
| | 01:10 | I would like to take this bit of
code and make it its own method.
| | 01:13 | So I'll select those three lines of code and
then I'll right click in the selected area.
| | 01:18 | I'll choose Refactor, Extract Method.
| | 01:21 | Eclipse asks for the new Method
name, I'll call it addTwoValues.
| | 01:26 | Notice the parameters are set as Strings,
that's correct, and also, Eclipse is
| | 01:31 | smart enough to know that if my final
statement is doing a calculation, then I'm
| | 01:35 | probably going to want to
return that value from the method.
| | 01:39 | So it says, I'm going to return a
double value, I'll click OK and Eclipse
| | 01:44 | refactors the code for me.
| | 01:45 | The new code is a single line that
says create a double value named result,
| | 01:50 | which is calculated by calling the
new addTwoValues method and it's passing
| | 01:54 | in the two strings.
| | 01:56 | And here is the new method, it's
declared as private, static, and double,
| | 02:00 | because it's private and static, it can
be called from within the Main method,
| | 02:04 | and because it declares double as the
return type, it knows that it's going to
| | 02:07 | return that calculated value.
| | 02:09 | Here is all the code that I extracted, and
here is the code that returns the result.
| | 02:14 | The keyword return means here is the
value that I'm returning from this method
| | 02:18 | and the data that you pass back must
match the data type that you declare here.
| | 02:23 | I'll Save my changes and Run the
application, I'm asked for my values and I'll
| | 02:27 | type in 5 and 10 and I get back 15.
| | 02:31 | So I know that the code is working.
| | 02:33 | It's also possible to declare
methods that receive variable numbers of
| | 02:37 | arguments, as long as all those
arguments are of the same data type.
| | 02:41 | Here is an example, I moved down to
the bottom of the application and I'll
| | 02:45 | create a new private static method and
I'm going to set the return data type as
| | 02:49 | double, just as before.
| | 02:51 | I'm going to call this
method though addMultipleValues.
| | 02:55 | I'll start with no arguments, but then
I'm going to place the cursor inside the
| | 02:59 | parentheses and I'm going to tell Java,
you can accept any number of arguments
| | 03:04 | as long as they're all doubles, that
is, as long as they are all numeric
| | 03:08 | primitives they can be translated as double.
| | 03:10 | Here is the syntax:
| | 03:12 | double space dot, dot, dot
space, and then the variable name.
| | 03:16 | The data type works as it does for all
arguments, but the dot, dot, dot means
| | 03:21 | treat this value as an array.
| | 03:23 | Right now, I'm seeing a little bit of
error information and that's because I
| | 03:27 | haven't returned a value yet.
| | 03:29 | So now I just need to fill in
the implementation of the method.
| | 03:32 | I'll expand the editor so we can see
more of the code, and within the method I'm
| | 03:36 | going to start by declaring a double
value of result and set it as 0d, meaning
| | 03:42 | the double version of zero.
| | 03:44 | Now I'm going to loop through those
values, because of the dot, dot, dot in the
| | 03:48 | middle of the declaration, values is
passed in as an array, and I'll loop
| | 03:52 | through using a for-loop, I'll type for
press Ctrl+Space and I'll use a for-each loop.
| | 03:58 | Eclipse tells me it's going to
create a new double value named d, each
| | 04:02 | time through the loop, and this is the
collection or array it's looping through, values.
| | 04:07 | Within the loop I'll add the value to
the result using the += operator result +=
| | 04:13 | d and finally after the
loop I'll return the result.
| | 04:19 | So, there is my completed method
accepting variable numbers of double values.
| | 04:23 | I'll go back to the top to the Main
method, and I'm going to add a little bit
| | 04:28 | of code down here, I'll say double
resultOfMultiple = addMultiple and I'll pass in 1, 2, 3, 4, 5.
| | 04:39 | And again, I can pass in as many
values as I want, as long as they can all be
| | 04:43 | easily converted into double values.
| | 04:45 | Then I'll output the result saying ("
The answer from multiple values is")
| | 04:50 | and then the answer.
| | 04:54 | I'll run the application I still have
to go through the inputs for the original
| | 04:58 | calculation, but then I get the
answer from the multiple values also.
| | 05:02 | Now it just so happens that I got back
the same values, so let's try running
| | 05:06 | the application again.
| | 05:08 | This time I'll add 5 and 5 together and
I get back 10 for the first answer, but
| | 05:13 | 15 for the second, because that's the
result of 1+2+3+4+5.So this is how you
| | 05:19 | declare your own methods with arguments.
| | 05:22 | Java requires arguments to be
declared if you haven't declared them you
| | 05:26 | can't pass them in and if you do declare
them you have to pass them in, it's very strict.
| | 05:31 | But you do have the option of using
the variable argument syntax to allow
| | 05:36 | yourself to pass in multiple
arguments as long as they all follow the same data type.
| | Collapse this transcript |
| Overloading method names with different signatures| 00:01 | The Java programming language allows
you to create methods that share the same
| | 00:05 | name, but have different signatures.
| | 00:07 | A method signature is the unique
combination of keywords and arguments that
| | 00:13 | the method receives.
| | 00:14 | For example, the standard main method
receives an argument which is an array of strings.
| | 00:19 | You can create your own custom methods
in your class and where necessary, you
| | 00:23 | can create multiple methods that
share the same name as long as they have
| | 00:27 | different signatures.
| | 00:28 | The Java Virtual Machine determines
at runtime which version of a method it
| | 00:32 | should run, depending on
what arguments are passed to it.
| | 00:35 | Let's create a few very simple methods.
| | 00:38 | I'm working in a beginning main
class in the project MethodOverloading.
| | 00:42 | I'll place the cursor after the static
void main method and I'll create a new
| | 00:47 | method using private static, I'll set
the methods return value to int and I'll
| | 00:53 | name the method addValues.
| | 00:55 | For this first version of the method
I'll receive two arguments, and they'll
| | 00:59 | both be data typed as integers.
| | 01:01 | I'll name the first one int1,
and the second one int2.
| | 01:06 | The body of the method will add up
these two values and return the result.
| | 01:10 | I'll do it on a single statement.
| | 01:12 | return int1 + int2.
| | 01:16 | In the main method I'll
declare two starting variables;
| | 01:18 | I'll declare them both as integers.
| | 01:21 | I'll name the first one value1
and I'll set it to a value of 5.
| | 01:25 | And I'll create the second one as
value2 and set it to a value of 10.
| | 01:29 | I'll declare an integer result
variable and get its value from addValues and
| | 01:35 | I'll pass in value1 and value2
and I'll output the result using
| | 01:39 | System.out.println, (The result is"
and then + result) I'll Save and Run the
| | 01:49 | application and everything
is fine. The result is 15.
| | 01:53 | Now I'm going to add two more versions
of this method, I'll copy the existing
| | 01:58 | version and I'll paste it in, making
sure I do this inside the body of the class
| | 02:02 | and notice right now that I'm getting
warnings that I have duplicate methods.
| | 02:06 | The reason they are duplicate is not
just because of the name, but also because
| | 02:10 | they receive the same number
and data types of arguments.
| | 02:13 | So unlike other languages like
JavaScript or ActionScript, I don't need to
| | 02:17 | rename the second version of the method.
| | 02:20 | I can just change the method signature.
| | 02:21 | I have this method receive a third argument.
| | 02:25 | The data type again will be int and the
name will be int3, and I'll change the
| | 02:29 | return statement to add that variable as well.
| | 02:32 | As soon as I make the
change, all the errors go away.
| | 02:34 | I'm still left with a warning that I have
a method that's not currently being called.
| | 02:39 | But I'll fix that.
| | 02:40 | I'll go back to my main method and
create a third value and I'll set it to 15
| | 02:45 | and then I'll change the way I'm
calling the method and I'll pass in value3.
| | 02:49 | I'll Save the change and Run the
application and now I get the result as 30.
| | 02:54 | Clearly I'm now running the second
version of the method, so you can have
| | 02:58 | more than one method of the same name as long
as they have different numbers of arguments.
| | 03:02 | But you can also distinguish methods from
each other by the data types of the arguments.
| | 03:07 | I'll create one more
version of the add values method.
| | 03:10 | My code is getting a little longer now,
so I'll maximize my editor and move the
| | 03:14 | cursor under all the other methods and
I'll create another private, static and
| | 03:19 | returns an int, and once again
it will have the name addValues.
| | 03:22 | This version of the method will have
two arguments but they'll both be strings,
| | 03:27 | and I'll call them val1 and val2.
| | 03:30 | Now in order to add these values
together I need to convert them to integers, so
| | 03:34 | within the method I'll
declare two integer variables.
| | 03:37 | The first one will be called
value1 and I'll set its value using
| | 03:41 | integer.parseInt, and I'll pass in val1,
and then I'll make a copy of that line,
| | 03:47 | I'll change the second version to
create a variable called value2, and it will
| | 03:51 | get its value from val2, and then
I'll do a return statement and I'll add
| | 03:56 | together value1 and value2.
| | 03:59 | So now I have three versions of the
method, addValues with 2 integers, addValues
| | 04:04 | with 3 integers and addValues with two strings.
| | 04:07 | I'll go back up to the code and I'll
create a couple of new variables, the first
| | 04:11 | one will be a string and it will be
named string1, and I'll give it a value of
| | 04:16 | 10, but because it's a string it
has to wrapped in double quotes.
| | 04:20 | I'll set string2 to a value of 25, then
I'll create a variable called result2,
| | 04:27 | and I'll get its values
from the addValues method.
| | 04:30 | And notice when I press Ctrl+Space
Eclipse shows me all the different versions
| | 04:34 | of the method that are available.
| | 04:36 | The version with the two integers, the
version with two strings and the version
| | 04:40 | with the three ints, I'll choose
the version with the two strings.
| | 04:44 | and I'll pass in string1 and string2.
| | 04:48 | I'll make a copy of my println command
and paste it down here, and I'll output
| | 04:54 | the value of result2.
| | 04:56 | I'll run the application and the second
version is clearly calling the version
| | 05:00 | that receives the strings.
| | 05:02 | So this sort of coding is
called method overloading.
| | 05:05 | When you overload a method, you are
reusing the same method name, but you're
| | 05:09 | creating alternative signatures.
| | 05:11 | This is a good coding strategy in
Java to handle situations where in one
| | 05:15 | circumstance you have a certain set of
variables, in another circumstance you
| | 05:18 | got another set and where the
data types can differ as well.
| | 05:22 | By simply reusing the method names,
but having distinct method signatures, it
| | 05:27 | makes your coding much more flexible.
| | 05:29 | And again, this is something that Java does
that other languages in the C family might not.
| | 05:34 | JavaScript and ActionScript for
example, don't allow method overloading.
| | 05:38 | In those languages each method name
can only be used once, they have other
| | 05:42 | strategies such as the ability to
receive variable numbers of parameters in a
| | 05:47 | method, but this capability of Java can
be valuable to your application design.
| | Collapse this transcript |
| Passing arguments by reference or by value| 00:00 | One of the questions you have to
answer when you learn a new programming
| | 00:03 | language is whether arguments passed into
function are being passed by copy or by reference?
| | 00:10 | Let's define these terms, when you pass
arguments by copy that means that you're
| | 00:15 | passing a variable in as an
argument to the function or method.
| | 00:19 | And within the function there is a new
copy of that value, that is the value
| | 00:23 | outside the function and the value
inside the function are separated and any
| | 00:27 | changes you make inside the function,
won't be reflected in the original value.
| | 00:32 | When you pass by reference, the
variable outside the function and the variable
| | 00:36 | inside the function are the same
variable, and any changes that you make
| | 00:40 | inside the function would be
reflected in the original value, once the
| | 00:44 | function is completed.
| | 00:46 | In Java you always are
passing arguments by copy;
| | 00:49 | that is you're always creating a new
instance of the value inside the function.
| | 00:53 | But there are certain behaviors that can
make you think you're passing by reference.
| | 00:57 | I'm going to show you three scenarios
and explain how each of them proves the
| | 01:01 | point that arguments are passed by copy.
| | 01:04 | Let's take the simplest
scenario, passing primitive values.
| | 01:07 | When you pass a primitive value into a
function, a copy of the original value is
| | 01:12 | made and any changes inside the
function won't be reflected in the original.
| | 01:16 | Here is a bit of code, a function named
incrementValue, it receives an argument
| | 01:21 | data typed as an int, within the
function it increments the value by 1 and
| | 01:25 | outputs the new value.
| | 01:27 | Now when I call the function I am
starting off with an original value, an int of
| | 01:31 | 10, and outputting that value and
that will clearly output the value of 10.
| | 01:36 | Then I call increment value and that
will obviously output a value of 11, but
| | 01:41 | what will be the final line of code output?
| | 01:43 | Will it be 10 or 11?
| | 01:45 | Well, because we are making a copy
inside the function and not referencing the
| | 01:48 | original, you'll see a
value of 10 in the final output.
| | 01:52 | That is to say the
original value did not change.
| | 01:56 | With primitives it's very easy to see
that you're passing parameters by copy.
| | 02:01 | Now you'll hear some Java
developers say that when you pass primitives,
| | 02:05 | you're making copies, but when you
pass complex objects, you're actually
| | 02:09 | passing by reference.
| | 02:11 | That's not the case.
| | 02:12 | You're still passing by copy, but
references to values inside the complex object
| | 02:17 | are parts of both versions of the
variable, both the original and the version
| | 02:21 | inside the function.
| | 02:23 | Let's take look at an example using an array.
| | 02:26 | In this version of the increment value
function, I'm receiving an array of integer values.
| | 02:31 | Within the function I'm incrementing
the first item in the array by 1 and then
| | 02:36 | I'm outputting that value.
| | 02:37 | In the calling code I am starting off
with an array of 3 values 10, 20 and
| | 02:41 | 30, then I am outputting the value of the
first item in the array, once again outputting 10.
| | 02:47 | I'm calling the function and
then outputting the original after.
| | 02:51 | This time the behavior will be
different than in the first scenario with a
| | 02:54 | simple primitive, the original value is
10, inside the function it's 11, but the
| | 02:59 | original value after is 11.
| | 03:02 | Well, if we were passing
by copy, what's going on?
| | 03:05 | Here is a good way to visualize it.
| | 03:07 | The variables inside a complex object
are references, but when you pass the
| | 03:11 | complex object to a function, you're
making a copy of the original object.
| | 03:15 | But both the original object and the new
object are pointing to the same values internally.
| | 03:21 | A good way to say it is that a reference
variable points to a location in memory
| | 03:26 | and when you pass a variable to the
function, a new reference is always created,
| | 03:29 | but the original value is
still in the same place.
| | 03:32 | Let's once again take this
integer array named original.
| | 03:36 | It has three values of 10, 20 and 30.
| | 03:38 | Let's visualize these
values as locations in memory.
| | 03:42 | In the original array, item 1 pointed
to this location in memory, when we take
| | 03:47 | that array and we pass it to a function,
we're making a copy of the array, but
| | 03:52 | the internal references are
pointing to the same place.
| | 03:55 | So our copy of the array inside the
function is still pointing to those
| | 03:59 | locations in memory,
those values of 10, 20 and 30.
| | 04:03 | So this is why it can look like complex
objects are being passed by reference.
| | 04:07 | The complex objects themselves are
being copied, but the internal references
| | 04:11 | are being retained.
| | 04:13 | Finally, let's look at a scenario with strings.
| | 04:16 | I've said many times that strings are
complex objects, that they contain an
| | 04:20 | array of char or character values.
| | 04:23 | But I've also said that strings are
immutable, once you create a string, you
| | 04:28 | can't change its value.
| | 04:30 | It may appear that you're changing its value,
but you are actually creating a new string.
| | 04:34 | Let's see what happens when
you pass a string as a parameter.
| | 04:38 | I've created a method named
changeString, which accepts a string argument.
| | 04:42 | Within the function I set its value to
a string of new, and output that value.
| | 04:47 | When I call the code, I start off with
an original string, I output its value, I
| | 04:51 | call the method and I
output the original value again.
| | 04:55 | With strings you'll see that you're
always passing by copy, and the new copy
| | 04:59 | can't reference the internal characters,
because strings are immutable, they
| | 05:03 | can't change once they're declared.
| | 05:05 | And so you can't reach back and change
that original value, the result with a
| | 05:09 | string will look like a primitive.
| | 05:11 | The original will say whatever it did,
inside the function it will have that
| | 05:15 | value, but the original
value will remain untouched.
| | 05:19 | As long as you remember that in Java
you're always passing parameters by copy.
| | 05:24 | But with complex objects other than strings,
the internal references can be retained;
| | 05:29 | you'll see that the behavior is
completely consistent across the entire language.
| | Collapse this transcript |
| Creating a more complex calculator application| 00:00 | If you've been following along through
the entire course, you've just learned
| | 00:03 | how to build your own methods, how to
encapsulate functionality inside methods
| | 00:08 | that are parts of classes.
| | 00:10 | I'm going to use these tools to
expand on the example of the calculator
| | 00:14 | application that I showed you
how to build in an earlier chapter.
| | 00:18 | I've opened up a version of the
calculator that currently only adds data together.
| | 00:22 | It accepts two values from the command
line through two calls to the getInput
| | 00:26 | method, converts those values to
double values, and then adds them together.
| | 00:30 | We're going to add functionality to the
calculator now, so that it can not only
| | 00:34 | add but can also subtract, multiply and divide.
| | 00:37 | The first step is to convert these
three lines of code into their own method.
| | 00:42 | I'll select those three lines and right
click, then go to Refactor, Extract Method.
| | 00:47 | I'm asked for the new Method
name and I'll call it addValues.
| | 00:52 | I've selected this option,
Declare thrown runtime exceptions.
| | 00:56 | I'll described runtime exceptions
in more detail later in the course.
| | 01:00 | But for now what you need to know is
that when you convert a value using a
| | 01:04 | parsing function, if the value can't be
converted, an exception will be thrown.
| | 01:08 | When an exception is thrown, you get an
instance of a particular class, in this
| | 01:12 | case a class named NumberFormatException.
| | 01:15 | And it's good practice in Java to
declare those exceptions, so that they can be
| | 01:19 | easily handled later on in the code.
| | 01:22 | I'll click OK and that result in
extracting the code into the addValues method.
| | 01:27 | I'll Save and Run the application to make
sure it's still working the way I want to.
| | 01:30 | I'll add together values of 5
and 10 and get 15, so all is good.
| | 01:35 | Now it's time to ask the user
what operation they want to do.
| | 01:38 | Instead of just assuming they're going
to add the values, we'll let them enter a
| | 01:42 | numeric selector, one for addition,
two for subtraction and so on.
| | 01:47 | I'll get another input value, I'll
declare a variable named String and I'll name
| | 01:51 | it op for operation.
| | 01:53 | I'll call getInput and I'll set the
prompt like this, Enter 1=Add, 2=Subtract,
| | 02:00 | 3=Multiply, and 4=Divide.
| | 02:05 | Now the code is getting little wide,
so I'll double click to expand my editor
| | 02:09 | and we can see all the code on that line now.
| | 02:12 | The next step will be to convert that
op value to an integer so that I can
| | 02:16 | process it in a switch statement.
| | 02:18 | I'll declare an int named opInt for
operation as an integer, and I'll convert it
| | 02:24 | using this code, Integer.parseInt, I'll
parse in op, and now I have an integer
| | 02:30 | which indicates what the user wants to do.
| | 02:32 | Now, I'm going to examine that
integer value in a switch statement.
| | 02:36 | I'll look for the values 1, 2, 3 and 4
and then execute the requested operation.
| | 02:40 | I'll type in the word switch;
| | 02:42 | I'll press Ctrl+Space and
choose switch case statement.
| | 02:45 | I'll set the key I'm examining to
opInt and I'll set the first case
| | 02:50 | statement value to 1.
| | 02:52 | Then I'll take this command, which is
adding the values together, and I'll cut
| | 02:56 | and paste it into the case statement.
| | 02:58 | So I'm saying if the user chose 1,
I'm adding the values together.
| | 03:02 | Now I'm going to select the entire
case statement, I'll copy those to the
| | 03:06 | clipboard and I'll paste them in three times.
| | 03:09 | I'm just going to add and subtract a
little bit of white space, so this is a
| | 03:13 | little easier to read.
| | 03:14 | Now I'll take the three new
cases and I'll change what they do.
| | 03:18 | I'll change the values I'm
looking for to 2, 3 and 4.
| | 03:23 | And I'll change the methods that I'm
calling, so that instead of always calling
| | 03:26 | addValues, I can also call
subtractValues, multiplyValues and divideValues.
| | 03:33 | I'll save my changes and show you
that there are some errors showing up.
| | 03:38 | I will move the cursor over the error
marker and the one I'm looking for is the
| | 03:42 | one that says Duplicate local variable
result, this variable is being declared
| | 03:47 | four times in the same code block,
and that breaks the rule of Java.
| | 03:51 | Each variable can be declared only once
within a particular code block, a code
| | 03:55 | block being delimited by the curly braces.
| | 03:58 | When you have this kind of situation,
the solution is to move the declaration of
| | 04:02 | the variable outside of the code
block and then simply address the variable
| | 04:06 | within the code block.
| | 04:07 | So I'm going to take this code,
double result, and I'll copy it to the
| | 04:11 | clipboard, I'll move the cursor above
the switch statement and paste it in, and
| | 04:16 | I'll finish the declaration with the semicolon.
| | 04:18 | Then I'll move down to the switch
statement and I'll remove the data type
| | 04:22 | declarations from each of the four cases,
because the variable has already been
| | 04:26 | declared at this point, now all I
need to do is address the variable.
| | 04:30 | I'll save my changes and see
that I still have some errors.
| | 04:34 | The next error tells me that the
subtractValues method is undefined and that's true.
| | 04:39 | I've only created a
method so far called addValues.
| | 04:42 | Now I could go and explicitly type out a new
method or I could let Eclipse do it for me.
| | 04:47 | So to let Eclipse do the work, I'll
move the cursor over one of the method
| | 04:51 | names that's undefined and a little
window pops-up and says, there's a quick
| | 04:55 | fix available, do I want to create a
method named subtractValues that accepts
| | 04:59 | two string arguments?
| | 05:00 | Well, that's exactly what I want to do.
| | 05:02 | So I'll click the link, and then
I'll scroll down a bit and I'll see that
| | 05:05 | Eclipse has generated that method for me.
| | 05:08 | I'll go back up to the case
statements and do the same thing for multiply
| | 05:12 | values and divide values.
| | 05:14 | You can see how much time Eclipse is
saving me by generating the method signatures.
| | 05:18 | I'm going to close-up this code a
little bit, and then I'll move down to my new
| | 05:22 | methods, divide, multiply and subtract.
| | 05:25 | The code within the addValues method is
almost the same as I want in all four of
| | 05:29 | these methods, so I'm going to select
it and copy it, and then I'll paste it
| | 05:34 | into place for each of the other methods.
| | 05:36 | And all I need to do in each of
these methods is change the operator.
| | 05:39 | For subtract I'll use the dash for
multiply, I'll paste in the code and change
| | 05:44 | the operator to an asterisk, and for
divide, I'll select that extra code, delete
| | 05:49 | it paste in the other code and
change the operator to a forward slash.
| | 05:55 | I'm pretty close to being done,
there's still one error there.
| | 05:58 | The local variable result may not
have been initialized, so I'll click the
| | 06:02 | error and I'll get another set of
quick fix proposals, one of them is the
| | 06:06 | correct suggestion.
| | 06:07 | When you declare a variable that's
outside a code block, but you're only going
| | 06:11 | to set its value inside a code block,
the Java compiler wants you to initialize
| | 06:15 | its value when you declare it, so I'll
go back up to the line where I declared
| | 06:19 | result and I'll set it 0.
| | 06:21 | Now finally I have one more
bit of code to take care of.
| | 06:24 | I've asked the user to type values
of 1, 2, 3, or 4, but what if they
| | 06:27 | type another value?
| | 06:29 | I'll move the cursor after the default
case, but before the break statement and
| | 06:33 | in this case I'll tell the user you
selected a value I didn't understand.
| | 06:37 | I use System.out.println, ("
You entered an incorrect value");
| | 06:42 | and then to terminate the application at
that point, I'll use the Return keyword.
| | 06:47 | I no longer need the break statement
there, because if we got into the default
| | 06:51 | block that means the application is done.
| | 06:53 | I'll go ahead and run the
application let's see how we do.
| | 06:57 | I'll type in two numeric values 10
and 5, and instead of adding, this time
| | 07:02 | I'm going to divide, by typing in the number 4,
and I get the value 2, and that's correct.
| | 07:06 | I'll run the application again, once
again, I'll type in 10 and 5 and this time
| | 07:12 | I'll multiply it by typing 3, and I get 50.
| | 07:16 | So now my calculator is
handling all four values.
| | 07:19 | It's still possible to break the
application, for example, what happens if I
| | 07:23 | type values here, 5 and 10, but then
instead of typing a numeric value I type a
| | 07:28 | string value, I'll get an exception.
| | 07:30 | I'll show you how to handle these
exceptions and how to debug your application
| | 07:34 | in a later chapter, but what's
important to know at this point is that you now
| | 07:38 | know how to accept values from the user,
how to examine those values, how to
| | 07:42 | process them conditionally, using if
statements and switch statements, and how
| | 07:47 | to execute simple math operations.
| | 07:49 | This application, file trivial, is
using many important parts of the Java
| | 07:53 | programming language.
| | 07:54 | And you're now ready to move on to
other aspects of the language that can give
| | 07:58 | your applications even more power.
| | Collapse this transcript |
|
|
6. Working with Complex ObjectsUsing the String class| 00:01 | The string class is one of the most
commonly used complex types in Java.
| | 00:06 | I call it a complex type, because when
you create a string, you're creating an
| | 00:09 | instance of a class.
| | 00:10 | It's not a primitive variable, such
as char, int, short and the others.
| | 00:16 | I'm working in a project called strings
that's part of the Chapter 6 Exercise Files.
| | 00:20 | And the beginning class
just has an empty main method.
| | 00:23 | I'll start by declaring a string
named s1 and I'll give it a value of
| | 00:28 | "Welcome to California!"
| | 00:29 | When you declare a literal string in Java,
you must wrap the string in double quotes;
| | 00:35 | single quotes are only used for character types.
| | 00:38 | Double quotes are always used for strings.
| | 00:40 | Now I'll output the value to the
console using System.out.println(s1).
| | 00:47 | I'll run the application and predictably
I get the output "Welcome to California!"
| | 00:52 | Now you can declare strings in one of two ways.
| | 00:55 | This syntax where you assign a literal
string directly to the equals assignment
| | 00:59 | operator is actually a shortcut.
| | 01:01 | Because the string class is a
complex class, you are actually creating an
| | 01:05 | instance of the class.
| | 01:06 | And you can also use the more
conventional instantiation syntax.
| | 01:11 | It would look like this, I'll declare a
second string named s2, I'll use the new
| | 01:16 | keyword, I'll call the
constructor method for the string class.
| | 01:21 | A constructor method is a method of
a class that has the same name as the
| | 01:24 | class itself, and then I'm going to
pass in exactly the same value to the
| | 01:29 | constructor method.
| | 01:31 | I'll select that text including the
quotes and paste it between the parentheses
| | 01:35 | and then add the semicolon at the end.
| | 01:38 | And I'll change the variable that I'm
outputting from s1 to s2, I'll Save and
| | 01:42 | Run and the output is exactly the same.
| | 01:46 | You can use either syntax
style to create a string, they are
| | 01:49 | functionally equivalent.
| | 01:51 | Now I mentioned in an earlier video
that if you want to compare two string
| | 01:54 | values, you shouldn't use
the double equals operator.
| | 01:57 | It's unpredictable.
| | 01:59 | There are some circumstances in which
you can compare s1 and s2, and if they
| | 02:03 | have the same value, you'll get a
true value back and there are some
| | 02:06 | situations where you won't.
| | 02:07 | This is a situation where you won't.
| | 02:09 | If you declare one string using the
shorthand syntax with the equals assignment
| | 02:13 | operator and just a literal string, and
the second string using the constructor
| | 02:17 | method, then you can't compare
the values using double equals.
| | 02:21 | It's a strange situation, but
I want to show you the result.
| | 02:23 | I'll place the cursor at the end
of the existing code and I'll create
| | 02:26 | a conditional block.
| | 02:27 | I'll type if and press Ctrl+Space,
choose the if statement, and then I'll set my
| | 02:32 | condition as s1 has a value of s2,
using the double equals operator.
| | 02:38 | And then in the conditional block, I'll
use System.out.println and I'll output
| | 02:42 | the string, ("They match!").
| | 02:44 | I'll add an else clause and I'll make a
copy of this println command, paste it
| | 02:50 | into the else clause and change
that to ("They don't match!").
| | 02:53 | I'll Run the application and I get back
a negative result even though those two
| | 02:58 | values look like they match pretty closely.
| | 03:00 | So here's what's going on, the s1
and s2 objects are different objects.
| | 03:05 | Even though they have the same string
value, you can't reliably use the double
| | 03:09 | equals operator this way.
| | 03:11 | So instead, you should
use a method called equals.
| | 03:14 | The string class has a very
deprogramming interface and the equals method is one
| | 03:19 | of its most useful methods.
| | 03:21 | Let's take a look at the documentation
for the string class, I'll double-click
| | 03:24 | the data type string, go to Dynamic
Help on the Help menu, click the link for
| | 03:29 | the class Java.lang.string
and maximize the help view.
| | 03:33 | I'll click the Method link and scroll
down to the es, and show you that there
| | 03:38 | are two versions of the equals method.
| | 03:40 | The equals method is case sensitive.
| | 03:42 | It compares the string to
the string of another object.
| | 03:45 | There is also equals ignore case, so you
can do a non-case sensitive comparison.
| | 03:50 | So I'll close the Help screen, and I'm
going to change my syntax so that instead
| | 03:54 | of using the double equals
operator, I'll use the equals method.
| | 03:58 | If (s1.equals(s2)).
| | 04:01 | I'll save and run the
application and now I get They Match!
| | 04:06 | Now for non-case sensitive
comparisons, use the equals no case method.
| | 04:10 | I'll go to the second string and
change the welcome word to uppercase.
| | 04:15 | I'll run the application
and I get They don't match!
| | 04:18 | because the equals method is case-
sensitive, but then I'll come down to the
| | 04:22 | equals method and change it to
equalsIgnoreCase I'll fix up the code so
| | 04:26 | it's syntactically correct and I'll run the
application again, and now I get They match!
| | 04:31 | Finally, I'll show you one more method.
| | 04:33 | I've shown previously that a string
contains an array of characters and you
| | 04:38 | can extract that array of characters and
then loop through it one character at a time.
| | 04:42 | I've moved the cursor below the
conditional code, I'll declare variable with the
| | 04:46 | data type of char, open bracket, closed bracket—-
that's an array of the primitive data type char-- and I'll
| | 04:53 | name it chars and then I'll
call the method toCharArray.
| | 04:57 | So it looks like this, s1.toCharArray();
| | 05:00 | So now I have an array of characters,
then I'll loop through the array and I'd
| | 05:05 | put one character at a time.
| | 05:07 | I'll type for and press Ctrl+Space
and I'll chose the for-each iteration.
| | 05:12 | For each variable which is going to be
data typed as char with the name of c in
| | 05:16 | the char's array, I'll use System.out.
println and I'll output the value of c,
| | 05:23 | the character in that position.
| | 05:24 | I'll run the application and here is the result.
| | 05:28 | Now I'm outputting the string one
character at a time, one line at a time.
| | 05:32 | Take a look at the rest of the
documentation for the string class.
| | 05:36 | You'll find all sorts of useful methods
that allow you to compare, set, extract
| | 05:40 | and otherwise manipulate string values.
| | Collapse this transcript |
| Building strings with StringBuilder| 00:00 | The string class is one of the most
common complex classes you'll use in Java.
| | 00:05 | The string class has a special
characteristic, it's immutable.
| | 00:08 | This means that when you set a value of a
string object that value cannot be changed.
| | 00:14 | Now it might seem like you can change it.
| | 00:16 | Let's take some very simple code, I
have declared a string called s1 and
| | 00:20 | given it a value of Welcome, I'll
place the cursor on the next line and say
| | 00:24 | s1 = s1+ "to California!";
| | 00:29 | you could also write this code using
the += operator, either way it looks
| | 00:33 | like you're appending to an existing
value and simply changing the value of
| | 00:38 | an existing variable.
| | 00:39 | Then I'll output the value of
that variable to the screen using
| | 00:42 | System.out.println, and I'll parse
in s1 and I'll Run the application and
| | 00:49 | everything looks like it's working just fine,
but it's not so great in the background.
| | 00:53 | What's really happening is that when
you append a value or otherwise change the
| | 00:57 | value of the string variable, you're
actually creating a new instance of the
| | 01:01 | string class, and you're
abandoning the reference to the old object.
| | 01:05 | That old object is still out there in memory;
| | 01:07 | it becomes eligible for garbage collection.
| | 01:10 | But in fact, you're using more
memory than you need to or should.
| | 01:13 | You won't see this behaviorally in
your applications, the issue only becomes
| | 01:17 | apparent when you're trying to tune
your applications in a small memory
| | 01:21 | environment, or you're working
with very large scale applications.
| | 01:24 | But because this is a universal issue
in Java, it's good to know how to deal
| | 01:29 | with it from the beginning.
| | 01:30 | Java provides two utility classes
called StringBuffer and StringBuilder, these
| | 01:35 | two classes have the same API or
programming interface, and they both implement
| | 01:40 | the same methods named insert and append.
| | 01:43 | The insert method can be used to
insert text into a string at either the
| | 01:46 | beginning or any other position in the string.
| | 01:49 | And the append method can be
used to append text to a string.
| | 01:53 | You can use either the StringBuilder or
the StringBuffer in most environments,
| | 01:56 | but in general, the StringBuilder is
more slender, it takes less memory and
| | 02:00 | resources, but it's only good
for single threaded environments.
| | 02:04 | StringBuffer should be used where you
need to synchronize the use of a string
| | 02:08 | among multiple threads.
| | 02:10 | If you're new to Java don't worry
about it, just use StringBuilder until you
| | 02:14 | find out you have to StringBuffer.
| | 02:16 | So here is an example of how
you might use StringBuilder.
| | 02:18 | I'm going to take this little bit of
code out and leave myself with the simple
| | 02:23 | s1 variable and then after I've created
the initial string, I'll create another
| | 02:27 | variable named StringBuilder, notice
that StringBuilder and StringBuffer are
| | 02:31 | both members of the package java.lang,
so they're always available to your code.
| | 02:36 | So I'll declare the variable
StringBuilder and I'll name sb and I'll
| | 02:40 | instantiate it using new
StringBuilder, I'll place the cursor inside the
| | 02:45 | parentheses and press Ctrl+Space and
show you the different ways that you can
| | 02:49 | create a StringBuilder.
| | 02:50 | You can either call the constructor
method with no arguments or with some of
| | 02:54 | these other settings, but the one I'm going to
use is an initial string and I'll parse in s1.
| | 03:00 | So now my StringBuilder class is
being created and it's been populated with
| | 03:03 | that initial value.
| | 03:05 | Now to append a value, I'll call sb.
append and I'll parse in that appended value
| | 03:10 | that I used before, "to California!"
and I'll change my print line command to
| | 03:16 | output sb, the StringBuilder.
| | 03:19 | I'll Run the application
and I get the same result.
| | 03:21 | Whenever you're working with strings
that you need to manipulate, either adding
| | 03:25 | text or inserting text, use the
StringBuilder class instead of a simple string,
| | 03:30 | you'll create fewer objects
and you'll conserve memory.
| | Collapse this transcript |
| Parsing string values| 00:00 | The string class has many methods that you
can use to manipulate and parse its values;
| | 00:05 | I'll show you some of these
methods in this project, Parsing Strings.
| | 00:09 | I'm starting in an empty main method and
I'll declare a variable named s1 with a
| | 00:14 | value of "Welcome to California!"
| | 00:17 | First, I'll show you how to
find out how long a string is.
| | 00:20 | I use System.out.println and I'll
output "Length of string:" and then to find
| | 00:29 | out how long the string is,
use the length method, s1.length.
| | 00:33 | I'll run the application and there's the result.
| | 00:37 | You can also parse strings
using methods of the string class.
| | 00:41 | Here, I'm going to show you how to find
a string within a string, I'll declare
| | 00:45 | an integer variable named pos for
position, and I'll call the method s1.IndexOf.
| | 00:52 | You'll see when I press Ctrl+Space
that there are a number of versions of
| | 00:55 | the IndexOf method;
| | 00:56 | you can parse in a character or
string starting from a particular location.
| | 01:00 | I'm going to use the version that's
looks for a particular strength, and I'll
| | 01:03 | pass in a literal string of ("California
") and then I'll output the value of the
| | 01:08 | position character using ("
Position of California":)
| | 01:13 | and then I'll append pos.
| | 01:15 | I'll run the application and it tells
me that California starts at position 11.
| | 01:21 | Next, I'll show you how to extract a value
from a particular position of the string.
| | 01:26 | I'll declare a new string called
sub, and I'll call s1.substring.
| | 01:31 | The substring method has three
different versions, the one that passes in a
| | 01:34 | single integer, the one that takes a
single integer and an ending integer, and
| | 01:38 | one called subsequence, named
differently, that returns a character sequence.
| | 01:43 | I'm going to use the substring method
and I'll ask for the value starting at
| | 01:47 | position 11, then I'll use System.out
.println again, and I'll output the
| | 01:52 | substring that I extracted.
| | 01:54 | I'll Run the application and there is
a result, I get everything starting at
| | 01:59 | the word California!
| | 02:01 | including the exclamation mark at the end.
| | 02:04 | Finally, I'll show you how to trim a
string that might have spaces at the end.
| | 02:09 | I'll create a new string called s2 and
I'll give it a value of "Welcome!" and
| | 02:13 | I'm going to add a whole bunch
spaces at the end of the string.
| | 02:16 | Then I'll declare an int variable named
len1, and get its value from s2.length,
| | 02:23 | and I'll output the value of len1.
| | 02:28 | I'll Run the application
and I get a value of 15.
| | 02:31 | Then I'll declare another variable
named s3, and I'll get its value from
| | 02:36 | s2.trim, the trim method
removes the extra white space.
| | 02:41 | Then I'll make a copy of my print line
command and this time I use a slightly
| | 02:44 | more extended syntax, so I don't
have to create another integer variable.
| | 02:48 | It will look like this, s3.length.
| | 02:51 | I'll Save my might changes and Run the
application and after trimming, I'm down
| | 02:56 | to just eight characters.
| | 02:58 | In this exercise I've shown you some
of what I think are the most useful
| | 03:01 | members of the string class, but
again, I encourage you to look at the
| | 03:04 | documentation for the string class.
| | 03:07 | You'll find in this list of methods
many, many tools that you can use to
| | 03:11 | extract, manipulate, convert and
otherwise use the string class however you need
| | 03:16 | to in your applications.
| | Collapse this transcript |
| Working with date values| 00:00 | Java gives you a couple of different
ways of representing dates just as with
| | 00:04 | strings, the date is a complex
object and not a primitive variable.
| | 00:08 | I'm working in this empty main method
in the Dates project and I'll start by
| | 00:12 | declaring an instance of this simple date class.
| | 00:15 | I'll type in the word Date.
| | 00:17 | Now this is going to be the data type
of my variable, but unlike all the other
| | 00:20 | data types that I've have used
previously, the date class is not a member of a
| | 00:24 | packaged called Java.lang, which is
always available to your code and to the
| | 00:28 | runtime environment.
| | 00:30 | Now we are stepping out into other
libraries in the core Java class library,
| | 00:34 | specifically the date class is a
member of a package called java.util, it's a
| | 00:39 | part of the core class library,
it's always available to you.
| | 00:42 | But if you want to use this class in your code
you have to explicitly import it into your code.
| | 00:47 | Eclipse will help you with the syntax,
with the cursor right after the word
| | 00:50 | Date press Ctrl+Space.
| | 00:52 | You'll see four different date classes offered.
| | 00:54 | The one we want is at the top java.util.
| | 00:57 | There are other date classes for
java.sql and others for sun.util.
| | 01:02 | I'll press Enter or Return and that
adds the import statement for that date
| | 01:06 | class into my code at the top.
| | 01:08 | I'll give the variable a name of d, and
then I'll create the instance using the
| | 01:12 | new keyword and then the constructor
method, which like all constructor methods
| | 01:16 | matches the name of the class and
then with the parentheses in place.
| | 01:20 | I'll press Ctrl+Space.
| | 01:21 | You'll see that there are a number of versions
of the constructor method for the date class.
| | 01:25 | If you use what we call the no
arguments constructor, that is the method that
| | 01:29 | you don't pass any values into,
you'll create an object that represents the
| | 01:33 | current date and time on your computer.
| | 01:35 | The next version takes a long integer,
representing the number of milliseconds,
| | 01:40 | since the epoch date.
| | 01:41 | January 1, 1970 at midnight, you can
also represent a date as a string, as three
| | 01:47 | integer values representing the year,
month and date, and you can get all the
| | 01:51 | way precise down to seconds.
| | 01:52 | I am going to choose the
no arguments constructor.
| | 01:55 | I'll finish that statement with a
semicolon and then I'll output the value of
| | 01:59 | the date object using System.out.
println and I'll just pass the date object in.
| | 02:05 | The date class has a two string method,
when you pass in the object to println,
| | 02:09 | just like all variables in Java, when
you pass the object in, you'll get a
| | 02:13 | string representation that's
determined by that two string method.
| | 02:17 | I'll run the application and
I'll get the default formatting.
| | 02:20 | The day and month represented as three
character alpha values, the date, the
| | 02:24 | time, the time zone and the year.
| | 02:28 | Now the other class that you can
use to represent a date in Java is
| | 02:31 | called Gregorian calendar.
| | 02:33 | The name of the class has
calendar in it but it really represents a
| | 02:36 | particular date and time.
| | 02:38 | You use very similar syntax to
instantiate a Gregorian calendar object.
| | 02:43 | Because Gregorian calendar is a long
name, I'll just type in the beginning,
| | 02:47 | Greg, and I'll press Ctrl+Space and
I'll let Eclipse fill in the rest of the
| | 02:51 | class and add the required
input statement at the top.
| | 02:55 | I'll name this new variable
gc for Gregorian calendar.
| | 02:58 | For the constructor method, once again,
I'll type the beginning of the class
| | 03:01 | name and press Ctrl+Space.
| | 03:03 | You'll see that there are constructor
methods for this class, including some
| | 03:07 | that match the style of the date class,
there's no arguments constructor method,
| | 03:11 | there is a version that takes a year,
month and day, one that goes all way down
| | 03:15 | to seconds and then there are
particular versions of the calendar class that
| | 03:19 | allow you to set the locale and time zone.
| | 03:22 | I'm going to use this version that lets
me set a particular year, month and day.
| | 03:27 | When you set the year, you need to
pass in a four digit numeric value.
| | 03:31 | I'll type a value of 2009, set the
month to a value from 0 to 11 just like a
| | 03:36 | Java array, a month is
represented using zero-based calculations.
| | 03:40 | So 0 is January, 1 is February and so on.
| | 03:44 | I'll type the number 1 for February
and then I'll set the day of the month at
| | 03:47 | 28, the last day of February in that year.
| | 03:50 | Now if I were to type in a value of 29,
the Gregorian calendar class is smart
| | 03:55 | enough to know that 2009 was not a
leap year and it would reject that.
| | 03:59 | One of the advantages of using a Gregorian
calendar object is that you can do math with it.
| | 04:04 | You can add, subtract and
otherwise manipulate the date.
| | 04:07 | I'm going to increment the value of
the day in the Gregorian calendar by 1.
| | 04:12 | So I should go from February 28 to March 1.
| | 04:15 | Here is the code, gc.add.
| | 04:18 | The add method takes two values, a
field which represents which part of the
| | 04:22 | calendar I want to manipulate, and the amount.
| | 04:25 | For the field use a value that's a member
of the Gregorian calendar class, like this.
| | 04:31 | I'll type in GregorianCalendar and then
dot and I'll see a listing of all of the
| | 04:36 | available settings that
represent parts of a date.
| | 04:39 | And I am going choose this one,
DATE which represents the day.
| | 04:42 | And then I'll tab over and set the value as 1.
| | 04:46 | So I am adding 1 day to the date.
| | 04:48 | Now to output the value, I have to
convert it back to a date object.
| | 04:53 | The Gregorian calendar doesn't have
formatting capability, it only has math,
| | 04:57 | manipulation and the ability to
breakdown the date into small parts.
| | 05:01 | So in order to get it ready for
formatting, I'll create another new date class.
| | 05:05 | I'll call this one d2, and I'll
get its value from gc.getTime.
| | 05:10 | The getTime method returns
an instance of the date class.
| | 05:14 | Now for formatting, I'm going to use
yet another class called DateFormat.
| | 05:18 | I'll create an instance of the
DateFormat class, just as with date in
| | 05:22 | Gregorian calendar, I need an import,
so I'll type in the name of the class
| | 05:25 | and press Ctrl+Space and I'm going to choose
the DateFormat class from the package java.txt.
| | 05:32 | I'll call my DateFormat
class df for date format.
| | 05:36 | Now in order to construct an instance of
this class, you don't use the new keyword;
| | 05:41 | the DateFormat class has a number
of methods that you can use to return
| | 05:45 | instances of the DateFormat class.
| | 05:47 | I'll use this syntax,
DateFormat.getDateInstance.
| | 05:51 | This is a particular design
pattern called a factory method.
| | 05:55 | A factory method of a class knows how
to return an instance of that class, and
| | 06:00 | you'll see in this list many different
factory methods that behave differently.
| | 06:04 | Again, for detailed information about what
each of these methods does, look at the docs.
| | 06:08 | I'll choose this very first
factory method, getDateInstance.
| | 06:12 | Next, I'll create a string and I'll
call this one sd for a string of a date.
| | 06:18 | And I'll get the value of sd from df.
format, and I'll pass in the d2 variable,
| | 06:24 | the date object I got from the calendar.
| | 06:26 | And then finally, I'll output the value using
System.out.println and pass in the value of sd.
| | 06:33 | I'll run the code and there is the result.
| | 06:36 | I started off with February 28th, I added a
value of 1 to the date and I got March 1, 2009.
| | 06:42 | Now this is the default formatting.
| | 06:44 | You can easily manipulate or
change how the formatter behaves.
| | 06:48 | I'm going to change the way I
called to getDateInstance method.
| | 06:52 | I'm going to pass in a DateFormat.FULL.
| | 06:55 | This is a field or a constant of the
date format class that means use more
| | 07:00 | extended formatting.
| | 07:01 | I'll Save and Run the application again and
now I get the full day, month, date and year.
| | 07:08 | So that's a look at three useful
classes that you can use to manage
| | 07:11 | and manipulate dates.
| | 07:13 | The date class which represents the
date as the number of milliseconds, since
| | 07:16 | January 1, 1970, through Gregorian
calendar that lets you break down the date
| | 07:21 | into parts and do math, and otherwise
manipulate the values, and the date format
| | 07:25 | class that allows you to
format the date for presentation.
| | 07:29 | All three of these classes require
explicit imports in your code, because
| | 07:33 | none of them are members of that package
java.lang, these classes are always available.
| | 07:37 | I'll talk more about import statements
later on in the course, but just know, if
| | 07:42 | you're not sure whether you need an
import statement for a class, just place the
| | 07:45 | cursor after the class name, press Ctrl+
Space and select it and if you need it,
| | 07:50 | Eclipse will add it to the code for you.
| | Collapse this transcript |
|
|
7. Exception Handling and DebuggingUnderstanding compile-time vs. runtime errors| 00:00 | Errors in Java can be separated into two
major types, compile time and runtime errors.
| | 00:06 | A compile time error is either a
syntax error or an error in the structure
| | 00:11 | of the application.
| | 00:13 | Syntax errors are pretty straightforward.
| | 00:15 | Let's say for example that I declare a
variable named s and I give it a value,
| | 00:20 | but I don't put the
semicolon at the end of the line.
| | 00:23 | That breaks a fundamental rule of Java syntax.
| | 00:26 | All statements must have a semicolon.
| | 00:28 | And when I save and try to build the
application, I get this error down at
| | 00:32 | the bottom in the problems view, Syntax error,
insert semicolon to complete BlockStatements.
| | 00:42 | Other kinds of compile time errors can
occur when you break fundamental workflow rules.
| | 00:47 | For example let's say I declare a
variable named s, I put in the semicolon at
| | 00:52 | the end of the line and that line
on its own is syntactically correct.
| | 00:56 | But then I immediately try to output the
value of s using System.out.println and
| | 01:03 | I parse in the value.
| | 01:05 | And so I have two syntactically
correct statements, but when I save the
| | 01:10 | application once again, I get
an error in my problems view.
| | 01:14 | If your errors are represented by this
red circle with x, that means it's an
| | 01:19 | error that is preventing the
application from compiling.
| | 01:23 | And if you try to run the
application you'll get this error dialog.
| | 01:27 | Errors exist, Proceed with launch.
| | 01:30 | If you proceed at this point, your
application might seem to run, but you'd be
| | 01:35 | running an old version of the
application, not the one for the code you have on
| | 01:39 | the screen right now.
| | 01:40 | If you have errors like this
your application can't be compiled.
| | 01:44 | In this case the rule that you are
breaking is that you can't declare a variable
| | 01:49 | without initialization code and then
refer to that variable immediately.
| | 01:54 | The most common fix to this is to add
equals null and that would make it so that
| | 01:59 | the compiler decided you
knew what you were doing.
| | 02:02 | Because I declared the variable and gave it
an initial value, I can now compile and run.
| | 02:08 | And when I run the
application I just get the word null.
| | 02:12 | So that's a compile time error.
| | 02:14 | The other type of error is a runtime error.
| | 02:17 | These are errors that occur because you
break some rules that can't be caught by
| | 02:21 | the compiler but when you run the
application the error is so bad it just kills
| | 02:26 | the application, it crashes it.
| | 02:28 | Here is a very simple error that occurs a lot.
| | 02:31 | I'm going to declare a new string
array variable, I'll just name it strings.
| | 02:36 | And I'll give it an initial
value of one item, "Welcome!"
| | 02:40 | This is one way of declaring an array
in Java by wrapping comma delimited list
| | 02:46 | inside a pair of braces.
| | 02:48 | If I only declare one value inside the
braces, then it's an array of one item.
| | 02:53 | Now I'm going to try to output an item
in the array using System.out.println and
| | 03:00 | I'll refer to strings, open bracket, 1, closed bracket.
| | 03:06 | This is clearly an error.
| | 03:08 | Arrays in Java are zero-based.
| | 03:11 | If I want to refer to the first item
in the array, I need to refer to the
| | 03:15 | index zero, not one.
| | 03:17 | If I'm referring to one that means the
second item in the array and it doesn't exist.
| | 03:22 | When I save my changes, the compiler
says looks good to me and I don't see any
| | 03:28 | problems in the problems view.
| | 03:30 | But when I run the application, I
get a big odd error and my application
| | 03:34 | just stops working.
| | 03:36 | Exceptions in Java cause the application
to quit unless you've handled them yourself.
| | 03:42 | The particular error that's
occurring is something called
| | 03:45 | ArrayIndexOutOfBoundsException.
| | 03:48 | In the next video I'll talk a little
bit more about exception classes or
| | 03:52 | exception objects, the kind of
objects that are generated in Java when an
| | 03:57 | exception occurs and how you can look
at the exception object both in the Java
| | 04:02 | debugger and in your own code.
| | Collapse this transcript |
| Handling exceptions with try/catch| 00:00 | If you know in your application that you
might generate a runtime exception, you
| | 00:04 | can anticipate and handle it
using a syntax called try and catch.
| | 00:09 | The first thing you have to
know is how exceptions behave.
| | 00:13 | I'm working in a project named
exceptions and it has a couple of lines of code
| | 00:17 | that will generate a runtime error.
| | 00:20 | I've declared a strings variable which
is an array of string objects and I've
| | 00:24 | initialized it with one
item, a string named welcome.
| | 00:27 | And then in the next line, I try to
output the second item in the array,
| | 00:31 | which doesn't exist.
| | 00:32 | When I run the application, I get an exception.
| | 00:36 | When these kinds of exceptions happen in
Java it stops your application cold, it
| | 00:41 | crashes the application.
| | 00:43 | I can show you that in fact this
application is crashing and is not
| | 00:47 | continuing with its execution.
| | 00:49 | I'll add another line of code down here
System.out.println and I'll output, "The
| | 00:55 | application is still running1" I'll
save and run the application, I'll see my
| | 01:03 | error and I don't see anything after it.
| | 01:07 | So how do you handle a potential runtime error?
| | 01:10 | The first thing you need to know is that
when an exception occurs, a variable is
| | 01:15 | generated, an exception object.
| | 01:17 | The exception object will be an
instance of a class named exception or of
| | 01:23 | another class that's a subclass of exception.
| | 01:26 | If you want to wrap your code and
deal with a possible exception, the first
| | 01:30 | thing to do is put the code into a try block.
| | 01:33 | The try block will be followed by a
catch block or more than one catch block and
| | 01:38 | the code in the catch block will
deal with the exception in some way.
| | 01:42 | Here is a very simple way to add a try
catch block around some code that might
| | 01:46 | generate a run-time error.
| | 01:48 | I'm going to select that code and then
I'll right click on it and I'll choose
| | 01:53 | Surround With, Try/catch block.
| | 01:56 | The syntax of the Try/catch block is
that you start off with the word try and
| | 02:02 | then you put the code that might
generate the exception inside the first set
| | 02:05 | of braces, then you follow that with a
catch block starting with the keyword
| | 02:11 | catch and then a variable declaration which is
of data type exception or one of its subclasses.
| | 02:18 | Then within the catch block, you can
handle the exception in some fashion.
| | 02:23 | If your code execution gets into the
catch block that will clear the error and
| | 02:28 | your application will continue running.
| | 02:30 | I'm just going to get rid of the TODO
comment and save my changes and then I'll
| | 02:34 | run the application again.
| | 02:37 | And I still see that there is an error but
then I get this extra little bit of code.
| | 02:42 | The application is still running.
| | 02:44 | And so I know that my try catch
block has handled the exception.
| | 02:48 | Within the catch block right now,
I'm executing a method of the exception
| | 02:52 | class called printStackTrace and
that's why in the console block, you're
| | 02:57 | seeing this output.
| | 02:58 | java.lang.ArrayIndexOutOfBoundsException:
| | 02:59 | 1.I could take that little bit of code
out, I am just going to comment it and
| | 03:08 | I'll put in a little bit of my own custom
code, System.out.println, there was an error.
| | 03:14 | So I'm telling the user that something
went wrong, but I'm being a little more vague.
| | 03:18 | Stack traces tend to scare users,
because they don't know what's going on inside
| | 03:23 | the program and they shouldn't have to.
| | 03:24 | I'll run the application
again and now I get clean output.
| | 03:29 | There was an error, but the
application is still running.
| | 03:33 | In this situation, the particular type
of exception that was thrown was not just
| | 03:38 | an instance of the exception
class but of one of its subclasses.
| | 03:42 | You can be more specific in your catch
block by knowing exactly which type of
| | 03:46 | exception you are anticipating.
| | 03:49 | To find out what that class is, I'm
going to remove the comments and run the
| | 03:53 | application again and I see that the
exception object is an instance of this
| | 03:58 | one, ArrayIndexOutOfBoundsException.
| | 04:02 | To be more specific about this, I'll go
into the console and I'll copy the name
| | 04:07 | of that exception class to the clipboard,
then I'll go back to my code and I'll
| | 04:12 | change the data type of the exception object.
| | 04:14 | I'm declaring from exception to a
rate index out of bounds exception, just
| | 04:19 | by pasting that in.
| | 04:20 | Then I once again comment out the
printStackTrace method and run the application.
| | 04:25 | And I'll see that everything is
working the way I wanted it to.
| | 04:28 | But now I set up a situation where
as long as they get this particular
| | 04:32 | exception, I'll be able to keep
running the application but if any other
| | 04:36 | exception happens the application will stop.
| | 04:39 | The compiler will tell me what went
wrong and I'll be able to figure out what
| | 04:42 | that exception was about and fix it.
| | 04:45 | So that's a look at how to use the
try catch structure, to anticipate
| | 04:49 | errors that you know might happen in
your application and then elegantly deal with them.
| | Collapse this transcript |
| Throwing exceptions in methods| 00:00 | As I showed in a previous video, a
runtime exception generates an instance of a
| | 00:04 | class called an exception class, either the
exception class itself or one of its subclasses.
| | 00:10 | I've shown how to deal with this
with a try catch block around the
| | 00:13 | possibly offending code.
| | 00:15 | But I'd also like to show you how to
explicitly declare some code that might
| | 00:19 | throw an exception and wrap it in a
method that has a keyword called throws,
| | 00:24 | that tells the rest of the
application what might happen.
| | 00:27 | Here is the same starting code as in
a previous video, instead of wrapping
| | 00:31 | this directly inside try catch, I'm going to
take this code and put it into its own method.
| | 00:37 | I'll select these two lines of code
right click on the selected code and choose
| | 00:42 | Refactor, Extract Method.
| | 00:44 | I'll give the method a name of
getArrayItem, and right here I'm going to select
| | 00:50 | an option of Declare thrown runtime exceptions.
| | 00:54 | This sort of refactoring, taking code
that might generate a runtime exception
| | 00:58 | and putting it into its own separate
method is such a common practice that
| | 01:03 | Eclipse has a special option for it.
| | 01:06 | I'll click OK and that creates the new method.
| | 01:09 | Now notice, it didn't add any
additional code and the reason is because in this
| | 01:13 | situation none of the code that I
executed already told Eclipse what kind of
| | 01:18 | runtime exception might happen.
| | 01:21 | So I'm going to put in the code myself,
I'll place the cursor after the name of
| | 01:25 | the method, now at this point, the
code is going to get a little bit wide.
| | 01:29 | So I'm going to go to a new line here
and I'll put in the keyword throws and
| | 01:35 | then add Array press control
space and choose the exception class
| | 01:40 | ArrayIndexOutOfBoundsException.
| | 01:43 | This now tells the rest of the
application that when this particular code is
| | 01:47 | running, that is the code within the
getArrayItem method, that it could throw
| | 01:51 | this specific kind of exception object.
| | 01:53 | Now, I'll go to the method getArrayItem,
I'll select that, I'll right click and
| | 01:59 | I'll select Surround With, Try/catch
Block and now Eclipse is smart enough to
| | 02:03 | know that because I'm calling a method
that could throw this object, that's the
| | 02:08 | one it's looking for.
| | 02:09 | I'll get rid of the TODO comment, I'll
replace e.printStraceTrace with my own
| | 02:15 | custom message, System.out.println "
Array item was out of bounds" and I'll
| | 02:25 | run the application.
| | 02:26 | And now I'm elegantly catching the
error, handling it myself, and the rest of
| | 02:31 | the application can keep on running.
| | 02:34 | So again, the common practice is when
you have a bit of code that might generate
| | 02:39 | an exception, put it in its own
special method and mark the method with the
| | 02:44 | keyword throws and the particular kind
of exception class that might be thrown.
| | Collapse this transcript |
| Using the debugger| 00:00 | All good Java development environments
including Eclipse provide good debuggers
| | 00:04 | that allow you to inspect data at runtime,
set breakpoints, and otherwise figure
| | 00:09 | out what's going on in your code.
| | 00:12 | I'm going to show you how to use the
debugger and along the way, I'll show you
| | 00:15 | how to work with parts of the Java class
library that commonly throw exceptions,
| | 00:20 | how you can find out what those
exceptions might be and anticipate them.
| | 00:25 | I'm working in an empty main
method in the current project debugger.
| | 00:29 | I'm going to declare a
variable of a special type URI.
| | 00:33 | URI stands for Uniform Resource Identifier.
| | 00:37 | This class is a part of the package
java.net and is part of a collection of
| | 00:41 | classes that are used for
network communications in Java.
| | 00:45 | After you have typed URI, press Ctrl+
Spacebar and choose the URI class from java.net.
| | 00:51 | That will add an import
statement at the top of the code.
| | 00:54 | Then give it a variable name uri, all
lower case, and set its initial value with
| | 01:00 | the constructor method new URI and pass
in a well formed domain string such as
| | 01:06 | "http://somecompany.com."
| | 01:12 | It doesn't matter what the name of
the domain is or even whether it's real
| | 01:15 | website, what matters is that it's well
formed with http://at the beginning and
| | 01:21 | then a well formed domain at the end.
| | 01:24 | When you save your changes and build
the project, you'll see an error has
| | 01:28 | occurred, Unhandled
exception type URISyntaxException.
| | 01:33 | The Java compiler seems to think that
when I call this URI constructor method,
| | 01:37 | it might throw an exception and that
it's up to me as the programmer to make
| | 01:41 | sure that I've handled that exception.
| | 01:43 | Well, how would I know that as the
programmer unless I have to wait for the
| | 01:47 | compiler to tell me?
| | 01:48 | And the answer as is so frequently the case in
Java is that it's there in the documentation.
| | 01:54 | I'll go to the URI documentation,
I'll double click URI, the data type and
| | 02:00 | then I'll go to my Dynamic Help and
click javadoc for java.net.uri and I'll
| | 02:07 | maximize the Help screen.
| | 02:10 | In the documentation, I'll click on
Constructor, here is the method that I just
| | 02:14 | called URI receiving a string argument.
| | 02:18 | I'll click that method and it tells me
and the documentation very explicitly,
| | 02:23 | this method could throw an the
instance of URI syntax exception.
| | 02:28 | So when you're working with a method
that's part of the Java class library
| | 02:33 | and that method has been defined as
throwing an exception, it'll be there in the docs.
| | 02:38 | So what do I have to do as a
developer to deal with that?
| | 02:41 | If a bit of code is going to throw an
exception I have to handle it with a
| | 02:46 | Try/catch method or by putting an
appropriate throws declaration in the method
| | 02:52 | signature where I'm actually calling the code.
| | 02:55 | I'm going to wrap up this code with a Try
/catch block, I'll select the code then
| | 03:00 | right-click it and choose
Surround With, Try/catch block.
| | 03:06 | Eclipse is smart enough to look at the
syntax of the class or the method and say
| | 03:11 | hey that method might throw URI syntax
exception and so that's the class that
| | 03:16 | puts into the catch block that it generates.
| | 03:19 | Now, I'll delete the TODO comment and I
will add a little bit more code down at
| | 03:24 | the bottom, so I can see clearly
that the application is still running
| | 03:27 | System.out.println and I'll
put the message "I'm alive!"
| | 03:35 | I'll save the change and run the application.
| | 03:40 | And the first time everything works
fine because the string that I passed into
| | 03:44 | the URI method was a well formed domain.
| | 03:48 | But now let's create an intentional error.
| | 03:50 | I'll change those
forward slashes to Backslashes.
| | 03:54 | That will create a malformed URI.
| | 03:57 | I'll save and run the
application and now I get the stack dump.
| | 04:02 | I still see I'm alive!
| | 04:03 | at the end of the output.
| | 04:05 | And by the way, you might not see
this at the end of the output it might be
| | 04:08 | mixed into the middle don't worry about that.
| | 04:11 | But if you see that message that means
that the Trycatch block is working but in
| | 04:15 | fact, this error message is being
thrown as part of that complex exception
| | 04:20 | object and this takes us to the debugger.
| | 04:24 | Let's say, that I wanted to
interrogate that exception object while I'm
| | 04:27 | programming, I wanted to look at its structure.
| | 04:31 | I can put a breakpoint on the line where
the printStackTrace command is being executed.
| | 04:36 | And I can freeze the execution of
the application, suspend it, while it's
| | 04:41 | suspended, I can use Eclipse to
inspect that exception object and see what
| | 04:46 | information is available.
| | 04:47 | To do this place a breakpoint on the
line where the exception object is in
| | 04:52 | scope, in this case it's on this
line where I'm calling printStackTrace.
| | 04:57 | To set a breakpoint, go to the left
trough over on the left side of the editor
| | 05:02 | and either double-click or you can
right click and choose Toggle Breakpoint.
| | 05:08 | Either way, you should see this
little icon showing that there is now a
| | 05:11 | breakpoint at this particular line.
| | 05:13 | Now it's time to run the
application in debug mode.
| | 05:17 | Go to the toolbar and click debug, it's
the little button that looks like it has
| | 05:22 | a cockroach or a bug on it. Click the button.
| | 05:26 | If you see a message from your firewall
application, let it know that everything
| | 05:30 | is okay, and then you should see
this message Confirm Perspective Switch.
| | 05:35 | This is telling you that Eclipse wants to
switch to something called the Debug perspective.
| | 05:40 | The debug perspective is a collection
of views that will allow you to more
| | 05:44 | quickly inspect and fix
your application. Click Yes.
| | 05:49 | And this is the debug perspective.
| | 05:52 | There is a Debug view in the upper
left that shows your current call stack, a
| | 05:56 | Variables view that shows all the
currently in scope variables the Editor, the
| | 06:01 | Outline and down at the bottom, the Console.
| | 06:05 | Go to the Variables view because you
suspended the application at the point
| | 06:09 | where the exception object became
available, you should see the exception object
| | 06:14 | named e listed there, double-click the
tab for variables to expand it and then
| | 06:20 | expands the e object.
| | 06:22 | You'll see that there's all sorts of
interesting information the cause, the
| | 06:27 | detail message, the index,
the input and the stack trace.
| | 06:32 | Now some of these values occur on all
exception objects like the detail message,
| | 06:37 | but the values that they
have may or may not be useful.
| | 06:41 | In this case, there's a pretty interesting
error here, Illegal character in opaque part.
| | 06:47 | But you'll also find that you can call
methods of the exception object to get
| | 06:51 | the information more elegantly.
| | 06:54 | Once you've finished inspecting the
exception object, double-click the Variables
| | 06:58 | tab to return it to its original size,
then go up to the toolbar and click the
| | 07:02 | Terminate button, it's the red
square button on the toolbar.
| | 07:07 | And then return to your
CustomForJava perspective.
| | 07:11 | You can choose the perspective from
the upper right or you can go to the Menu
| | 07:15 | and choose Window, Open Perspective,
Other and choose the perspective you want,
| | 07:21 | I've been using this one CustomForJava.
| | 07:24 | Once you know what the structure of
the exception object is, you can do some
| | 07:27 | interesting stuff with it.
| | 07:29 | So for example, instead of printing
the stack trace, I'm going to do a little
| | 07:33 | print line here System.out.println.
| | 07:37 | And I'm going to output a
value from e.getMessage.
| | 07:41 | This is a method that's
available on all exception objects.
| | 07:45 | I'll save my changes and
run the application again.
| | 07:49 | And I get that message Illegal
character in opaque part at index 5, and it's
| | 07:55 | talking about index 5 of the string.
| | 07:57 | If you start counting at 0, the letter
h is 0, ttp is 1, 2, 3, the : is 4 and
| | 08:05 | the / is 5, that \\ was interpreted as
a \ by Java and it's telling me exactly
| | 08:13 | where the problem is in that string.
| | 08:16 | So now, I can come back to the code
and go oh gosh, I put in \\ instead of //
| | 08:21 | and I can fix it, save and
run, and everything is okay.
| | 08:27 | So whenever you are working with a
method that might throw an exception, you
| | 08:31 | should wrap it inside a Try/catch block
and then within the catch block to can
| | 08:35 | set a breakpoint and
inspect that exception object.
| | 08:39 | Once you know how to use the debugger for
that, you know how to use it for everything.
| | 08:44 | Whenever you have some information in
your Java programming environment and
| | 08:48 | you're not sure what the value of a
variable is, set a breakpoint and use the debugger.
| | Collapse this transcript |
|
|
8. Using Data CollectionsUsing simple arrays| 00:00 | Java gives you a couple of ways of
managing ordered collections of data in memory.
| | 00:05 | The simplest approach
syntactically is to use simple arrays.
| | 00:08 | Simple arrays are very easy to code,
but they're not particularly flexible.
| | 00:12 | There are couple things to
know about simple arrays.
| | 00:15 | First all of the items in an array must
be of the same type, so you can create
| | 00:19 | an array of integers or create an
array of strings, but you can't create an
| | 00:23 | array that contains both.
| | 00:25 | Also, when you declare an
array it's always of a fixed size.
| | 00:29 | You set the size when you declare it
and you can't change the size at runtime.
| | 00:34 | If you want to use resizable arrays you
want to take a look at the class array
| | 00:37 | list which I'll describe in a separate video.
| | 00:41 | There are few different syntax
styles that you can use to declare and
| | 00:44 | initialize an array.
| | 00:45 | I'm working in an empty main
method in a project named simple arrays.
| | 00:50 | Here is one style of syntax.
| | 00:52 | Start with the data type of the array,
followed by a pair of brackets, then
| | 00:56 | assign, the array name, put in an
equals operator, and then initialize the
| | 01:01 | array using the new keyword, the data
type again and the brackets again but
| | 01:06 | this time the size.
| | 01:08 | So this is an array of three integers.
| | 01:11 | Now, I'll add up a little bit of looping code.
| | 01:14 | I'll type in for and press Ctrl+
Spacebar and I'll choose iterate over array,
| | 01:19 | I'm iterating over the a1 array,
Eclipse figured that out for me.
| | 01:24 | And within the for loop I'll output
System.out.println and I'll output the value
| | 01:29 | of a1, bracket, i, bracket) meaning the item
at position i. I'll save and run the application and
| | 01:37 | the output is three zeros.
| | 01:41 | Now, there is a variation on this
syntax that's possible and it's completely a
| | 01:44 | matter of preference which one you use.
| | 01:46 | I am going to select and copy this
block of code and then paste it in.
| | 01:51 | I'll change the name of the second array to a2.
| | 01:54 | I'll make the change in three
places, here, here and here.
| | 01:59 | And then I'm going to take the brackets
and move them from after the data type
| | 02:04 | and paste them after the array name.
| | 02:07 | This variation does exactly the
same thing as the first version.
| | 02:10 | It creates an array of three items and
the items will have their default value.
| | 02:15 | Integer is just like all other primitive
numeric types, have the default value of zero.
| | 02:21 | And so when I print these out once
again I should get three zeros, and when
| | 02:25 | I run the application, I get the three items
in array a1 and the three items in array a2.
| | 02:33 | The third style syntax for simple
arrays is to initialize the values in the
| | 02:38 | declaration statement.
| | 02:39 | I've used this version of the
syntax previously in the course.
| | 02:43 | Start off with your data type, once
again you can place the brackets either
| | 02:47 | after the data type or after the
array name and then put in a pair of curly
| | 02:52 | braces and then declare your list
of items as a comma delimited list.
| | 02:57 | So I'll add in a list of 3, 6, 9.
| | 03:01 | The number of items in the array and
their values are determined by that list.
| | 03:06 | As with the previous declarations,
once the array is set to have a particular
| | 03:10 | number of items it will always have that
number of items, you can't change it at runtime.
| | 03:16 | I'll make a copy of one of these for
loops, and I'll copy and paste it down here.
| | 03:21 | I'll change the references here from a2 to a3.
| | 03:26 | I'll run the application
and there is the result.
| | 03:30 | The last array has values of 3, 6 and 9.
| | 03:32 | Once you've declared an array, you
can address the items in the array using
| | 03:39 | array syntax, where you referred to
the index of an item using zero-based
| | 03:44 | numbering wrapped inside brackets.
| | 03:47 | So for example, I could say System.out.
println, "The value of the first item is"
| | 03:58 | and then I can address a3, open bracket, 0.
| | 04:03 | I'll save and run the application, and I
see that the value of the first item is three.
| | 04:08 | And as I've shown in previous videos,
if I try to address an array item and I
| | 04:13 | get it wrong, if I put in an index to
an item that does not exist I'll generate
| | 04:18 | an exception a runtime error.
| | 04:21 | So that's the basics of simple arrays,
once again the syntax can vary a little
| | 04:25 | bit, you can place these initial
brackets either after the data type or after
| | 04:29 | the array name and you can either use
the new keyword and an explicit number of
| | 04:34 | items in the array, or you can use a
comma delimited list wrapped in braces.
| | 04:39 | Either way the array must contain items
all of the same data type and it is not
| | 04:45 | resizable at runtime.
| | Collapse this transcript |
| Using two-dimensional arrays| 00:00 | Java supports the use of
multidimensional arrays.
| | 00:03 | Just as with simple arrays a
multidimensional array contains items all of
| | 00:08 | the same data type.
| | 00:09 | And once the sizes of the dimensions
of the array have been set you can't
| | 00:13 | change them at runtime.
| | 00:14 | I'll show you how to use a
multidimensional array in this empty project 2DArrays.
| | 00:21 | I'll start by declaring the array.
| | 00:23 | This is going to be a multidimensional
array of strings, so I'll start with the
| | 00:28 | data type followed by brackets,
but because this is going to be a
| | 00:32 | two-dimensional array, I
add another pair of brackets.
| | 00:36 | Next, I assign the array
name, I'll call it states.
| | 00:40 | Then after the equals assignment
operator, you put in the new keyword, once
| | 00:45 | again you put in the data type.
| | 00:47 | And now just as with simple arrays you
declare the array size, but now you're
| | 00:51 | declaring both the top-level
dimension and the child dimension.
| | 00:55 | I'll set the size of my top-level
dimension at three and my child dimension at 2.
| | 01:00 | Now my goal is to create a primary array of
three items each one representing a state.
| | 01:06 | And then within the secondary array or
child array there'll be two items, one
| | 01:11 | for the name of the state
and one for its capitol.
| | 01:14 | Now I'll set the values.
| | 01:16 | Use similar syntax to set values.
| | 01:18 | I'll start with states, bracket, 0, bracket, 0.
| | 01:22 | The first item in the first primary array.
And I'll set that to a value of California.
| | 01:29 | Next I'll create the second item
in the first primary array using the
| | 01:34 | syntax states, bracket, 0, bracket, 1,
and I'll set that to the name of the capitol of
| | 01:41 | California, Sacramento.
| | 01:44 | Now I'm going to copy and paste those
two lines of code a couple of times.
| | 01:49 | I'll create two new copies.
| | 01:53 | And for the second pair, I'll
change the primary array item to one.
| | 01:57 | And for the third pair I'll set
the primary array item to two.
| | 02:02 | Now I'll set the values, the second state
will be Oregon, and its capitol is Salem.
| | 02:09 | And for the third pair I'll
use Washington and Olympia.
| | 02:15 | Now to output these values, I am
going to use a loop inside a loop.
| | 02:20 | I'll use two for loops and I'll manage
my output by using a StringBuilder object
| | 02:25 | to build strings for each
combination of state name and capitol.
| | 02:29 | I'll start by typing the word for and
pressing control space and I'll choose
| | 02:34 | for, iterate over array.
| | 02:37 | In the primary for loop the integer
counter variable will be named i. And
| | 02:42 | I'll be looping through the primary array,
this syntax is the same as for a simple array.
| | 02:47 | I'm iterating through the primary
dimension, the one that has three items.
| | 02:53 | Then I'll click into the primary for
loop and I'll add a secondary for loop.
| | 02:57 | I'll once again type for
and choose iterate over array.
| | 03:02 | And this time, Eclipse knows that I've
already used the variable i, so it uses
| | 03:06 | the variable j for the secondary counter.
| | 03:10 | Now to make sure that I'm iterating
over the secondary array, I'll place the
| | 03:14 | cursor after name of the
array, states, and I'll add bracket, i, bracket.
| | 03:20 | So now I have an outer loop and an inner loop.
| | 03:24 | Now my goal is each time through the
loop, I'm going to output the state name
| | 03:28 | and its capitol all in a single line.
| | 03:32 | To put it together I'll declare a StringBuilder.
| | 03:33 | I'll put the declaration and
initialization of the StringBuilder in the outer
| | 03:39 | loop, so then I can manipulate
and append to it in the inner loop.
| | 03:43 | So I'll set the data type to
StringBuilder and its variable name to sb and
| | 03:47 | I'll initialize it.
| | 03:53 | Within the for loop, I'm simply going
to add the values to the StringBuilder
| | 03:58 | using sb.append and I'll output states,
open bracket, i, open bracket, j.
| | 04:07 | And then after the for loop I'll
use a println command to output the
| | 04:11 | StringBuilder to the console System.out.println.
| | 04:16 | And I'll just refer directly
to the StringBuilder object.
| | 04:18 | I'm not quite done yet but
let's see the results so far.
| | 04:22 | I'll save and run the application and
I'm seeing that I am successfully getting
| | 04:27 | both the state name and its
capitol output to the same line.
| | 04:31 | So now I need to add a little bit of
conditional logic so I can separate those values.
| | 04:38 | I'll go to the inner loop and
I'll add some conditional code.
| | 04:42 | I'll type if and press control space
and choose the if statement and I'll set
| | 04:46 | the condition to if J has a value of zero.
| | 04:50 | So if I'm working on the state
name then j will have a value of zero.
| | 04:54 | And before I append the state name, I
want to append a little bit of text.
| | 04:59 | So I'll say sb.append, I'm appending a
string to the existing StringBuilder, and
| | 05:04 | so now the text should say the capitol of and
then the name of the state. Let's check that.
| | 05:09 | The capitol of California, so now, all I
have to do is separate those two values
| | 05:15 | and I'll use an 'else' clause for that.
| | 05:24 | If I'm just about to append the capitol
name to the string builder, I'll put in
| | 05:29 | a space the word is and another
space and let's see how I'm doing.
| | 05:34 | And now I have sensible output, the
capitol California is Sacramento, the
| | 05:39 | capitol of Oregon is Salem and so on.
| | 05:41 | So I have successfully organized my
data into a multidimensional array.
| | 05:47 | Now the strength of this approach is
that if you know exactly how much data
| | 05:51 | you're going to be working with, it's a
pretty straightforward process to store
| | 05:55 | it in memory and then access it at runtime.
| | 05:58 | If on the other hand you have to be
able to expand the array or shrink it at
| | 06:02 | runtime, because you don't know how
much data you're going to be dealing with
| | 06:06 | and you can't just declare the array,
and then deal with a fixed size, then you
| | 06:10 | should start looking at
the array list class instead.
| | 06:14 | And I'll talk about that in another video.
| | Collapse this transcript |
| Managing resizable arrays with ArrayList| 00:00 | There are many situations in
applications where you need to manage ordered
| | 00:04 | collections of data.
| | 00:05 | That means that once you add data to
the collection, it stays in the same order
| | 00:10 | and you can reference the items in the
data collection by their index position.
| | 00:13 | This simple array in Java is useful but it
has a downside, it's not resizable at runtime.
| | 00:20 | And so Java provides a special class for
resizable arrays, it's named array list.
| | 00:26 | You declare an array list as an
instance of a class, so it's a complex object.
| | 00:31 | I'll start in the empty main
method of this project ArrayList.
| | 00:34 | And I'll begin by typing the
name of the class ArrayList.
| | 00:38 | Remembering that Java is case-
sensitive, ArrayList is spelled with an
| | 00:42 | uppercase A and an uppercase L. The ArrayList
class is not a member of the java.lang package.
| | 00:48 | So you must provide an import
for it at the top of your code.
| | 00:52 | After typing in the name of the class,
press Ctrl+ Spacebar and Eclipse will
| | 00:56 | add the import for you.
| | 00:58 | Eclipse also adds a little bit of
additional notation after the class name.
| | 01:02 | The less than and greater than characters
are sometimes known as the diamond operator.
| | 01:07 | And in Java the diamond operator is
used to declare something called a generic.
| | 01:11 | A generic is a special data type, and
in this context it means this array list
| | 01:17 | will contain items only
of a particular data type.
| | 01:20 | It is possible to create an array list
of mixed data, but most of the time we
| | 01:25 | don't use it for that purpose.
| | 01:26 | Most of the time array lists and other
collections contain items all of the same data type.
| | 01:32 | You declare which data type by simply
setting the data type between the less
| | 01:36 | than and greater than characters, so
this array list could contain integers or
| | 01:41 | can contain shorts or, as I'm going to
do here, it could contain strings or any
| | 01:47 | other complex object.
| | 01:49 | So that's the complete data type
including the generic declaration.
| | 01:53 | This will be an array list of strings.
| | 01:56 | Next as with all declarations I'll
provide the variable name I'll call it list,
| | 02:00 | and then I'll initialize it
using the constructor method.
| | 02:03 | I'll once again type in the name of the
class, this will be a constructor method
| | 02:07 | call, and then I'll press control space
again and I'll choose the version of the
| | 02:12 | array list constructor method
that doesn't receive any arguments.
| | 02:16 | Eclipse looks at the original
declaration, and says you said this was going to
| | 02:20 | be an array list of strings, so when I
call the constructor method, I'm going to
| | 02:25 | use that same string generic
declaration and that's correct, I'll complete the
| | 02:30 | declaration and
initialization with the semicolon.
| | 02:34 | Now I can add items to the list.
| | 02:36 | I said it was going to contain strings,
so anything I pass in must either be a
| | 02:41 | string or be translatable to a string.
| | 02:44 | To add items to the array
list call the add method.
| | 02:47 | There are two versions of the add method,
you can either pass in a value and it
| | 02:52 | will be appended to the end of the
list or you can pass in an integer, an
| | 02:56 | index, and the value and then the item will
be added in the position that you determine.
| | 03:01 | I am just going to use the simple add
version that accepts the string and I am
| | 03:06 | going to add three items to the list,
California, Oregon and Washington.
| | 03:19 | I'm going to output the list to the console.
| | 03:22 | I'll use System.out.printline, and I
am just going to add the list object.
| | 03:29 | The list object will be serialized into
a string for me because its two string
| | 03:33 | method handles that operation automatically.
| | 03:37 | I'll save and run the application,
and I see my items displayed in a comma
| | 03:41 | delimited list wrapped in square
brackets and that's how an array list is
| | 03:46 | translated automatically.
| | 03:49 | Now I'm going to add another item.
| | 03:51 | I'll call list.add and I'll just keep on
moving north, I'll add Alaska, and then
| | 03:57 | I'll copy and paste my print line
command and run the application again.
| | 04:02 | And I see that I've successfully added
an item at runtime, something I wouldn't
| | 04:07 | have been able to do if
this were a simple array.
| | 04:11 | You can add items to an array list at
runtime and you can also remove items.
| | 04:15 | In order to remove items, you can
provide either the index position or an object
| | 04:20 | reference that matches.
| | 04:22 | In the case of strings, you can remove
items simply by providing a matching string.
| | 04:26 | I am going to remove the first item in
the list when I type .remove and press
| | 04:31 | Ctrl+ Spacebar, I see that there are these two
versions of the remove method. It's overloaded.
| | 04:37 | And I'll use the first version.
| | 04:38 | I'll provide an index value of
zero meaning remove the first item.
| | 04:44 | I once again copy and paste my print
line command and I'll output the list.
| | 04:50 | And I'll see that after removing the
first item California I'm left with a list
| | 04:55 | of three items starting with Oregon.
| | 04:59 | Next I'm going to get an item in
a particular position in the list.
| | 05:03 | I'll declare a string variable named state.
| | 05:05 | In order to get an item from the
list, you use the method list.get.
| | 05:10 | You provide an integer value.
| | 05:13 | So I'm going to provide a value of one
remembering that an array list just like
| | 05:17 | a simple array starts its numbering at
| | 05:19 | Zero, this would mean get
the second item in the list.
| | 05:22 | I once again paste in my print
line command and I'll change it.
| | 05:27 | I'll start with the literal "The
second state is" and then I'll append state.
| | 05:35 | I'll save and run, and I get the second
state as Washington and that's correct.
| | 05:41 | You can also find an item in the list.
| | 05:43 | That is, get its index position by
passing an object reference or in the case of
| | 05:48 | strings by passing in the string value.
| | 05:51 | So I am going to declare an integer
variable named pos, and I'll get its value
| | 05:56 | by list.indexOf an I'll pass in Alaska.
| | 06:01 | And then I'll once again use a print
line command and l'll output Alaska is at
| | 06:09 | position and I'll append pos.
| | 06:12 | I'll run the application and I see
Alaska is at position 2, which taking into
| | 06:21 | consideration the zero-based numbering
is at position 2, Oregon position zero,
| | 06:27 | Washington position one, Alaska position 2.
| | 06:31 | Take a look at the documentation of
the array list for more information about
| | 06:35 | how you can use this powerful class.
| | 06:38 | I'll double click the name of the
class in my code and go to Dynamic Help and
| | 06:43 | click the link for its javadocs, expand
the help view and then go to the method list.
| | 06:50 | You'll see that there are methods in
they are not just for adding removing
| | 06:53 | and searching, but also for getting
the size of the array list and managing
| | 06:57 | how it uses its memory.
| | 06:59 | Use array list to manage ordered
collections of data, or you need to resize the
| | 07:04 | collection at runtime, and where you
need to be able to add remove and search
| | 07:08 | for items, it's an incredibly
powerful class that does much more than the simple array.
| | Collapse this transcript |
| Managing unordered data with HashMap| 00:00 | Most programming languages have the
ability to store unordered collections of
| | 00:04 | data where you can randomly access
items in the collection by their keys.
| | 00:09 | In some languages these are known as
associative arrays, in others structures.
| | 00:14 | But they always serve the same purpose,
an unordered collection of data where
| | 00:18 | you can get to one item at a time.
| | 00:21 | In Java, we do this with a class called the
HashMap, just like the array list it's a class.
| | 00:27 | And when you declare it you have to import it.
| | 00:29 | I'll start in this empty main method in
the project HashMap and I'll declare an
| | 00:34 | instance of the HashMap class.
| | 00:37 | I'll type in the name of the
class and press control space.
| | 00:40 | Eclipse recognizes that this class
must be imported and it adds the import at
| | 00:45 | the top of the code.
| | 00:47 | Just as with the array list the
HashMap is designed to store data all of the
| | 00:51 | same type but where the array list
means one data type, the HashMap needs two.
| | 00:57 | Each item in a HashMap
will have a key and a value.
| | 01:01 | Notice that these are represented in
the Diamond Operator that is where the
| | 01:04 | generic is declared using the letters K and V.
| | 01:08 | In some languages the key always has
to be a string, but in Java you can
| | 01:13 | really use any object.
| | 01:15 | For simplicity though in this
exercise I'll declare both my keys and my
| | 01:19 | values to be strings.
| | 01:20 | So I'll type in String, press tab and
type String again and then I'll declare
| | 01:27 | the variable name, map.
| | 01:29 | Next, I'll instantiate the class.
| | 01:31 | I'll type in the code = new then once
again I'll type the name of the class and
| | 01:36 | press control space.
| | 01:38 | There are four different versions of
the constructor method for HashMap.
| | 01:42 | There is one with no arguments, there is
one with an initial capacity, and there
| | 01:47 | are a couple that let you
initialize the object in other ways.
| | 01:50 | I'm going to choose the
simplest the one with no arguments.
| | 01:53 | Eclipse looks at my original declaration
and matches my constructor method call.
| | 01:58 | Now the codes get in little
wide so I'll maximize my editor.
| | 02:02 | I'll add the semicolon at the end of the
line and now I've created my first HashMap.
| | 02:08 | In order to add items to the
HashMap use the method named put.
| | 02:14 | I'll call map.put and I'll see that
there's only one version of the put method.
| | 02:19 | It requires two values,
in this case two strings.
| | 02:23 | And once again using the names of
states, I am going to use the name of the
| | 02:27 | state as the key and its capital as the value.
| | 02:31 | So I'll type in California then
tab over and type in Sacramento.
| | 02:40 | I'll add another item to the map this
will have a state name of Oregon and a
| | 02:46 | capital of Salem and finally
I'll add Washington and Olympia.
| | 02:56 | Now I'd like to output the
contents of the map to the command line.
| | 03:00 | Just as with the array list, the
HashMap has a two string method that will
| | 03:04 | serialize its contents so it's easy to read.
| | 03:06 | So I'll use System.out.println
and just pass in the map object.
| | 03:12 | I'll save and run my
application and there is the results.
| | 03:17 | Each item contains a key and a value
separated by the equals operator and the
| | 03:23 | entire list is wrapped in curly braces.
| | 03:27 | Just as with array lists,
HashMaps are resizable at runtime.
| | 03:31 | So I'll add in yet another State Alaska
and its capital Juneau and I'll copy and
| | 03:40 | paste my printline command.
| | 03:43 | I'll organize my codes, so that it's
all grouped together correctly, and I'll
| | 03:49 | run the application and there you see
that I am successfully adding an item.
| | 03:54 | You can find an item in a
map by referring to the key.
| | 03:58 | So for example, let's say that I
wanted to find the capital of Oregon.
| | 04:03 | I'll declare a string variable, I'll
call it cap and I'll call map.get and I
| | 04:09 | will pass in the key Oregon.
| | 04:14 | And then I'll use of printline command
and I'll say the capitol of Oregon is and
| | 04:23 | I'll output the value of cap.
| | 04:26 | And I'll run the code and I get the
capitol of Oregon is Salem, that's correct.
| | 04:31 | Now once again as I mentioned this
second item in the HashMap does not have to
| | 04:35 | be a string, it could be
any kind of complex object.
| | 04:39 | And as you get into creating your
own custom classes that represent data,
| | 04:43 | you'll find that HashMaps are very useful for
storing large collections of data in memory.
| | 04:49 | Next, I am going to remove an item.
| | 04:52 | With the array list you removed an
item by its index position, but remember a
| | 04:56 | HashMap isn't in any particular order.
| | 04:58 | So if you want to remove an
item, you refer to its key.
| | 05:02 | So I'll call map.remove and I'll pass
in California and I'll print out the map,
| | 05:10 | and I've removed California and I'm
left with the three remaining states.
| | 05:15 | Take a look at the documentation for
the HashMap class to learn more about it.
| | 05:20 | I'll select the name of the class and
go to Dynamic Help, click for the javadoc
| | 05:24 | and maximize and go to the method list.
| | 05:27 | You'll see that there are methods to
determine whether a particular item is
| | 05:30 | available in the list.
| | 05:32 | Those methods are name
contains key and contains value.
| | 05:35 | There is a method for determining
whether the HashMap is empty, it's called
| | 05:39 | isEmpty and returns a Boolean.
| | 05:41 | There's put methods, a putAll method,
size methods and values methods.
| | 05:47 | I'll show you how to use a couple of
these other methods in a later video when
| | 05:51 | I show you how to loop through the HashMap
using something called an iterator object.
| | 05:56 | But this should give you enough
information to get started with HashMaps storing
| | 06:01 | unordered data collections
in your Java applications.
| | Collapse this transcript |
| Looping through collections with iterators| 00:00 | When you loop through a simple array in
Java, you typically use a for loop and a
| | 00:04 | counter variable or a foreach loop.
| | 00:07 | If you're using the counter variable
approach, you increment that variable once
| | 00:11 | each time through the loop and
then use that as an index value.
| | 00:15 | You could do that with an array list,
but the array list and the HashMap
| | 00:19 | both have more elegant approaches available
for iterating or looping through their contents.
| | 00:24 | There's a pattern called an iterator,
an iterator is a special Java class
| | 00:29 | that's designed to allow you to loop
without having to keep track of internal
| | 00:33 | numbering yourself.
| | 00:34 | I'll show you how to use iterators on
both the array list and the HashMap.
| | 00:39 | I'm working in a project called
iterators, which is a part of this
| | 00:42 | chapter's exercise files.
| | 00:44 | The beginning code for this
application declares an array list named list and
| | 00:49 | a HashMap named Map.
| | 00:51 | Items are added to each of the objects, and
then the objects are output to the Console.
| | 00:55 | I'll run the application and show the results.
| | 01:00 | Now because these classes are not
members of java.lang, at the top of the class
| | 01:04 | you'll see these import
statements, these are critical.
| | 01:08 | Now, I'll show you how to create
an iterator from an array list.
| | 01:12 | The first step is that you need to know
what kind of class you're going to be getting.
| | 01:16 | For an array list, the iterator is
called a list iterator and there was a
| | 01:21 | special class for it.
| | 01:23 | I'll declare a class named ListIterator,
notice that there are two available,
| | 01:27 | I'll choose the one from java.util.
| | 01:30 | And when I declare the data type, just
like the array list, I need to declare
| | 01:34 | the data type of its values.
| | 01:36 | In this case, it will be string.
| | 01:41 | I'll give this variable a name of
listIterator with a lowercase initial character.
| | 01:47 | Now to populate its value, I'll call the
array list objects listIterator method,
| | 01:53 | this returns the iterator
that references the list values.
| | 01:57 | I now have an object that I can use
to easily loop through the values.
| | 02:01 | Next I'll use a while loop, I'll type
in the keyword while and press control
| | 02:06 | space and I'll choose this
version while loop with condition.
| | 02:11 | It's up to me to
determine what that condition is.
| | 02:15 | The listIterator object
has a method called hasNext.
| | 02:18 | As long as there is an available next
item in the collection, it will return true.
| | 02:23 | When I have dealt with the last item
in the collection, it will return false.
| | 02:27 | So my condition will be listIterator.hasNext.
| | 02:33 | Within the code block for the while loop,
I'll now create a string variable and
| | 02:38 | I'll give it a variable name, value.
| | 02:41 | And in order to get the next
item from the iterator, I use this
| | 02:44 | code listIterator.next.
| | 02:48 | When you call the next method, it moves
internally to the next item within the
| | 02:53 | iterator and the collection and it
returns a reference to the value.
| | 02:57 | If it's complex object,
it's a reference to the object.
| | 03:00 | Now I can output the value.
| | 03:03 | I'll use System.out.println and just value.
| | 03:08 | So that's how use the listIterator when
you're working with an array list object.
| | 03:12 | I'll run the application and show
that it's outputting in turn California,
| | 03:16 | Oregon and Washington.
| | 03:19 | Because I started from an array list
which is an ordered collection, it's
| | 03:23 | guaranteed that I'll be looping
through in the order in which the items were
| | 03:26 | placed into the list.
| | 03:28 | So now I'll show you how to do
something fairly similar with a HashMap.
| | 03:32 | Remember that this HashMap has two
sets of strings, the keys and the values.
| | 03:38 | You can iterate through either.
| | 03:40 | But I'm going to focus on iterating
through the keys because once you have a
| | 03:43 | key, you can get to the value.
| | 03:46 | With an array list, it's a single
step to get to the iterator you need.
| | 03:49 | But with a HashMap it's two steps.
| | 03:52 | The first step is to get the collection
of strings that you want to loop through
| | 03:56 | and the second step is to get the iterator.
| | 03:59 | With the HashMap class you can either
get the values using the method values or
| | 04:04 | you can get a set of values called a
key set and that would be the set of keys
| | 04:09 | California, Oregon and Washington.
| | 04:11 | When you get the keys, they'll
end up in an object called a Set.
| | 04:15 | Type in the word Set and press Ctrl+
Spacebar and choose the set class from java.util.
| | 04:21 | And as with all classes in the collections
framework set the data type, I'll set it to string.
| | 04:27 | Now to populate that set
of values called map.keySet.
| | 04:31 | Now as I've been typing, I should've been
getting import statements at the top of the code.
| | 04:37 | If you aren't getting your import
statements for any reason, you can easily fix
| | 04:41 | that by pressing Ctrl + Shift + O on
Windows or Command + shift + O on Mac, and
| | 04:47 | Eclipse will fix up your imports
making sure you have the ones you need and
| | 04:51 | putting them in the right order.
| | 04:53 | Now let's go back to the code.
| | 04:55 | I'm missing my variable name
here and I'll just call it keys.
| | 04:59 | Okay now I'm ready to create my iterator.
| | 05:02 | When you're working with a set, and
you want to iterate through its values,
| | 05:06 | instead of getting a list iterator
you'll get a class simply named iterator.
| | 05:10 | At this point, you might be
asking how do I know this?
| | 05:14 | And the answer is it's in the documentation.
| | 05:17 | Remember that because Java is so
strongly typed, every bit of documentation will
| | 05:21 | tell you exactly what you're getting.
| | 05:23 | So I'm going to create a class
which is data type as an iterator.
| | 05:28 | Again make sure you choose the right
version, this one should be from java.util,
| | 05:33 | set the data type, and set the
variable name, I'll call it iterator.
| | 05:38 | And then get the value of the
iterator from keys.iterator the method.
| | 05:43 | Now I'm ready to loop.
| | 05:45 | I'll go to the next line and type while
and press Ctrl+ Spacebar once again I'll
| | 05:51 | choose while loop with condition.
| | 05:53 | And the programming interfaces of the
iterator and the list iterator are exactly the same.
| | 05:59 | So I'll be able to use while iterator.hasNext.
| | 06:06 | And within the while loop, I'll once
again declare a string, I'll set its
| | 06:10 | name to a value, I'll get its value
from iterator.next, again following
| | 06:15 | exactly the same syntax that I did
with the listIterator and then I'll output
| | 06:20 | the value System.out.println.
| | 06:26 | I'll run the application and I get
California, Oregon and Washington.
| | 06:31 | But remember, those key values came
from a HashMap, but remember those strings
| | 06:37 | are keys in a HashMap and each key has
an associated value, so I'm going to do
| | 06:43 | this with a little bit more complexity.
| | 06:45 | I'll expand my editor, so I have a
little bit more width to work with, and I'll
| | 06:50 | add before the value the capital of,
and then the value, and then after that I
| | 06:59 | add another plus operator and a space
is, and then after another space and
| | 07:05 | another quote, another plus
operator and then map.get(value).
| | 07:13 | So the whole purpose of this was to
loop through the keys, so that I could then
| | 07:17 | address the keys and their associated
values, here is the result the capitol of
| | 07:22 | California is Sacramento and so on.
| | 07:26 | Iterators always work on
collections of single values.
| | 07:30 | When you're working with a HashMap
you're working with a collection of keys
| | 07:33 | and associated values.
| | 07:35 | So the first step is to extract the
keys and the next step is to get the
| | 07:39 | iterator so you can loop through the contents.
| | 07:42 | Iterators are a valuable part of what's
known as the collections framework in Java.
| | 07:47 | They're designed to make it very easy
to loop through the contents of your data
| | 07:51 | in memory without having to keep track
of your own numeric counter variables or
| | 07:56 | use your own handcrafted strategies.
| | Collapse this transcript |
|
|
9. Creating Custom ClassesUnderstanding encapsulation| 00:00 | The principles of object-oriented
programming depend on a few basic concepts and
| | 00:05 | one of the most important
concepts is encapsulation.
| | 00:08 | Encapsulation means that you're packaging
complex functionality to make it easy to use.
| | 00:14 | When you first create Java applications,
most new programmers will put all of
| | 00:18 | their code into the main method, and
I've been doing that so far in this course.
| | 00:23 | But you quickly find out as your
applications get larger and gain features that
| | 00:27 | putting all the code into one place
makes that code very tough to manage.
| | 00:32 | So instead, you want to break the code
out into individual classes, grouping the
| | 00:37 | functionality, however, the
logic dictates for your application.
| | 00:41 | When you do this, you have some big advantages.
| | 00:44 | One advantage is that you can
restrict access, one part of the application
| | 00:48 | might be able to use a particular
function or another part of the application
| | 00:51 | wouldn't be allowed.
| | 00:53 | If you put all the code in one
place, that's tough to restrict.
| | 00:56 | When you break it apart, it's easier.
| | 00:59 | Similarly, when you store data in
a Java class, if you wrap it up as
| | 01:04 | encapsulated data, you have the
option of hiding how it's being stored.
| | 01:09 | You don't have to tell the user of the
data, that is a programmer who's calling
| | 01:13 | a particular class, whether that data
is being stored as an array, a collection
| | 01:18 | of some kind, or any other object.
| | 01:21 | You simply provide methods that the
user of that class can call and all the
| | 01:25 | complexity is hidden.
| | 01:26 | One way to think about encapsulation is
to look at an analogy of the 3D world.
| | 01:32 | Let's take an example of an industrial
machine, in this case, an olive press.
| | 01:37 | In order to use an olive press, if you
were asked to know everything about how
| | 01:41 | the press worked, it would be
very difficult to get started.
| | 01:45 | If you had to know which direction each
gear was going to turn, which order each
| | 01:49 | of the pressing arms is going to come
down, and how much oil might come out of
| | 01:53 | each individual olive, it would be very
difficult to get any work done at all.
| | 01:57 | So most real industrial machines are
encapsulated and that means that they wrap
| | 02:03 | up their complexity in a big box and
then you can simply add the olives in the
| | 02:08 | case of an olive press, perhaps press
a button and out comes the olive oil.
| | 02:13 | It's much easier for a new user to
understand how to use the olive press.
| | 02:18 | There is still complexity, there are
still gears, there are still pressing arms,
| | 02:22 | there are still calculations to be
done, but the whole process of getting
| | 02:26 | started with the machine is greatly simplified.
| | 02:28 | Code-encapsulation works the same way.
| | 02:32 | Let's take an example of non-encapsulated code.
| | 02:35 | Again, if you're a new Java developer,
you might be tempted to put all the code
| | 02:39 | for the application in the
main method of your primary class.
| | 02:43 | In this example, I'm creating an array
and then I'm creating instances of two
| | 02:48 | other classes, and then I'm looping
through the array and doing something with it.
| | 02:53 | This little bit of code might not
look too daunting but imagine if the code
| | 02:57 | had expanded so you had literally hundreds or
thousands of lines of code all in one place.
| | 03:04 | Then somebody comes along and says
would you add a new feature to the
| | 03:07 | application or I found a
bug and it needs to be fixed.
| | 03:11 | This sort of monolithic code is
very, very difficult to manage.
| | 03:15 | So in Java applications, you're
encouraged from the beginning to break your
| | 03:19 | applications down into small pieces.
| | 03:22 | So for example, I may take some of that
code and move it off into its own custom class.
| | 03:28 | I might create a class called OlivePress.
| | 03:31 | Within the OlivePress class, I might
declare a private field or a private variable.
| | 03:37 | In this case, it's an array of olive
objects named olives, and then I might
| | 03:42 | have a constructor method that allows
me to pass that data in as I create an
| | 03:46 | instance of the class.
| | 03:48 | Then I might have a method called getOil that
can be called from anywhere in the application.
| | 03:53 | This method would encapsulate the
complexity of how you have to loop through the
| | 03:57 | list of olives, crush them
and add them to the olive oil.
| | 04:01 | The developer of this class needs to
understand and deal with the complexity,
| | 04:06 | but the user of the class only has to
call the getOil method and so the primary
| | 04:11 | code of the application can now be
very brief and very easy to read.
| | 04:15 | I would create an instance of the
OlivePress, I'd pass in my olives, I'd call
| | 04:20 | the getOil method and I get back the oil.
| | 04:23 | All of the mechanics and the complexity of how
the operation happened would be hidden from me.
| | 04:29 | All I need to know is call
the method, get the result.
| | 04:33 | So that's how encapsulation works.
| | 04:35 | The benefits of encapsulation include
that you can break your functionality down
| | 04:40 | into small maintainable units.
| | 04:42 | It's much easier to fix bugs when
you're looking at a small amount of code and
| | 04:47 | much more difficult when you're
looking at a massive amount of code.
| | 04:51 | So encapsulation helps you maintain
the application over the long-term.
| | 04:55 | You can also use encapsulation to
group functionality and data together.
| | 04:59 | In Java, as with most object-oriented
languages, you can define classes that
| | 05:04 | group the data and the functionality
that manages that data together or you can
| | 05:09 | create individual classes;
| | 05:11 | one for the data, one for the
functionality, and bind them together using a
| | 05:15 | process called loose coupling.
| | 05:18 | And finally, all of this together
means that you can test your software and
| | 05:23 | maintain it over the long-
term at a granular level.
| | 05:26 | Rather than looking at your
application as one huge block of code, you're
| | 05:31 | breaking it down into small manageable pieces.
| | 05:34 | So in the rest of this chapter, I'm going
to talk about the mechanics of this in Java.
| | 05:39 | How do you create your own custom classes?
| | 05:42 | How do you move code from a
monolithic application and break it down
| | 05:45 | into smaller pieces?
| | 05:47 | And how do you declare classes that
serve as utility libraries or that are
| | 05:52 | their own custom classes that can be
instantiated and seen as data objects all on their own?
| | Collapse this transcript |
| Creating and instantiating custom classes| 00:00 | Complete applications in Java
typically consist of more than one class.
| | 00:05 | You'll have a starting class that has
the main method for a console application,
| | 00:09 | but then you have all sorts of
supporting classes that either encapsulates data
| | 00:13 | or functionality or both.
| | 00:15 | For this exercise, I'll show you a
simple strategy for taking an application
| | 00:20 | where all the code is in a single class
or a single file and extracting it out
| | 00:25 | to multiple files, so it's
easier to keep track of and maintain.
| | 00:29 | I'll start with this
beginning Calculator application.
| | 00:32 | This is a version of the Calculator
application that I worked on in a previous
| | 00:35 | chapter of the course.
| | 00:37 | It accepts two numeric values and then
asks the user what operation they want to do;
| | 00:42 | addition, subtraction, and so on.
| | 00:44 | Right now, all of the code for
the application is in a single file.
| | 00:48 | There is code to get the input and to
figure out what to do, but then all of the
| | 00:53 | supporting methods are
also in the primary class.
| | 00:56 | In a well-structured Java application,
you would extract a lot of this code out
| | 01:00 | to separate classes.
| | 01:02 | It's up to you as the developer and
the application architect to figure out
| | 01:06 | where the code goes and
how to group it together.
| | 01:09 | I'll show you a strategy for this
application, where I take all of the
| | 01:12 | mathematical operations and group them
together into one class and then I'll
| | 01:16 | take the functionality that's
accepting input from the command line and put
| | 01:20 | it into another class.
| | 01:21 | The goal will be to create
classes that are reusable.
| | 01:25 | I'll start in the CustomClasses project
and I'm going to create two new classes.
| | 01:30 | I'll right-click on the
default package and choose New>Class.
| | 01:35 | The first class will be SimpleMath.
| | 01:38 | You could name the class anything you
want, but make sure you use an uppercase
| | 01:42 | initial character and that you don't
put in any spaces or special characters.
| | 01:47 | This will not be the starting class so
don't check the option to create a main method.
| | 01:52 | You'll only be able to call this class
from other classes of the application.
| | 01:57 | Click Finish, and you end up
with a very simple class structure.
| | 02:02 | The class is public and the name is SimpleMath.
| | 02:06 | When you declare your own classes, the
name of the public class must match the
| | 02:11 | name of the Java file and you can only
have one public class in each Java file.
| | 02:16 | It is possible to declare multiple
classes in a single Java file, but any other
| | 02:21 | classes can't be public and will only be
accessible from within the code in this file.
| | 02:25 | I am going to have just one class in
this file and I'm going to put all of my
| | 02:29 | mathematical operation methods into it.
| | 02:32 | So I'll go back to the application, I'll
scroll down, and I'll locate my divide,
| | 02:37 | multiply, subtract, and add methods.
| | 02:40 | I'll select all four of them and
I'll cut them to the clipboard.
| | 02:44 | Then I'll go to SimpleMath.java,
I'll place the cursor inside the class
| | 02:49 | declaration, and paste in the methods.
| | 02:55 | Now because I'm going to be calling
these methods from another class, I can no
| | 02:58 | longer have them marked as private.
| | 03:01 | They must be marked public or I can
just remove the access modifier entirely.
| | 03:06 | I like to be explicit in my access
modifiers though, so I am going to change
| | 03:09 | private to public on all four methods.
| | 03:12 | I'll save my changes to this file and
go back to the application, and now I'll
| | 03:24 | go to the switch statement
where I'm calling those methods.
| | 03:27 | I now have errors telling me
that these methods are undefined.
| | 03:31 | I'll fix this by adding the name of
the class SimpleMath as a prefix to the
| | 03:37 | call to the method.
| | 03:39 | I'll type Simp and press Ctrl+Space
and there is my new class, SimpleMath.
| | 03:44 | I'll separate the name of the
class and the method name with a dot.
| | 03:48 | Notice when I type in the dot,
the four available methods are shown
| | 03:52 | automatically and I can
easily call them where needed.
| | 03:55 | Now I am going to copy SimpleMath and
the dot to the clipboard, and I'll paste
| | 04:00 | that string in to each of
the other three method calls.
| | 04:03 | I'll save my changes and I'll run the
application, I'll enter a value, I'll
| | 04:10 | enter another value, I'll choose
subtraction this time, and everything still works.
| | 04:17 | So now I've successfully
refactored my application.
| | 04:21 | I've extracted the code that's not a
part of the main operation and put it in
| | 04:24 | its own separate class.
| | 04:26 | Let's do the same thing with the input function.
| | 04:29 | Once again, I'm going to create a
new class, I'll right click and choose
| | 04:33 | New>Class, and I'll call this InputHelper.
| | 04:38 | Once again making sure I don't have the
main method selected, I'll click Finish.
| | 04:42 | I'll go back to the main application,
I'll scroll down to the bottom and I'll
| | 04:47 | grab this getInput method, make sure
you get all of the method including the
| | 04:51 | opening and closing braces, I'll cut
that code to the clipboard, I'll go to my
| | 04:57 | new class, place the cursor inside
the class declaration, and paste.
| | 05:02 | Notice that when I paste the code
into the new class, Eclipse automatically
| | 05:06 | adds import statements for the
BufferedReader and InputStreamReader classes that I need.
| | 05:12 | Just as I did with the methods in the
SimpleMath class, I'll change this access
| | 05:16 | modifier from private to public.
| | 05:18 | I'll save my changes to this file and
go back to the main application, and I'll
| | 05:23 | go up to the calls to the getInput method.
| | 05:25 | I'll type in input and press Ctrl+
Space and I'll choose my new class,
| | 05:31 | InputHelper and add the dot.
| | 05:34 | I'll select and copy the InputHelper
.string and paste that in twice and
| | 05:42 | I'll save my changes.
| | 05:44 | Down to the bottom, I get a warning,
The import java.io is never used.
| | 05:49 | That import statement was handling the
classes that deal with input, but because
| | 05:54 | I've moved the usage of those classes
into my own separate custom class, I no
| | 05:58 | longer need the import statement.
| | 06:00 | I can either delete it explicitly
or I can let Eclipse do it for me.
| | 06:04 | To do it in Eclipse, hold down the
Ctrl and Shift keys on Windows or the
| | 06:09 | Command and Shift keys on Mac and
press the letter O, and that is something
| | 06:13 | called organizing imports.
| | 06:16 | That's a great trick, because it will
not only get rid of the imports that you
| | 06:20 | don't need, but it will also add or
propose the imports that you do need and
| | 06:25 | alphabetize and otherwise organize them for you.
| | 06:27 | I'll save my changes and run the
application again and I'll test it again with
| | 06:32 | values of 10, 3 and this time I'll
multiply and everything still works.
| | 06:41 | By organizing your application in
smaller classes, it makes it easier to
| | 06:45 | maintain your work over time, and
you'll be tempted to tune and refactor your
| | 06:50 | application as you go along.
| | 06:52 | Eclipse will help you with this in many ways.
| | 06:55 | Let's say, for example, that you end
up not liking the name of this class
| | 06:59 | SimpleMath, and you think well, I'd
like to change the name of that class so
| | 07:03 | that it matches InputHelper, I'd
like it really to be named MathHelper.
| | 07:07 | But it would be a real pain to go
through and try to search and replace for
| | 07:10 | every occurrence of this class name.
| | 07:12 | I have it here and I have it
four times in the main method.
| | 07:15 | Well, this kind of class
renaming is called refactoring and it's
| | 07:19 | incredibly simple in Eclipse.
| | 07:22 | Go to the class in your package Explorer,
right click, choose Refactor and then Rename.
| | 07:30 | Assign the new name of the class
and I'm going to call it MathHelper.
| | 07:35 | Then click Finish and you'll see that
the name of the class is updated in all
| | 07:39 | the calls in the main application, the
name of the file is changed, and the name
| | 07:45 | of the class in the class
declaration is changed as well.
| | 07:48 | At the minimum, you can use your custom
classes to organize the code, bringing
| | 07:53 | together methods that execute similar
operations and moving them out of the main
| | 07:57 | application file that has your main method.
| | 08:00 | How you design the application and how
you separate the code is completely up to
| | 08:05 | you, but Java gives you all the tools to do it.
| | Collapse this transcript |
| Organizing classes with packages| 00:00 | So far in this course, I've been
creating applications where every class
| | 00:04 | was placed in the root folder of
its project, but Java developers very
| | 00:08 | seldom actually do that.
| | 00:10 | Most classes in a Java application are
placed in packages or subfolders of the project.
| | 00:16 | Because of the way Java application is
structured it could have dozens, hundreds
| | 00:20 | or even thousands of classes, and as
an application gets larger it's very
| | 00:25 | important to organize these classes into groups.
| | 00:27 | We call these groups packages but they
represent actual physical folders on disk.
| | 00:33 | I'm going to start by creating a sub
package to store my helper classes.
| | 00:37 | I'm working in a version of the
Calculator application where all of the classes
| | 00:41 | are stored in the root folder or default
package and I'm first going to create a
| | 00:45 | custom package and then
move my helper classes into it.
| | 00:49 | I'll go to the default package in
the package Explorer view, right-click
| | 00:54 | and choose New>Package.
| | 00:56 | Initially, I'm going to use a
shallow package structure meaning that each
| | 01:00 | package will be just a subfolder of the root.
| | 01:03 | So I'm going to call this package, helpers.
| | 01:07 | Now, when I create a package in
Eclipse, I am actually creating a physical
| | 01:11 | folder on disk as well.
| | 01:13 | Next, I'm going to move my helper
classes into the helpers package.
| | 01:17 | I'll do this one at a time.
| | 01:19 | I'll start with InputHelper.java,
I'll right-click on the file and I'll
| | 01:24 | choose Refactor>Move.
| | 01:27 | I'll select my new helpers package and click OK.
| | 01:31 | The file is moved into the package and a
couple of changes are made to the code.
| | 01:36 | First of all, in the InputHelper.java
file, a new package declaration is added
| | 01:41 | to the top of the file.
| | 01:43 | This is a requirement in Java.
| | 01:45 | When a class is anywhere but the default
package, it has to be declared that way in the code.
| | 01:51 | The syntax is the keyword package and then
the name of the package ending with a semicolon.
| | 01:57 | Also, in the main application, where
I am using that class, a new import
| | 02:01 | statement has been added
to the top of that code.
| | 02:04 | Once again, this is a requirement.
| | 02:06 | If the class isn't a member of the
same package as the one that's calling it,
| | 02:09 | then it has to be imported.
| | 02:12 | In this case, I am referring not just
to the package but also the class name,
| | 02:16 | helpers.InputHelper.
| | 02:18 | Now I'll move my second helper class.
| | 02:21 | I'll go to MathHelper.java in the
package Explorer, right-click and choose
| | 02:25 | Refactor>Move and once again, I'll
choose the helpers package and click OK.
| | 02:32 | My main application now has imports for
both helper classes and both InputHelper
| | 02:37 | and MathHelper have the package declaration.
| | 02:41 | I'll run the application, I'll click
the Run button and if prompted, I'll
| | 02:45 | choose Java Application.
| | 02:48 | I'll enter some values and an
operation and everything is working just fine.
| | 02:53 | So organizing your classes into
packages doesn't do anything to change the
| | 02:56 | functionality for application;
| | 02:59 | it just gives you a way of organizing the
code so you can find it more easily later on.
| | 03:03 | In large scale Java development
environments package names typically are
| | 03:07 | structured using a prefix of the
company's domain in reverse domain order.
| | 03:12 | So for example, if a company is named
lynda.com then you would start off with a
| | 03:17 | package prefix of com.lynda.
| | 03:20 | The reason to do this is so that you
can eliminate any possible conflicts with
| | 03:24 | other classes in the Java environment.
| | 03:27 | Remember that Java compilation
doesn't create a single monolithic file.
| | 03:32 | Instead your runtime application
consists of a whole bunch of compiled classes
| | 03:37 | and it's up to the JVM to figure
out which classes needed at runtime.
| | 03:41 | By using reverse domain
notation in your classes, you guarantee
| | 03:44 | universal uniqueness.
| | 03:46 | So I'm going to do a
little bit more refactoring.
| | 03:49 | I'll go to my default package and once
again I'll add a new package, and I'll
| | 03:53 | name this package com.lynda.calc.
| | 03:56 | So I start off with the domain name
first and then something to say which
| | 04:01 | application I'm working on.
| | 04:02 | You can add more levels to
your packages, it's up to you.
| | 04:05 | I'll click Finish, then I'll go to my
Calculator class, I'll right click and
| | 04:12 | choose Refactor>Move and
I'll choose com.lynda.calc.
| | 04:17 | Notice that because I have dot
notation, each of these is seen as its
| | 04:21 | own individual package.
| | 04:23 | I won't be placing anything in com or com.lynda;
| | 04:27 | those are just prefixes for
the way I am organizing my code.
| | 04:30 | But my main class will go in this calc package.
| | 04:34 | I'll click OK and my source code file is
moved and I'll look at my code and I'll
| | 04:39 | see that the package declaration
has been added at the top of the code.
| | 04:44 | Next, I'll rename my helpers
package, I'll right-click, I'll choose
| | 04:49 | Refactor>Rename and I'll change the
package name to com.lynda.calc.helpers.
| | 04:56 | I am still distinguishing this package
from the package that contains my main
| | 05:01 | application and keeping all my helper
classes in their own unique package.
| | 05:05 | But they're all deeply buried now
in my uniquely named primary package.
| | 05:11 | This time I'll choose Preview and show
you that Eclipse can show you what your
| | 05:15 | code will look like
before and after refactoring.
| | 05:19 | I'll click OK and the change is made.
| | 05:23 | My main application still has the imports for
the two classes, InputHelper and MathHelper.
| | 05:28 | If I prefer, I can change these and
just put in an asterisk and take out the
| | 05:33 | second import, and this now means
import everything in that package.
| | 05:39 | If you have classes in the package
that you're not using that's okay;
| | 05:43 | it won't affect performance.
| | 05:45 | But note that if you use the Organize
Imports tool in Eclipse that's the tool
| | 05:49 | that kicks in when you press Ctrl+Shift+
O on Windows or Command+Shift+O on Mac,
| | 05:54 | Eclipse will convert from an asterisk ,
a wildcard import to explicit imports
| | 05:59 | for each class that you're using.
| | 06:01 | That's the preferred approach for Java
development because it helps you know
| | 06:05 | by looking at the top of your code
exactly which classes are actually in use
| | 06:09 | in your application.
| | 06:11 | I'll go take look at the InputHelper
and MathHelper classes and I'll see that
| | 06:16 | the package declarations
have been modified there.
| | 06:19 | And finally, I'll save everything and
run the application again and make sure I
| | 06:22 | haven't broken anything.
| | 06:24 | I'll enter the numeric value and
another numeric value and this time, I'll
| | 06:29 | multiply and I get back a correct answer.
| | 06:33 | So, organizing your coding
packages is a good thing to do.
| | 06:37 | As your applications become larger
and more complex and you have more and
| | 06:41 | more classes, you'll find organization
of your classes through packages to be invaluable.
| | Collapse this transcript |
| Creating and using instance methods | 00:00 | When you declare a method in a Java
application, you can declare it either as a
| | 00:05 | class method or an instance method.
| | 00:07 | A class method is a method like the
ones I've been using so far, it's called
| | 00:11 | from the definition of the class.
| | 00:13 | An instance method in contrast is called
from an instance of the class or an object.
| | 00:18 | Typically, you can use class methods
when you're building up a library, say, of
| | 00:22 | utility functions and you are going to
pass in all the values that the method is
| | 00:26 | going to operate on as arguments
passed into the method when it's called.
| | 00:30 | But when you start working with
more complex objects, objects that have
| | 00:33 | persistent data in them, you are going to
want to learn how to use instance methods.
| | 00:38 | For this exercise, I'm working a project
named InstanceMethods that has three classes.
| | 00:43 | All three classes are starting off pretty empty.
| | 00:46 | The Main class has a main method
that doesn't do anything yet and there's
| | 00:49 | an OlivePress class and an Olive class, and
again, they don't have any functionality yet.
| | 00:55 | I'm going to design this Olive class so
that it can be instantiated and then its
| | 01:00 | methods can be called.
| | 01:01 | I'll place the cursor
inside the class declaration.
| | 01:04 | To define in the instance method, you
use the same sort of signature as you do
| | 01:08 | with a class method, but you
don't put in the static keyword.
| | 01:12 | Remember, the Main method has this
word, static, and all of the methods
| | 01:15 | that I've defined throughout this course up
to this point have also used the word static.
| | 01:20 | The word static means this is a class method
that can be called from the class definition.
| | 01:25 | If you drop out the word,
static, it's an instance method.
| | 01:28 | Just as with class method you
start with an access modifier;
| | 01:31 | public if you want to method to be
called from anywhere in the application;
| | 01:35 | private if it's only available within the class;
| | 01:37 | and protected if it's available
within this class or any of its subclasses.
| | 01:42 | I'll declare this method as public.
| | 01:44 | Next you need a return type.
| | 01:46 | Initially, this method will return
void or nothing and then the method name
| | 01:50 | which I'll call crush.
| | 01:52 | Add in the parentheses at the end of
the method name and a pair of braces and
| | 01:56 | now you can add code to implement the method.
| | 01:58 | When an Olive is crushed, we'll
say it hurts, so the Olive says ouch.
| | 02:02 | So I'll output using system.out.println
the word ouch and I'll save my changes
| | 02:09 | and that's my first instance method.
| | 02:11 | Now I'll go back to the main application.
| | 02:14 | Within the main application, in order
to call that method, I need to create an
| | 02:18 | instance of the Olive class.
| | 02:20 | So I'll declare a variable.
| | 02:22 | I'll assign a data type of
Olive, the name of the class.
| | 02:25 | Notice that as I type the name of the
class, I get the little squiggly line
| | 02:28 | underneath the class name and that
tells me that the class currently is
| | 02:32 | being seen as undefined.
| | 02:33 | The compiler doesn't know where it is.
| | 02:36 | So I'll press Ctrl+Space, I'll see a
listing of all the classes that start with
| | 02:40 | the word Olive and I'll choose Olive.
| | 02:42 | An Eclipse adds a required import
statement at the top of the code.
| | 02:45 | Even though this is my own class and my
own application, the rules for imports
| | 02:50 | are the same as with the Java class library.
| | 02:52 | If the class that I'm using is in a
package other than the one that contains the
| | 02:56 | current class, I must import it.
| | 02:58 | Next, I'll declare the variable name
which I'll set as olive, all lowercase, and
| | 03:03 | I'll instantiate using new Olive.
| | 03:06 | Now you may be thinking where is that method.
| | 03:09 | If I go back to Olive.java notice that
there is no definition of a constructor
| | 03:14 | method or any other method
that matches the class name.
| | 03:17 | The answer is that the Java compiler
always adds a no arguments constructor
| | 03:22 | method, a method that can be used
to create an instance of the class.
| | 03:25 | If you don't define one, one is defined
for you and that's what I'm calling here.
| | 03:30 | So I have created an instance of the
Olive class and now I'll call its method
| | 03:34 | using olive., and when I type the dot,
Eclipse shows me the list of methods
| | 03:38 | that are available.
| | 03:39 | The crush method is at the top of the list.
| | 03:42 | All of the other methods that you see here
are defined as a part of the class object.
| | 03:47 | I'll talk later in the course about
inheritance, but basically all these methods
| | 03:51 | are coming from a class name object.
| | 03:53 | That is the super class
of other classes in Java.
| | 03:56 | I'll call the crush method, I'll save
my changes and run the application and
| | 04:01 | there is the output.
| | 04:02 | I call the objects instance method and
it was responsible for outputting that
| | 04:06 | string to the console.
| | 04:08 | Now I'll create one more instance method.
| | 04:10 | So far my application knows how to
crush a single olive, but clearly that's not
| | 04:14 | enough to get enough olive oil.
| | 04:16 | So now, I'm going to create an
OlivePress class and once again, just like the
| | 04:21 | olive, it will be designed to be instantiated.
| | 04:23 | I'll go to OlivePress.java and I'll
create a public method named getOil.
| | 04:29 | Once again, it will return void.
| | 04:30 | The getOil method will receive an
array of olive objects and it will loop
| | 04:35 | through the olives and crush them one at a time.
| | 04:38 | So I'll go to my method getOil and I'll
design it to receive an array of olives.
| | 04:43 | I'll type in the word, olive, I'll
press Ctrl+Space and choose olive, that will
| | 04:46 | add the required import statement.
| | 04:48 | I'll add the opening and closing
brackets to indicate that I'm receiving an
| | 04:52 | array of olives and I'll name the array, Olives.
| | 04:56 | Now within the method,
I'll loop through the array.
| | 04:58 | I'll type for and press Ctrl+Space.
| | 05:01 | I'll choose the for each syntax
and I'm saying for each olive in the
| | 05:05 | olives array do something.
| | 05:07 | And once again just like I'm doing in the main
application right now, I'll call olive.crush.
| | 05:12 | I'll save those changes;
| | 05:13 | I'll go back to the main application
class and change it so that it's now going
| | 05:17 | to crush a whole bunch of olives.
| | 05:19 | I'll go back to main.java and
I'm going to take out this code.
| | 05:23 | I don't need that anymore and I'm
going to declare an array of olives.
| | 05:27 | Once again, I'll press Ctrl+Space and
choose olive, I already have my import
| | 05:31 | statement at the top so I
don't need re-declare it.
| | 05:34 | I'll declare this as an array and name
it olives, and then I'll use the syntax
| | 05:39 | to initialize the array with values.
| | 05:41 | I'll start with a brace and then
newOlive(), newOlive(), and newOlive().
| | 05:47 | So I am creating three anonymous objects.
| | 05:52 | I am not assigning variable names to them;
| | 05:54 | I'm just creating them and passing
them into the array, and then immediately
| | 05:58 | assigning the entire array to the olives array.
| | 06:01 | Next, I'll create an instance of the OlivePress.
| | 06:05 | I'll type in OlivePress, I'll press Ctrl+
Space that adds an import statement for
| | 06:09 | that class, I'll name it press and
I'll instantiate it, once again using the
| | 06:15 | constructor method that the Java
compiler adds for me, and finally, I'll call
| | 06:19 | press.getOil and I'll pass in the olives array.
| | 06:23 | I'll make sure to add the semicolon
at the end of the line and I'll run the
| | 06:26 | application and because I created
three olives in the array, I get the
| | 06:31 | word, ouch, three times.
| | 06:33 | So this is how instance methods work.
| | 06:35 | Don't put in the static keyword and it
becomes an instance method that's called
| | 06:39 | from an instance of the class
rather than from the class definition.
| | 06:43 | Once you know how to create and use
instance methods, you are on your way to
| | 06:46 | creating full-blown objects that
incorporate both methods that is
| | 06:50 | functionality and data.
| | Collapse this transcript |
| Storing data in instance variables| 00:01 | When you declare your own custom classes
you can assign them instance variables.
| | 00:07 | Instance variables in Java are known as
fields and they are variables that are
| | 00:10 | assigned at the class level and are
available to the entire class and optionally
| | 00:14 | to the rest of the application.
| | 00:16 | I'm working in a version of the
application named InstanceVariables that's in
| | 00:20 | this chapter's exercise files.
| | 00:22 | It starts within Olive class that
has a public method named crush.
| | 00:26 | Right now it's just outputting a simple
string, but I'm going to define a set of
| | 00:30 | instance variables in this
class that can be used later on.
| | 00:33 | To declare an instance variable or a
field you place the cursor inside the
| | 00:37 | class definition and within the class
definition, you declare each variable
| | 00:41 | with an access modifier, a data type, and a
name and optionally, you can set an initial value.
| | 00:47 | So for example, I'll start with
public string, meaning I am declaring a
| | 00:51 | variable or a field that can be
accessed from anywhere in the application and
| | 00:56 | that will contain a string.
| | 00:57 | I'll give the field a name of name, and
I'll set it initially to a value of Kalamata.
| | 01:03 | So that's the type of
olive that I'm working with.
| | 01:05 | I'll let another string variable, this
one will be named flavor and it will be
| | 01:10 | a flavor of grassy.
| | 01:11 | According to Wikipedia,
Kalamata olives have a grassy flavor.
| | 01:15 | Next, I'll also declare a variable named color.
| | 01:18 | Now rather than setting this as
a string, I'll use long integer.
| | 01:22 | Colors can be translated into long
integers using the same hexadecimal values
| | 01:27 | that you might use in HTML
for cascading style sheets.
| | 01:30 | So I'll call this public, long, color
and I'll set it to a value of 0x000000 or
| | 01:39 | Black, and finally, I'll
create a variable called oil.
| | 01:44 | I'll set this as an integer
and I'll give it a value of 3.
| | 01:48 | This is random, what I'm saying is
that when I crush a Kalamata olive, I'm
| | 01:53 | getting 3 ml of oil, that's almost
certainly incorrect in the real world, but it
| | 01:58 | will work for this example.
| | 01:59 | So now these variables or fields are
available to the entire application.
| | 02:04 | Eventually, I'm going to hide the
actual data within the application, but
| | 02:08 | for now this will work.
| | 02:09 | I'll save my changes and go to the main
application where I'm creating an array of olives.
| | 02:15 | Now I'm going to re-factor or change
the structure of the application so that
| | 02:20 | instead of creating an array of
Olives that's fixed at runtime I'm going to
| | 02:24 | instead use an array list and this will
allow me to resize the array as needed.
| | 02:29 | I'll go into the Main method
and add some extra whitespace.
| | 02:33 | I'll create an ArrayList after typing
ArrayList, I'll press Ctrl+Space and that
| | 02:37 | will add the required import, and
I'll set the array list as containing
| | 02:41 | instances of the Olive class,
and I'll name it olives.
| | 02:45 | There'll be a conflict because I'm
already using that name further down, but
| | 02:49 | that's okay, I'll take care of that in a moment.
| | 02:52 | Next, I'll instantiate the array list.
| | 02:54 | Now, I'm going to create three
instances of the Olive class.
| | 02:58 | I'll start by declaring a
single variable, Olive olive.
| | 03:03 | I'm not instantiating it yet;
| | 03:05 | I'm declaring it once so that I
can reuse that reference three times.
| | 03:09 | Next, I'll say olive = new Olive and
I'll output the name of the olive that I
| | 03:15 | just created using system.out.println(
olive.name) and then I'll add the olive to
| | 03:22 | the array list using olives.add(olive).
| | 03:26 | I'm done with this array, I'll get
rid of it and then I'll copy these three
| | 03:30 | lines of code and paste them in twice.
| | 03:32 | Now I'm obviously making this code more
verbose than it really needs to be, but
| | 03:36 | my goal here is to show you that
because I declared a public field in the olive
| | 03:40 | class, I can reference it
from within the main application.
| | 03:44 | I'll save my changes and run the
application and I see some errors.
| | 03:49 | I'll go down to my errors list and
double-click and it tells me that the getOil
| | 03:52 | method is expecting an array, but
I'm trying to pass in array list.
| | 03:56 | So I'll jump to that method and
here's a great little Eclipse shortcut.
| | 04:00 | Now that my methods are being
scattered across multiple classes, I need to be
| | 04:04 | able to move among them more easily.
| | 04:05 | Eclipse lets you click on a method name and
jump to the reference and here's the shortcut.
| | 04:11 | Hold down the Ctrl key on Windows
or the Command key on Mac, move the
| | 04:15 | cursor over the method, and choose
Open Declaration and that will take you
| | 04:19 | to the method itself.
| | 04:20 | Now change the method declaration so
that it's receiving an array list of Olives.
| | 04:26 | Save and run the application and
you'll see that you're looping through the
| | 04:30 | array list using the same syntax
as you did with the array earlier.
| | 04:34 | You don't need to create an iterator for this;
| | 04:36 | if all you need to do is look through,
you can simply use it for each command.
| | 04:40 | So as I create the Kalamata olives, I
am outputting the names of the olives and
| | 04:45 | as I crush them, I'm still getting ouch.
| | 04:48 | Now let's go ahead and fix that.
| | 04:49 | We need to be more specific.
| | 04:51 | I'll go to the Olive class and I'm going
to change how the crush method behaves.
| | 04:55 | I'm going to change it to return the
amount of oil that just got crushed.
| | 05:00 | I'll change the data type from
void to int and I'll add return oil.
| | 05:05 | I'll save the changes
there and go to OlivePress.
| | 05:08 | Within the OlivePress class and
within its getOil method, I'll declare an
| | 05:12 | integer variable named oil
and I'll set it a value of 0.
| | 05:16 | Within the for loop, I'll increment
the amount of oil that I've received
| | 05:20 | using oil += Olive.crush.
| | 05:23 | I'll jump to the crush method.
| | 05:25 | Remember that I'm returning the total
amount of oil which is this integer value.
| | 05:30 | I'll come back to the OlivePress and
after the for loop, I'll output the amount
| | 05:35 | of oil that I just received.
| | 05:37 | The string will be, You got, and then
the amount of oil and then units of oil.
| | 05:42 | I'll save and run the application and it
tells me, I got 9 units of oil three times three.
| | 05:48 | Finally I'll go back to Olive.
| | 05:51 | You might have noticed that at no point
was I actually accessing the oil field
| | 05:55 | from the main application.
| | 05:56 | So I don't need to make this field
public and this is the first time I'm going
| | 06:00 | to talk about hiding data
within a Java application.
| | 06:04 | In a Java application, you should
only make data accessible that must be
| | 06:08 | accessible to the rest of the application.
| | 06:09 | If you can hide the data
within a class, you should do it.
| | 06:13 | So the only method that's actually
accessing this value at this point is a
| | 06:17 | method within the class and I
can make this field private.
| | 06:20 | I'll save and run the
application again and it still works.
| | 06:24 | So that's a look at how to declare
instance variables or fields in a Java class.
| | 06:29 | These are persistent data values.
| | 06:31 | When you create the instance of the
class, the object, these data values will
| | 06:35 | persist as long as the
object persists in memory.
| | 06:38 | I've shown you how to make those
variables either public or private.
| | 06:41 | If you make them public, if you need to
be able to access those values from the
| | 06:45 | rest of the application or private, if
they're only used within the class, and
| | 06:49 | there is also the access modifier
protected, but we won't need that until we
| | 06:54 | start dealing with inheritance.
| | Collapse this transcript |
| Using constructor methods| 00:00 | Whenever you define your own custom
class it has a constructor method.
| | 00:04 | A constructor method is a special kind
of method that's called when you create
| | 00:08 | an instance of the class, and as I
showed earlier if you create a class that
| | 00:12 | doesn't have an explicit constructor
method, such as this Olive class, the Java
| | 00:16 | compiler adds a no arguments
constructor method for you.
| | 00:20 | You can create your own custom
constructor method though if you prefer.
| | 00:23 | I'm working in a version of the
project called constructors that in this
| | 00:27 | Chapter's Exercise Files.
| | 00:29 | Now, place the cursor after the field
declarations and before the custom method crush.
| | 00:34 | A constructor method looks like this.
| | 00:36 | You start with the keyword public and
then the name of the Method is always the
| | 00:40 | same as the name of the class.
| | 00:42 | Constructor methods can be designed to
receive arguments, but if you're going to
| | 00:45 | have any constructor methods and you
want to be able to call the constructor
| | 00:49 | method with no arguments then
you need to define it explicitly.
| | 00:52 | So I am going to create a constructor
method and within the constructor method
| | 00:57 | I'll just output a message to
show when the method is being called.
| | 01:00 | I'll output constructor of and then I'll
append the value of the object name field.
| | 01:06 | When you refer to the name field
prefix it with the word this, this in Java
| | 01:12 | means the current instance of the current class.
| | 01:16 | So I'll type in this and I'll see a
listing of all the custom fields that I've
| | 01:19 | defined and I'll choose name.
| | 01:22 | I'll Save my changes and Run the
application, if prompted with the Run As dialog
| | 01:27 | I'll click Java application and click
OK and I see constructor of Kalamata each
| | 01:32 | time I create an instance of the class.
| | 01:36 | Now, notice with constructor
methods, you don't do any return type.
| | 01:40 | You don't put in the keyword void,
because constructor methods never return a
| | 01:44 | value, so you put in the accessor
method which should always be public, and the
| | 01:48 | name of the class, and you're done.
| | 01:50 | Now as with other kinds of methods you
can overload a constructor method, that
| | 01:54 | is, you can have more than one version
of it, as long as you distinguish them by
| | 01:58 | the numbers or data type of the arguments.
| | 02:01 | I'll move the cursor down below the no
arguments constructor method, and this
| | 02:05 | time I'm going to ask Eclipse to
generate a constructor method for me that
| | 02:09 | accepts values into the constructor
method and passes those values to the fields
| | 02:14 | that I've already defined.
| | 02:14 | I'll right click in the empty space,
then I'll go to the Source menu and I'll
| | 02:20 | select Generate Constructor using fields.
| | 02:24 | Eclipse shows me all the fields
that are a part of this class name,
| | 02:28 | flavor, color, and oil.
| | 02:31 | I'm going to create a constructor
method that just receives the value of oil
| | 02:35 | and they'll click OK. Here's the result.
| | 02:39 | The constructor method that's been
generated receives an argument named oil data
| | 02:43 | type as an integer the same
as the field that matches.
| | 02:46 | Skipping over the next line, the call
to the super method, which I'll explain
| | 02:49 | in a moment, the method takes the argument
that's been passed in and passes it to the field.
| | 02:55 | this.oil means the field or instance
variable and oil by itself means the argument.
| | 03:01 | If you don't put in the keyword this,
prefixing the variable name, you're
| | 03:05 | talking about the argument.
| | 03:07 | Now the super method isn't
really needed in this situation.
| | 03:11 | Super opening closing parentheses means
call the constructor method of the superclass.
| | 03:17 | We haven't talked about inheritance yet,
and I'll described as more closely when
| | 03:20 | we talk about inheritance later on,
but this basically means call the
| | 03:24 | constructor method of the class
that this class is inherited from.
| | 03:28 | I don't need that bit of code, I'm
going to delete it, and I'll close ups
| | 03:31 | some of this whitespace.
| | 03:33 | Now I'll Save the changes to this
file and go back to the main application
| | 03:37 | and I'll go to the constructor
methods that I'm already calling when I
| | 03:40 | construct each of the olives.
| | 03:42 | The default value for the oilfield in
the Olive class is 3, so when I run the
| | 03:47 | application right now, I end up with 9
units of oil, 3 times 3, but because I've
| | 03:53 | created a constructor method for the
class, I can now pass in the number of
| | 03:57 | units of oil when I construct
the class, when I instantiate it.
| | 04:01 | So I'll set these values now to 2, 1 and 2.
| | 04:05 | I'll Save the changes and
notice that Eclipse says that's fine.
| | 04:09 | There's a constructor method that's
looking for integer argument and that's
| | 04:13 | what you've passed in.
| | 04:14 | I'll run the application and this time,
I don't see the output telling me that
| | 04:18 | I've constructed the class,
but I get 5 units of oil.
| | 04:22 | 2+1+2, let's go back again
and look at the class code.
| | 04:27 | So now I have more than one
constructor method, one that accepts no arguments
| | 04:32 | and one that accepts an integer, and
this is a very common pattern when you're
| | 04:36 | creating your own custom classes.
| | 04:38 | You can overload your constructor
methods can have multiple versions as long as
| | 04:42 | you distinguish them by the number or
data types of the arguments, and then it's
| | 04:46 | up to the Java Virtual Machine and
the Compiler to figure out which of the
| | 04:50 | constructor methods will be called.
| | 04:52 | I recommend when you're creating your
own custom classes that you always create
| | 04:55 | a no arguments constructor, even
if it's not going to do anything.
| | 04:59 | That will make it very clear in your
code that a no arguments constructor is
| | 05:03 | executing the default action that is nothing.
| | 05:06 | So I'll go back to olivePress.java and
I will place the cursor inside the class
| | 05:10 | declaration, make a little bit of
whitespace, and I'll create a constructor
| | 05:15 | method for this class as well.
| | 05:17 | I'll close up the braces to show
very clearly that it's an empty, no
| | 05:21 | arguments constructor method.
| | 05:23 | Again, this is not required, but it
is recommended, so that when other
| | 05:27 | developers look at your code they can
clearly see the no arguments constructor,
| | 05:30 | and see that it's not going to do anything.
| | 05:33 | That's last change I will make to this
application, so I'll run the application
| | 05:37 | again, and show that it still works fine.
| | Collapse this transcript |
| Managing instance data with getter and setter methods| 00:00 | When you're working with object-
oriented development patterns a lot of
| | 00:04 | developers feel that fields should
always be private and their data should only
| | 00:09 | be accessed through what we
call getter and setter methods.
| | 00:12 | In some languages there is a port
for implicit setters and getters.
| | 00:16 | For example, in both C# and in
ActionScript 3, you can use the words set and
| | 00:22 | get before method names as separate
words and then you can refer to those
| | 00:26 | methods as properties.
| | 00:28 | In the Java language, in the absence
of some other framework, you can only
| | 00:32 | use explicit setters and getters,
that is methods that start with the word
| | 00:37 | get as part of the method name, but
these are so common that there is support
| | 00:41 | for generating these kinds of methods in
the development environment such as Eclipse.
| | 00:45 | I'm working in the class Olive which is a
member of the project getters and setters.
| | 00:49 | This is class has 4 fields, 2 strings,
one long in one end, and 3 of the fields
| | 00:56 | are public and one private.
| | 00:58 | To generate getter and setter methods,
place the cursor anywhere in the class.
| | 01:03 | You don't have to select the code as
I've shown here, and then you can right
| | 01:07 | click and choose Source or you can
go to the main Menu and choose Source.
| | 01:12 | From there choose Generate Getters and Setters.
| | 01:17 | In this dialog box choose the field
for which you want to Generate Getter
| | 01:21 | and Setter methods.
| | 01:22 | For this first example,
I'll only choose the oilfield.
| | 01:27 | Next, determined the insertion point,
where do you want to put the new code.
| | 01:31 | If you choose first member, the code
will go right after the class declaration,
| | 01:35 | and last member will put it at the end.
| | 01:38 | I typically like to put my getters and
setters after the field declarations.
| | 01:42 | So I'll choose after oil;
| | 01:45 | that's the last field
declaration and before the methods.
| | 01:48 | Next, indicate how you want to Sort.
| | 01:50 | Do you want to put the Fields in
alphabetical order or do you want to do all the
| | 01:54 | getters first and then all the setters.
| | 01:57 | I'm generating only getter and setter
for one field initially, so it doesn't
| | 02:01 | matter which I choose, but typically,
I like the first option, Fields in
| | 02:05 | getter/setter pairs.
| | 02:07 | Next, set the Access modifier, are your
getters and setters going to be public,
| | 02:12 | protected, default, or private?
| | 02:14 | I'm going to set them as public, so that they
can be called from anywhere in the application.
| | 02:18 | I'll click OK, and that generates
two methods named getOil and setOil.
| | 02:25 | Here is the syntax of an explicit
getter method, it always has a return data
| | 02:31 | type, which matches the original
fields' data type, the name of the method
| | 02:35 | matches the name of the field with a
prefix of get, and the name of the field is
| | 02:40 | changed to have an uppercase initial character.
| | 02:43 | So oil, all lowercase, becomes oil
with an uppercase O, and then within the
| | 02:47 | getter method, there is a return
statement that returns the value of the field.
| | 02:52 | A setter method always has a void return
type, and it has a prefix of set before
| | 02:57 | the field name, it receives a value that
matches the data type of the field, and
| | 03:02 | then it sets the field using this, to
distinguish the field from the argument.
| | 03:07 | Once you've created these methods,
you can we refactor the rest of the
| | 03:10 | application to always set
the fields through the methods.
| | 03:14 | So for example in my public
constructor down here the one who receives an int
| | 03:19 | value, instead of saying this.oil=oil,
I'll call the method setOil and pass
| | 03:25 | in oil, the argument.
| | 03:27 | Following this pattern results in
centralizing the processing of the argument,
| | 03:32 | later on if you want to validate,
modify, or otherwise secure the data;
| | 03:37 | it makes it very easy to do.
| | 03:39 | Now let's do something
similar in the olivepress class.
| | 03:43 | Currently this getOil method in this
class loops through an array list of olive
| | 03:48 | objects, crushes each of them, then
calculates the amount of olive oil, but it
| | 03:53 | doesn't actually return the
olive oil to the application.
| | 03:57 | You could change this method so that
it have a return type say of int, and
| | 04:01 | then add a return statement, or
another approach, would be to create a field
| | 04:06 | of the class, so that once the getOil
method was done, it would set the amount
| | 04:11 | of oil as a member of the class and then the
rest of the application could access that oil.
| | 04:16 | So I'm going to place the cursor right
after the class declaration and before
| | 04:19 | the constructor method.
| | 04:21 | I'll declare a private integer
variable and I'll name it totalOil and I'll
| | 04:27 | initialize it to a value of 0.
| | 04:29 | When the class is instantiated, this
private field will have a value of 0, but
| | 04:35 | then I can add values to it each
time the getOil method is called.
| | 04:40 | Next, I'll add a getter
and a setter for this field.
| | 04:44 | I'll right click and choose
Source>Generate getters and setters.
| | 04:49 | I'll check the only field, I'll place
the insertion point after totalOil, and
| | 04:55 | I'll set the access
modifier to public and click okay.
| | 05:00 | So there's my getter and setter.
| | 05:01 | The rule that I want to follow is the
only code within the class is allowed to
| | 05:06 | set the totalOil, but code
anywhere in the application can access it.
| | 05:11 | So I am going to change the access
modifier for setTotalOil to private.
| | 05:16 | So now from the point of view of the rest
of the application, it's a read-only value.
| | 05:22 | Within the getOil method I'll move
the cursor down here, and I'll call the
| | 05:25 | method setTotalOil and pass in
the value that was calculated.
| | 05:30 | I'll take this line of code that's
outputting the total amount of oil and I'm
| | 05:34 | going to place it in the main application.
| | 05:35 | I'll go to main.java and place the
cursor after the call to the OlivePresses get
| | 05:41 | oil method, I'll paste in that line of
code and now instead of outputting the
| | 05:47 | value of an oil variable, which is no
longer in the scope of this class, I'll
| | 05:52 | get that value from press.getTotalOil,
because it's a public accessor method, a
| | 05:58 | public getter method, I can call
it from anywhere in the application.
| | 06:03 | It's up to the olivepress to set the oil,
but my main application code can get to it.
| | 06:08 | I'll run the application as a Java
application and there is the result.
| | 06:14 | Everything still works
exactly the same as before.
| | 06:18 | Finally, let's say that in this
application I wanted to reuse the press
| | 06:22 | object, so that I could add olives at one
point in the application and then at another point.
| | 06:28 | As long as I create a single instance
of the olivepress class and keep it in
| | 06:32 | memory for the duration of the
application session, I should be able to do
| | 06:36 | that, but right now my setTotalOil
method is rewriting the value of total oil
| | 06:42 | every time it's called.
| | 06:44 | Let's say that instead, I
wanted to incrementally add to it.
| | 06:48 | I could go to the setTotalOil method and
change the operator from equals to plus
| | 06:53 | equals, and now I'm adding to the total.
| | 06:56 | I'll Save my changes.
| | 06:59 | I'll go back to main.java and I'm
going to copy these lines of code
| | 07:04 | starting with press.getOil.
| | 07:06 | I'll paste those at the end and so now
I am going to crush those olives once,
| | 07:11 | and then I am going to crush them again,
because I'm now incrementally adding
| | 07:15 | a value, I should be multiplying the amount
of olive oil each time I go through the loop.
| | 07:21 | I'll Save and Run, and the first time
through I got the 5 units and after the
| | 07:26 | second time through I have 10, and so on.
| | 07:30 | This illustrates the value of getters
and setters, when you wrap the access of
| | 07:35 | the data in a setter;
| | 07:37 | it lets you change the rules very, very easily.
| | 07:40 | So before every time the method was
called, I was just assigning the value, but
| | 07:45 | then with one little change, now I'm
incrementally adding to the value, and you
| | 07:50 | can design and code any other sort of
business rule you like once you have the
| | 07:54 | getters and setters in place.
| | 07:56 | So this is a major part of
what we talked about when we were
| | 07:59 | discussing encapsulation.
| | 08:01 | Hiding data refers to the practice of
setting fields as private and then only
| | 08:06 | allowing access to those fields
through getter and setter methods.
| | 08:11 | Again in Java, in the pure
programming language, you don't have implicit
| | 08:15 | setters and getters, like you do in
some other languages, but there is a very
| | 08:19 | strong convention for how you design
setters and getters and then call them
| | 08:23 | from within your application.
| | Collapse this transcript |
| Using class variables and Enum classes| 00:00 | In this video course so far, I've shown
you how to create two types of methods,
| | 00:05 | class methods that are called from a
definition of a class and instance methods
| | 00:09 | that are called from an
instance of the class or an object.
| | 00:13 | The same distinction
occurs with fields or variables.
| | 00:17 | When you declare a variable as a member
of a class using access modifiers such
| | 00:21 | as public and a data type such as
string, it's automatically an instance
| | 00:26 | variable or an instance field.
| | 00:28 | You can also create class fields by
incorporating the additional keyword static.
| | 00:34 | The most common reason to do this
is to represent a constant value.
| | 00:39 | Java doesn't support an explicit
const or constant keyword, so instead, you
| | 00:44 | typically set constant values using a
combination of static and the keyword
| | 00:49 | final, which means that a value
can't be changed once its been set.
| | 00:53 | I'll demonstrate this in the Olive
class in this version of the project class
| | 00:58 | variables, and I'll define a
few possible values for the color.
| | 01:03 | Right now my color field has a value
of 000000 which has equivalent value of
| | 01:09 | black, but I want to make my
code a little bit more readable.
| | 01:13 | So I'll place my cursor inside the
class declaration and I'll declare a field
| | 01:18 | using these keywords, public, static, final.
| | 01:22 | Public means that the field would be
accessible from the entire application.
| | 01:26 | Static means that it's a class field,
it will be accessed from the class
| | 01:30 | definition, not from an instance of a class,
and final means its value can't be changed.
| | 01:36 | Next, I'll set the data type long, to
match the field data type of color, and
| | 01:41 | then the name of the constant will be set.
| | 01:43 | The convention for constant values is
to set their names in all uppercase.
| | 01:49 | So I'll set the name of this one as BLACK,
then I'll put in the equal assignment
| | 01:53 | operator and I'll copy the
value from the color field.
| | 01:56 | I'll finish the declaration with a semicolon
and now I have a constant value to work with.
| | 02:05 | Next, I'll go down to the color
field where I've used the literal value.
| | 02:09 | I'll get rid of that and
I'll replace it with Olive.;
| | 02:13 | and I'll see the value BLACK appear.
| | 02:16 | I'll Save the changes and Run the
application and you should see that it runs
| | 02:20 | exactly the same way it did before.
| | 02:23 | Now I'll add one more field, I'll copy
the one for BLACK and paste it in, I'll
| | 02:29 | change the second one from BLACK to GREEN,
and I'll change the hexadecimal color
| | 02:34 | value to 00FF00 and you can keep on
doing this, adding as many different Olive
| | 02:41 | colors as you need it.
| | 02:43 | I'll Save the change and Run it again
and even though I'm not using that GREEN
| | 02:47 | value the application still runs just fine.
| | 02:51 | So this is a look at how to
declare constants or class variable.
| | 02:55 | Again, there's no constant keyword in
Java, instead, you declare values using
| | 03:00 | the keywords static and final.
| | 03:03 | You can make these fields public,
private, or protected, whatever you need, and
| | 03:07 | you set their names to all uppercase,
and that's just a very strong convention
| | 03:12 | that all Java developers follow.
| | Collapse this transcript |
|
|
10. Working with Inheritance and PolymorphismUnderstanding inheritance and polymorphism| 00:00 | In a previous video, I described the
concept of encapsulation, one of the major
| | 00:05 | concepts of object-oriented programming.
| | 00:07 | There are two other concepts that
you need to master to be a great
| | 00:10 | object-oriented programmer, and they
are named Inheritance and Polymorphism.
| | 00:15 | I'll describe them here.
| | 00:17 | Inheritance means that there's a
relationship between classes in your application.
| | 00:22 | An inheritance relationship lets you
inherit or extend functionality from
| | 00:26 | one class to another.
| | 00:28 | In the world of C++ there
is multiple inheritance.
| | 00:32 | A single class can inherit
functionality from multiple other classes but in
| | 00:36 | Java, there is only single inheritance,
each new class can extend or inherit
| | 00:41 | functionality from only one other class.
| | 00:44 | This actually makes it a lot easier
to manage your code because if you've
| | 00:48 | created an inheritance relationship and
you run into a bug that bug can either
| | 00:52 | be in the class you are working with
or in the class that you inherited from,
| | 00:56 | but the issue has to be
somewhere in that very linear path.
| | 01:00 | There are a number of ways to describe
an inheritance relationship and they are
| | 01:04 | just different vocabularies.
| | 01:06 | You'll hear some developers
describe the relationship as a
| | 01:08 | parent-child relationship, where
the parent has the functionality and
| | 01:12 | the child is inheriting.
| | 01:13 | You will also hear the terms base
and derived, where a base class has the
| | 01:18 | functionality and the
derived class is extending it.
| | 01:22 | In the world of Java, the terms that are
most commonly used are Superclass and Subclass.
| | 01:27 | The Superclass has the functionality and
the Subclass is extending the Superclass.
| | 01:33 | And again, each subclass in Java can
only have one Superclass, in fact even if
| | 01:39 | you don't explicitly extend a class
all of your classes are extending another
| | 01:44 | class, a Superclass.
| | 01:45 | There is a special class named object
with an uppercase O and this is at the top
| | 01:51 | of the Java inheritance tree.
| | 01:53 | If you don't explicitly inherit from
some class, you're inheriting from object
| | 01:58 | automatically, so that's Inheritance.
| | 02:02 | Polymorphism is the last
important term to understand.
| | 02:05 | Polymorphism means that when there is
an inheritance relationship between a
| | 02:09 | Superclass and a Subclass you can deal
with an object that's instantiated from
| | 02:14 | the subclass either as its native type,
the subclass or as it's inherited or to
| | 02:19 | extend a type the Superclass.
| | 02:22 | To do this, you declare the object and
instead of declaring the native data type
| | 02:27 | you declare the Superclass type.
| | 02:29 | If it's a class that you're
instantiating by calling a constructor method,
| | 02:33 | you call the constructor method from the
subclass but you use the data type of the Superclass.
| | 02:38 | When you've done that it becomes
possible to take that object which you
| | 02:42 | declared as the Superclass and pass
it to any method that's expecting an
| | 02:47 | instance of the Superclass.
| | 02:49 | When you have an inheritance
relationship this can give you enormous flexibility
| | 02:53 | in designing your code.
| | 02:55 | Let's visualize an inheritance relationship.
| | 02:58 | Let's imagine a class named Olive.
| | 03:00 | Well there are many kinds of olives
in the world and so you might declare a
| | 03:05 | Superclass named Olive that has
functionality that's common to all olives but
| | 03:10 | then you might create multiple subclasses,
each representing one particular kind of Olive.
| | 03:16 | This is how we would diagram the
relationship with an arrow pointing to the Superclass.
| | 03:21 | That arrow means that the subclasses are
extending the functionality of the Superclass.
| | 03:27 | The Superclass is olive and all
the others are the subclasses.
| | 03:32 | We call this single inheritance
because each subclass can only have a single
| | 03:36 | superclass, but as you can see, a
superclass can have many subclasses.
| | 03:42 | superclasses don't need any special
code, any class can be a superclass.
| | 03:47 | And all of the fields and methods of
that class can be inherited, unless
| | 03:51 | they're marked as private.
| | 03:53 | You'll see that it's very common to
set fields or data values as private in a
| | 03:58 | class and methods of a
superclass as protected or public.
| | 04:02 | Private means that only the
superclass can deal with the field directly,
| | 04:06 | protected means that a method can be
called either by the superclass or by its
| | 04:11 | subclasses, and public means that
those methods can be called by anybody.
| | 04:16 | Let's take a look at
code of a sample superclass.
| | 04:19 | This might be the class Olive, the class Olive
might have a couple of fields or data values.
| | 04:25 | I've declared a double value called
volume and a Boolean value called crushed
| | 04:29 | which is initially set to false.
| | 04:32 | I have a method called getVolume and
the logic of that method says if the value
| | 04:37 | crush is true then return the
volume and otherwise return zero.
| | 04:42 | This is using the ternary operator,
a shortened conditional syntax.
| | 04:47 | There is a protected method named
setVolume, it's protected so that it can only
| | 04:52 | be called by the class itself or its subclasses.
| | 04:55 | And there is a public method named crush
which basically says this Olive has been crushed.
| | 05:01 | The fields or data values are
marked as private only the superclass can
| | 05:05 | deal with them directly.
| | 05:07 | To get volume method which is a
getter accessor method can be called by
| | 05:10 | anybody in the application.
| | 05:12 | This setVolume method, the setter can
only be called by the class itself and the
| | 05:17 | subclass and the crushed
method is declared as public.
| | 05:20 | Now again this is just one way of
designing the code, it follows some standard
| | 05:25 | recommendations in Java by keeping
private data private, but you could choose
| | 05:29 | to do it differently.
| | 05:31 | Now the subclasses that extend the superclass.
| | 05:34 | In order to extend the superclass you
declare the class in your Java file and
| | 05:39 | you use the extends keyword
and reference the superclass.
| | 05:43 | It might look like this, I'm placing
my class into a package named olives and
| | 05:49 | then I create the class named Kalamata
and I use the extends keyword and then
| | 05:54 | the superclass named Olive.
| | 05:56 | The subclass implementation might have a
lot of details but here's one small example.
| | 06:01 | As the subclass is constructed, and
its constructor method is called it would
| | 06:06 | be responsible for setting its own volume or
the amount of oil it's capable of producing.
| | 06:11 | So within the constructor method
Kalamata which matches the name of the class
| | 06:15 | itself it calls this.setVolume(2).
| | 06:19 | SetVolume is a protected method, so
the subclass can call it, but the actual
| | 06:24 | data it's affecting is stored in the
superclass, it's hidden from the rest
| | 06:29 | of the application.
| | 06:30 | Another subclass of the same superclass
would call the setVolume method also but
| | 06:35 | it would set its numeric volume differently.
| | 06:37 | So now Liguria is saying, I can get
five units of oil and Kalamata is saying, I
| | 06:44 | can get two units of oil.
| | 06:46 | They're both calling the same method,
they're both using that same hidden data
| | 06:50 | that's in the superclass, but they are
determining what the actual value is.
| | 06:54 | When you go to the main class code,
you can now say I'm going to declare
| | 06:58 | an array of Olives.
| | 07:00 | Olive, bracket, bracket,
means multiple Olives.
| | 07:03 | But then when you actually declare
the instances of the object, you use the
| | 07:07 | constructor methods of
the individual subclasses.
| | 07:11 | I have an array with two Kalamatas
and one Liguria, but they're all olives
| | 07:17 | because of the inheritance relationship.
| | 07:19 | I could then create an instance in
the OlivePress call to getOil method and
| | 07:24 | within that method it would then go
and call the appropriate methods of the
| | 07:29 | olive object and for Kalamata's, it
would get two units, for Liguria's it would
| | 07:33 | get five units and so on.
| | 07:35 | The rest of the application does not
need to know the mechanics of how the
| | 07:39 | volume is being calculated.
| | 07:41 | All the top-level application has to do
is say, I've got these three olives and
| | 07:45 | they're of these types, go ahead and crush them.
| | 07:48 | The actual mechanics are hidden
within the class implementations.
| | 07:53 | This idea that you can create an
instance of a class by referring to it uniquely
| | 07:58 | named constructor method but then take
the object and fit it into a data type of
| | 08:03 | its superclass is polymorphism at work.
| | 08:06 | You're taking an object that has a
native type in your saying I'm going to use
| | 08:10 | it as though its supertype, that's
polymorphic and it allows you to build really
| | 08:15 | elegant applications
| | 08:17 | Within the implementation of the
OlivePress, it would simply loop through the
| | 08:21 | olives and call the methods, it would
get the oil, it would add that to the
| | 08:26 | olive oil, and the end result
would be a correct calculation.
| | 08:30 | The OlivePress doesn't need to know
how much oil you get out of each olive
| | 08:34 | and it doesn't even need to know that they're
all these different kinds of olives out there.
| | 08:38 | From the point of view of the
OlivePress, there is only one kind of olive an
| | 08:42 | Olive, and you can crush it
and you can add it to the oil.
| | 08:46 | The details are hidden
within the implementation.
| | 08:50 | So that's the idea of
inheritance and polymorphism.
| | 08:53 | In the rest of the videos of this
chapter I'll show you how to implement
| | 08:56 | inheritance and put it to work
polymorphically in your applications, and then in
| | 09:01 | a later chapter we'll go on to more
advanced concepts using constructs called
| | 09:06 | interfaces and abstract classes that
also adds to the inheritance model of Java.
| | Collapse this transcript |
| Extending custom classes| 00:00 | The goal of creating an inheritance
relationship between classes is to extend or
| | 00:05 | inherit functionality in the subclass.
| | 00:08 | I am going to demonstrate this in my
OlivePress application, working in a
| | 00:12 | version of the project named extending custom
| | 00:15 | In this application I've defined a
custom class named Olive, it has two public
| | 00:20 | class fields BLACK and GREEN.
| | 00:22 | It has three public instance fields, two
strings in a long, and it has a private
| | 00:27 | instance field for oil, an integer.
| | 00:30 | It has a getter and a setter for the
oil value and a couple of constructor
| | 00:34 | methods and one custom crush method.
| | 00:37 | Now, I'm going to create
subclasses for the Olive class.
| | 00:41 | My goal is to create classes that
inherit most of the functionality of the
| | 00:45 | superclass, but then set particular
values that are unique to those classes.
| | 00:51 | I'll place my subclasses in the
same package as the superclass olive.
| | 00:55 | I'll go to the package Explorer, I'll right
click on the package and I'll select New> Class.
| | 01:02 | I'll name my first subclass, Kalamata,
I'll set the superclass to my olive class.
| | 01:09 | When you set the superclass you have to
use the entire package and class name.
| | 01:13 | You can't just name the class by its name.
| | 01:16 | And this would be tough to
type without making mistakes.
| | 01:19 | So I'm going to click the browse button
and let Eclipse do some of the work for me.
| | 01:23 | In the superclass selection dialog
I'll type Olive and I'll choose Olive and
| | 01:28 | click okay and then click finish.
| | 01:32 | And here is my subclass Kalamata.
| | 01:34 | Now I'll repeat that operation and
create a second subclass, I'll right-click
| | 01:38 | on the package, choose New > Class and I'll
name this one, Ligurian another olive variety.
| | 01:46 | Once again I'll browse for the
superclass selecting Olive and I'll click Finish.
| | 01:53 | I now have two subclasses of the Olive class.
| | 01:56 | Now when I create my olives in the
main application, I'd like to be specific
| | 02:02 | about what kind of olives I'm creating.
| | 02:04 | Right now, I'm calling the Olive
constructor method three times and passing in
| | 02:09 | values for the amount of oil
that that Olive will generate.
| | 02:13 | Instead I'd like to say I want to
create two Kalamata's and one Ligurian.
| | 02:19 | All I need to do is use the appropriate
constructor methods for these classes,
| | 02:24 | but I can't do it quite yet.
| | 02:26 | Even though the
superclass has constructor methods.
| | 02:29 | Constructor methods are not
literally speaking members of the class.
| | 02:33 | There are special kind of syntax and
so they're not inherited by subclasses,
| | 02:39 | each subclass needs its own
explicit constructor that matches its name.
| | 02:44 | So I will go to the Kalamata
class and fix the problem there first.
| | 02:48 | I'll place the cursor inside the
class declaration and right-click and I'll
| | 02:52 | choose Source and then I'll let Eclipse
do some of the work for me by choosing
| | 02:57 | this option, Generates
Constructors From Superclass.
| | 03:01 | I'm asked which constructors I want to
implement, the one with no arguments or
| | 03:06 | the one with the integer argument or both.
| | 03:09 | Because of the way I am designing this
application I only want my subclasses to
| | 03:13 | have no arguments constructors.
| | 03:16 | So I'll deselect the version that would
receive an integer argument and click OK.
| | 03:21 | So here's my new constructor method.
| | 03:23 | There is a single line of code here named super.
| | 03:26 | The super method is a way of calling
the superclass's constructor method.
| | 03:31 | I'll leave that in place for the moment
and I'll just remove the TODO comment.
| | 03:35 | I'll save those changes and go to the
Ligurian class and repeat the process.
| | 03:39 | Once again I'll right-click inside
the Class Declaration and choose Source
| | 03:44 | generate constructors from superclass,
I'll deselect the constructor that
| | 03:48 | receives an integer argument and click
OK, and I'll remove the TODO comment.
| | 03:54 | Now I'm ready to use the
subclasses in my main application.
| | 03:58 | I'll go to main.java in the main
application file I'm calling the constructor
| | 04:03 | method for the superclass three times.
| | 04:06 | Notice that I declared a variable typed
as the superclass, but when I actually
| | 04:11 | construct the objects I don't have
to use the superclass constructor.
| | 04:15 | I can instead use the subclass
constructor, the native type of the object will
| | 04:20 | then be the subclass, but it
can masquerade as the superclass.
| | 04:25 | This is polymorphism at work.
| | 04:28 | By declaring as the superclass, I can
then say I've got a whole bunch of olives,
| | 04:32 | but I don't have to be specific about
what types of olives, but when I construct
| | 04:37 | them I can be specific and affect the behavior.
| | 04:40 | So I'll go to the first constructor
method call and I'll change that to
| | 04:44 | Kalamata, I'll type Kal and press Ctrl+
Spacebar and the rest of the class name
| | 04:49 | is filled in for me by Eclipse.
| | 04:51 | Now, I'll do something similar but
the second one will be an instance of
| | 04:55 | the Ligurian class.
| | 04:56 | I'll type Lig and press Ctrl +
Spacebar, and Eclipse finds two classes that
| | 05:02 | start with that string, I'll choose
Ligurian and then finally, I'll change the
| | 05:06 | third one and I once again use
Kalamata, typing Kal and Ctrl + Spacebar.
| | 05:13 | When you type Ctrl + Spacebar, you
should get new import statements up at the
| | 05:16 | top of your code for the new classes.
| | 05:19 | Now, I've still got problems here right
now my subclasses only have no arguments
| | 05:24 | constructor methods.
| | 05:25 | They don't have versions of the
constructor method that can receive values.
| | 05:29 | When I move the cursor over the first
constructor method call, I get a list of
| | 05:33 | available quick fixes.
| | 05:36 | What do you want to do Eclipse is
asking me to match the constructor.
| | 05:40 | I'll choose the first one, remove the
argument and now that constructor method
| | 05:45 | call matches what I have in the class.
| | 05:47 | I'll do the same thing for Ligurian,
removing the argument and then for the
| | 05:52 | second version of Kalamata.
| | 05:54 | I'll save my changes, and it will now
appear as though everything is in good shape.
| | 05:59 | I'll run the application, and you'll
see that after running the first series of
| | 06:03 | olives I get nine units of
oil, and after the second 18.
| | 06:06 | Well, why is this happening?
| | 06:10 | The reason is because in the
superclass, in the oil declaration there is a
| | 06:15 | default value of three and I am no
longer doing anything to override that value.
| | 06:21 | My goal is to have each of the
subclasses decide for itself.
| | 06:24 | How much oil do I generate, what's
my color, what's my name and so on.
| | 06:29 | So I'll go over to kalamata.
java and I'll make those changes.
| | 06:33 | First of all, going back to the
superclass these three fields are public and so
| | 06:38 | I can change them from directly
within the subclass, I'll say this.name =
| | 06:43 | Kalamata and this.flavor equals Grassy and this.
| | 06:52 | color == Olive.BLACK.
| | 06:56 | Now to set the oil value once again I'll
go back to the superclass, and show you
| | 07:01 | that we provided a way of setting
the oil value using this version of the
| | 07:05 | constructor method which is public.
| | 07:07 | So go back to Kalamata, and
I'll pass in a value of two.
| | 07:11 | So now all Kalamata olives
will have the same oil value.
| | 07:16 | When I save my changes,
notice the error at the bottom.
| | 07:19 | It tells me that if I'm going to call
the superclass's constructor, that has to
| | 07:23 | go at the top before any other statements.
| | 07:26 | So I am going to move that code up
holding down Alt on Windows or Option on Mac
| | 07:31 | and pressing the up arrow a few
times, then I'll save my changes.
| | 07:35 | Now I'll copy those lines of code to
the clipboard, and go over to Ligurian and
| | 07:40 | I'll paste that in getting rid of the
super method call with no arguments.
| | 07:45 | I'll change the oil value for Ligurian to five.
| | 07:48 | We'll say that that's a very big olive,
I'll change the name to Ligurian, I'll
| | 07:52 | change the flavor to Yummy and
I'll change the color to green.
| | 08:00 | So now each of the subclasses is
responsible for setting its own field values,
| | 08:05 | when I run the application, all I
need to know is that I am creating these
| | 08:09 | instances of these subclasses, all
the specifics are determined by the
| | 08:14 | subclasses themselves and when I run
the application, it looks like I got the
| | 08:17 | same values, nine units and 18 units but
it turns out that that's because of the
| | 08:23 | values and the particular
combination of olives that I just selected.
| | 08:27 | So I'll go back to Ligurian and I'm
going to change the Ligurian so that it's a
| | 08:31 | really tiny olive, it only gives me
one unit of oil, I'll run the application
| | 08:36 | again and this time the numbers change.
| | 08:38 | So you can see how creating an
inheritance relationship allows you to inherit
| | 08:43 | functionality from a superclass but
then set specific values in the subclass
| | 08:49 | that are respected by the
rest of the application.
| | 08:52 | From the main application's point of view,
all it needs to know is these are the
| | 08:56 | types of olives, all of the
details are handled in the subclass code.
| | Collapse this transcript |
| Overriding superclass methods| 00:00 | When a subclass extends a superclass, it
inherits the methods of that superclass.
| | 00:05 | But it can override them
replacing the version in the superclass;
| | 00:09 | I'll show you how to do this with the
Olive superclass and Kalamata subclass in
| | 00:14 | this version of my
application overriding methods.
| | 00:17 | The olive superclass has a method
called crush, it outputs a simple string
| | 00:22 | and returns a value.
| | 00:23 | Now, the particular example I'm going
to show is very simple, but my goal is to
| | 00:28 | show you the basic syntax and then as
you find reasons to extend superclasses
| | 00:33 | and override their methods
you'll know how to do it.
| | 00:36 | Go to the subclass Kalamata and place
the cursor after the constructor method.
| | 00:41 | Now you could type all the code
yourself, but Eclipse will help you, press
| | 00:44 | Ctrl+Space and you'll see a list of
all the methods of the superclass, choose
| | 00:50 | the one you want to override crush,
a new version of the crush method is
| | 00:54 | added to your code.
| | 00:55 | This annotation the @ character and the
word Override with an uppercase O is not
| | 01:00 | required, but it is recommended it
makes your code more readable, it makes it
| | 01:05 | clear that you're overriding the
superclasses version of the method.
| | 01:09 | When you override the superclass
version the data type must match.
| | 01:13 | So if I go back to the superclass
method it returns an int value and here's the
| | 01:19 | subclass version, this arrow pointing
upward over and the trough indicates that
| | 01:24 | this is an overriding method and when
you click it, it will take you to the
| | 01:27 | superclass version, I'll go back to
the subclass, I'll get rid of this TODO
| | 01:32 | comment, we don't need that, the
version of the class that Eclipse generates
| | 01:36 | includes a statement return super.
crush, this means called the superclasses
| | 01:42 | version of the method and
return whatever value it returns.
| | 01:46 | So, even though you're overriding,
you still can take advantage of the
| | 01:50 | functionality that's apart
the superclass implementation.
| | 01:54 | Now, I'll place the cursor inside the
new method and I'll use System.out.println
| | 02:01 | and I'll output the message "crush
from subclass", then I'll go back to the
| | 02:09 | superclass version of the method and
I'll output "crush from superclass", I'll
| | 02:15 | save all my changes and run the
application and you'll see where ever the
| | 02:19 | subclass version is being called that
first to get the message from the subclass
| | 02:23 | and then from the superclass.
| | 02:26 | And this is because of the order of
the code first I'm getting this print
| | 02:29 | command, then I'm calling the return
statement and calling the super crush
| | 02:34 | method, the super crush method is
outputting its message returning the value
| | 02:40 | and then finally the subclass method takes over
and returns the value to the main application.
| | 02:45 | So to review the rules for overriding
methods the data type of the method that
| | 02:49 | you're overriding must be repeated in
the subclass, the at override annotation
| | 02:54 | is not required but it is recommended,
it makes your code more readable.
| | 02:59 | And once you know how to override
methods from the superclass you can customize
| | 03:03 | the behavior of your subclasses
however your application requires.
| | Collapse this transcript |
| Casting subclass objects| 00:00 | Earlier in this video course when I
was describing the use of primitive
| | 00:03 | variables, I described the process of
conversion as either upward or downward.
| | 00:09 | I described the conversion of an
integer say to a float or double as an upward
| | 00:14 | conversion and said that this sort of
conversion is implicit, automatic, and
| | 00:19 | safe, but if you try to go in the
other direction converting downward where
| | 00:23 | you take a very specific value and
try to squeeze it into a less specific
| | 00:28 | value that's where the conversion
can lose data, and so you have to be
| | 00:32 | explicit in your syntax.
| | 00:34 | This same thing is true of
complex objects that have an inheritance
| | 00:37 | relationship, when you use an object
that's a subclass and you treat it as its
| | 00:42 | superclass, we don't call that
converting we call it casting, but we still use
| | 00:47 | the same directions, the specific
version being used as the more general version
| | 00:51 | is called upward casting and taking an
object that's been seen as the superclass
| | 00:57 | and casting it downward to the
specific object is called down casting.
| | 01:02 | And just as with primitive
variables you have to be specific.
| | 01:05 | Let's take an example, I'm working
in a version of my application that's
| | 01:09 | called casting objects.
| | 01:12 | In this version of the application I
removed a little bit of code, but I still
| | 01:16 | have a declaration of an olive variable
and then I'm instantiating that variable
| | 01:21 | three times, twice as a Kalamata and
once as a Liguirian, I'm then adding those
| | 01:26 | objects to an array list that
explicitly is declared as only containing
| | 01:31 | instances of the olive class.
| | 01:34 | I'm allowed to pass in the subclass,
because that's an upward conversion and
| | 01:39 | it's implicit and it's safe.
| | 01:41 | But now I'll show you what
happens when you try to recast downward.
| | 01:45 | I'll go down to the bottom of the code
and I'm going to get a reference to the
| | 01:49 | first item in that array list.
| | 01:52 | I know that it's an instance of Kalamata
class, because that's how I declared it up here.
| | 01:58 | So I'll start off below all the other
code and put in a data type of Kalamata
| | 02:04 | and I'll name the variable olive1.
| | 02:07 | And then I'll get a reference to that
object using the syntax olives.get and
| | 02:12 | I'll pass in a value of 0 for
the first item in the array list.
| | 02:17 | Now when I save my changes and build
the project I get this, type mismatch
| | 02:22 | cannot convert from Olive to Kalamata,
it's a downward casting that I'm trying to do.
| | 02:28 | Even though I know it's a Kalamata olive,
I created it as a Kalamata olive, the
| | 02:34 | compiler and the JVM at this
point will think it's simply an olive.
| | 02:39 | So I have to tell the compiler
its okay, it's a Kalamata olive.
| | 02:43 | Here is how you do it, place the
cursor before the code that's returning the
| | 02:48 | reference and then declare the native
type of the object wrapped in parentheses.
| | 02:58 | I'm telling the compiler and getting
the reference to this object, but I want
| | 03:02 | you to treat it as the subclass, I'll
save the changes, the error goes away
| | 03:08 | and all I have left now is a warning saying
the value of that variable isn't yet used.
| | 03:13 | So let's go ahead and add a little
bit specific functionality to Kalamata,
| | 03:18 | that's not available in all other olives.
| | 03:20 | I hold down the Ctrl key on Windows or
Command on Mac and click the name of the
| | 03:25 | class Kalamata and that takes me
to the declaration of the class.
| | 03:30 | I'll add a new public method into the
class after the override of the crush method.
| | 03:35 | It'll be a public method that
returns a String and it will be named
| | 03:39 | getOrigin and I'll return a value
simply of "Greece" because that where
| | 03:45 | Kalamata's come from.
| | 03:46 | I'll save my changes and go back to
the main class and then I'll output the
| | 03:52 | return value from that method using
a System.out.println command and the
| | 04:00 | output will look like this "Olive1 is
from" and then I'll append to that the
| | 04:07 | value of olive1.getOrigin.
| | 04:09 | I'll run the application and there
is the result Olive 1 is from Greece.
| | 04:19 | Now if I didn't have this casting
syntax I wouldn't even be able to compile the
| | 04:24 | application, but if I could I wouldn't
be able to call that get origin method,
| | 04:29 | the compiler would say, well you said
that was an olive not a Kalamata and if
| | 04:33 | it's not a Kalamata then it
doesn't have to get origin method.
| | 04:37 | So this is how you cast objects downward
from the general type to their specific type.
| | 04:43 | As you continue using the
inheritance model in Java you'll find that this
| | 04:48 | casting becomes more and more important.
| | 04:51 | The ability to cast upward and
downward so that you can either use objects in
| | 04:56 | their general form that is as their
superclass or in their specific form their subclass.
| | Collapse this transcript |
| Understanding interfaces and implementing classes| 00:00 | In previous videos, I've describe how
to create an inheritance relationship
| | 00:04 | between Java classes, superclasses
that contain functionality, and subclasses
| | 00:09 | that inherit that functionality.
| | 00:11 | There is another way of creating
inheritance relationship using an interface.
| | 00:16 | An interface in Java lets you define
the structure of a class including the
| | 00:21 | names and signatures of the classes
methods and any final fields that is class
| | 00:26 | or instance variables that
will always have the same values.
| | 00:30 | You can then implement that
interface with a class that you can
| | 00:33 | actually instantiate.
| | 00:34 | The Java class library
uses interfaces extensively.
| | 00:38 | Here is an example of an interface
you probably will use in your own
| | 00:41 | applications, the collection interface.
| | 00:44 | The collection interface is the high-
level definition of objects that are a part
| | 00:49 | of the Java collections framework and
we've only used a number of classes in
| | 00:53 | this framework including the array list.
| | 00:55 | The collection interface defines the
names and signatures of methods that are a
| | 01:00 | part of all the classes in the
list of implementing classes.
| | 01:04 | I'll go down to the method list and
you'll see that they look familiar.
| | 01:08 | These are the same methods that
are a part of the array list class.
| | 01:12 | The idea of an interface is
that you're defining a contract.
| | 01:16 | If you say that a class implements an
interface, it must implement all of these
| | 01:21 | classes and it must use the exact
method names and the same number and data
| | 01:26 | types of arguments and
the same return data type.
| | 01:29 | This then allows you to use the
concept of polymorphism in your code.
| | 01:33 | An array list can be seen either as an
array list or as the interface that it
| | 01:37 | implements, collection.
| | 01:39 | Let's see how you might use
this in an actual application.
| | 01:42 | I am in a project named UsingInterfaces
that's a part of his chapter's exercise files.
| | 01:47 | In this version of the application I
have a call to a method named getOil that's
| | 01:52 | defined in the class OlivePress.
| | 01:54 | I am passing in an object as an array
and this object is declared as an array
| | 01:59 | list containing instances of the Olive class.
| | 02:02 | In the OlivePress class, where I've
defined that method, I'm using exactly the
| | 02:07 | same data type array list.
| | 02:09 | Now because array list implements the
collection interface I can actually make
| | 02:13 | this method a lot more flexible.
| | 02:16 | Instead of requiring an instance of the
array list class, I can instead require
| | 02:20 | an instance of the collection interface.
| | 02:23 | So I'll change the data type in the
method signature from array list to collection.
| | 02:28 | After typing the name of the interface,
I'll press Ctrl+Space and choose the
| | 02:32 | collection interface and that causes
the required import statement to be added
| | 02:36 | to the top of the code.
| | 02:38 | I'll then clean up my imports by
going to Source>Organize Imports and that
| | 02:43 | removes the import for the array list,
which is no longer referred to in this class.
| | 02:47 | I'll save my changes and that rebuilds
the project and you'll see that there are
| | 02:52 | no programming problems as a result.
| | 02:54 | I am up casting from array list to
collection, from the more specific type to
| | 02:59 | the more general type.
| | 03:01 | And now this method can accept any
instance of any class that implements the
| | 03:06 | collection interface.
| | 03:07 | In the Main class, I'm going to still
keep the array list declaration here.
| | 03:13 | I'm not going to change its collection
and the reason is because the array list
| | 03:16 | class has other methods that are not
part of the contract that are not described
| | 03:22 | in the collection interface.
| | 03:24 | One of the most important
of these is the get method.
| | 03:27 | This method is a specific part of
array list and is not part of the contract
| | 03:32 | and if I data typed this object as collection
the compiler would not accept my call to get.
| | 03:38 | But with that change I'll save and
run the application and show you that it
| | 03:42 | still works exactly as it did before.
| | 03:45 | But now my getOil method is more flexible.
| | 03:47 | I can pass in any instance of
any class that implements the
| | 03:51 | collection interface.
| | 03:53 | Now you can create your own custom
interfaces in your applications and your own
| | 03:57 | implementing classes and I'll show
you how to do that in another video.
| | Collapse this transcript |
| Creating your own interfaces| 00:00 | You can use interfaces in
your own applications to model
| | 00:03 | inheritance relationships.
| | 00:05 | You create your own interfaces just
like you do classes and in the interface
| | 00:09 | definition, you add your method
definitions, the method names and signatures,
| | 00:14 | and you can also add final fields that
is values that don't change at runtime.
| | 00:20 | Interfaces can't have constructor
methods or other elements of classes though.
| | 00:25 | So interfaces should only be used in
situations where you're modeling behavior
| | 00:30 | and not dynamic management of data.
| | 00:32 | I'll give you a very brief example of this.
| | 00:35 | I'll be working in a version of the
application named creating interfaces.
| | 00:39 | Let's say, for example, that I wanted
to create an inheritance relationship
| | 00:43 | between an interface called press
and a specific class called OlivePress.
| | 00:48 | I'll be creating an
actual class named OlivePress2.
| | 00:52 | Now I'll right click on press and
choose New>Interface and I'll give it a name
| | 00:57 | of Press and I'll click Finish.
| | 01:00 | The first thing you'll see that
syntactically different from a class is this keyword.
| | 01:04 | Instead of public class
I'm saying public interface.
| | 01:09 | Now within the class definition, I
can define as many methods as I want.
| | 01:13 | I'll go back to my existing OlivePress class
and I am going to take some code from there.
| | 01:18 | Let's say, for example, that I want
all classes that implement my press
| | 01:22 | interface to implement a getOil method.
| | 01:24 | I am going to select and copy
the method's signature, but not
| | 01:29 | the implementation.
| | 01:30 | Then I'll go back to press, I'll paste
that in and I'll add semicolon at the
| | 01:35 | end of declaration.
| | 01:36 | Notice that when I paste it in the
code, Eclipse automatically added import
| | 01:40 | statements for the
collection and the Olive class.
| | 01:43 | Those are required, but also notice
that I'm not implementing the code here.
| | 01:48 | I'm just saying what the name of the
method is, what its arguments are, and what
| | 01:52 | its return data type is.
| | 01:54 | I'll go back to OlivePress and
I'll take a couple more methods.
| | 01:58 | I'll take to getTotalOil method,
copy and paste it in, add the semicolon,
| | 02:04 | I'll go back to OlivePress again, and I'll
take setTotalOil, I'll copy and I'll paste.
| | 02:12 | Now when I save, I get an error.
| | 02:15 | It tells me that methods defined in an
interface can only be marked as public or
| | 02:20 | something called abstract.
| | 02:22 | Don't worry about abstract;
| | 02:23 | I'll describe that later.
| | 02:24 | What's important here is that when
you declare method signatures in an
| | 02:28 | interface, they must be public.
| | 02:31 | You can't make them private because
you can't implement the code here.
| | 02:35 | So I'll change private to public and
save my changes and the error goes away.
| | 02:40 | Next I'll show you how to create a
class that implements the Press interface.
| | 02:45 | I'll create a new class and
I'll name this OlivePress2.
| | 02:51 | Now you can actually
implement multiple interfaces in Java.
| | 02:55 | So you can add as many interfaces here as
you want, but I am only going to implement one.
| | 03:00 | I'll type in press and choose the
Press interface that I just created, I'll
| | 03:06 | click OK and Finish.
| | 03:08 | When the class is generated by Eclipse,
all of the methods that were defined in
| | 03:13 | the interface are added automatically
to the new class, just as in a superclass
| | 03:18 | subclass relationship, you use the
override annotation above all the method
| | 03:23 | signatures that you are overriding.
| | 03:25 | It is an inheritance relationship and
just like a superclass and a subclass, you
| | 03:31 | can say that an OlivePress2 is a Press.
| | 03:34 | To complete the coding process, I would add
the implementing code in each of these methods.
| | 03:40 | This would be enough to get you started though.
| | 03:42 | Now, I will say that using interfaces
in your own code is completely optional.
| | 03:48 | If you like the idea of interfaces, use them;
| | 03:51 | if you don't like them, ignore them.
| | 03:53 | But it is important to understand how
interfaces work because of the number of
| | 03:57 | times you are going to encounter them
in the core Java class library, such as
| | 04:01 | with the collection an array list
class that I described in a previous video.
| | 04:06 | If you want to create your own
interfaces for your own applications though, this
| | 04:10 | is the syntax and the process in Eclipse.
| | Collapse this transcript |
| Using abstract classes and methods| 00:00 | In previous videos, I showed examples
of creating inheritance patterns with
| | 00:04 | concrete superclasses and with interfaces.
| | 00:08 | There is another option in
Java called an abstract class.
| | 00:11 | Abstract classes combine the
best of the other two options.
| | 00:15 | Like concrete superclasses, they can
have fully implemented methods that they
| | 00:19 | can share with their subclasses, but
like interfaces, they typically aren't
| | 00:23 | instantiated directly, so they can
create a better programming contract.
| | 00:27 | I'm starting in a version of the
Olive Press application that has a concrete
| | 00:31 | superclass named Olive.
| | 00:33 | To change it to an abstract class I'll
add the keyword abstract after the public
| | 00:37 | access modifier, but before the keyword class.
| | 00:41 | Nothing has changed so far in the
functionality of this application.
| | 00:44 | I'll save and run the
application, and show that it still runs.
| | 00:48 | But the reason there are no functional
changes yet is because I'm not trying to
| | 00:52 | instantiate the Olive class directly.
| | 00:54 | Going back to the Main class, I'll
show that I am instantiating the subclasses:
| | 00:59 | Kalamata, Ligurian, and Kalamata again.
| | 01:02 | Watch what happens when I try
to instantiate Olive directly.
| | 01:05 | I will move the cursor down to the end
of the Main method, and I will add a line
| | 01:09 | of code that declares a new variable.
| | 01:11 | I will set the data type as Olive,
and I will name it olive2, and I will
| | 01:15 | instantiate it with new
Olive, the constructor method.
| | 01:20 | When I save my changes, I get the error
message, Cannot instantiate the type Olive.
| | 01:25 | So when you declare a class as abstract,
you can't instantiate it directly,
| | 01:30 | except under certain conditions.
| | 01:32 | I am just going to comment-out this code
for the moment, I will come back to it later.
| | 01:36 | The point of using an abstract class
as a superclass is that you can create a
| | 01:41 | contract that says all of this abstract
classes' subclasses promise to implement
| | 01:46 | some sort of functionality.
| | 01:47 | Here is an example, I will go back to
the Olive class and show that it has a
| | 01:52 | method called getOrigin(),
which returns a string of Greece.
| | 01:56 | Now because this class is abstract, it
can have this concrete implementation,
| | 02:01 | but the reality is that not
all olives come from Greece.
| | 02:05 | Some have an origin of Greece, some
of Italy, and some of other countries.
| | 02:09 | So I might make the decision that I'm going to
implement this method in each of the subclasses;
| | 02:14 | not in the superclass.
| | 02:16 | But I want to make sure that all
of the subclass is implemented.
| | 02:19 | So I will change this
method to an abstract method.
| | 02:23 | The syntax is just like the class itself,
you place the word abstract after the
| | 02:28 | access modifier, and in this
case, before the return type.
| | 02:31 | And then, you use the same kind of
syntax you would in an interface.
| | 02:36 | I will delete the implementation and add
the semicolon at the end of the declaration.
| | 02:41 | I'm now saying that this method must be
implemented in all classes that extend this class.
| | 02:47 | Watch what happens when I
save my changes. I get errors.
| | 02:50 | The classes Kalamata and Ligurian are
extending the abstract class and they must
| | 02:56 | implement all abstract methods.
| | 02:58 | So let's go to each of
these classes and fix the problem.
| | 03:01 | I will go to Kalamata, I will place
the cursor below all of the other methods
| | 03:05 | but within the class declaration.
| | 03:07 | I will right-click, and choose
Source > Override/Implement Methods.
| | 03:12 | This is a trick that most good Java
editors will be able to do for you.
| | 03:15 | It will look at the superclass and say,
here are the methods that you have
| | 03:19 | not implemented yet.
| | 03:20 | And then it will generate the
stub for the method for you.
| | 03:23 | I'll click OK, and I get
the new method getOrigin().
| | 03:27 | The Override directive above the
method can be retained if you like.
| | 03:31 | It is optional, but it is a good way
of noting that you are implementing a
| | 03:34 | method that was declared in the superclass.
| | 03:36 | I will delete the TODO comment and I will
replace the value null with a string of Greece.
| | 03:43 | I will save those changes and now I will go
to Ligurian, and I will do the same thing.
| | 03:49 | I will once again make a little bit of
space, right-click in the open space,
| | 03:53 | and choose Source > Override/
Implement Methods, once again getOrigin() is
| | 03:58 | checked, and I will click OK.
| | 03:59 | Then I will delete the TODO comment and
replace null with Italy, again as a string.
| | 04:05 | I'll save my changes, and
all of the errors go away.
| | 04:09 | Now to prove this works
correctly, I will go back to Main.java.
| | 04:12 | At the bottom of this code I'm
already declaring a variable named olive1,
| | 04:16 | data-typed as Kalamata.
| | 04:18 | I am going to change that so that the
data type is the superclass of Olive,
| | 04:22 | and because Olives is a collection of
olive objects, I can remove the casting syntax.
| | 04:28 | Then I will copy and paste that code,
both the declaration and the output of
| | 04:32 | the getOrigin() method.
| | 04:33 | And I will change the second set to
olive2, the name of the variable is olive2.
| | 04:39 | I will change index that I am looking for
from 0 to 1, and I will change the string.
| | 04:44 | I will save the changes and run the
application, and now I am told that Olive 1
| | 04:49 | is from Greece, and Olive 2 is from Italy.
| | 04:51 | The magic of this inheritance
architecture is that at the top level, I am only
| | 04:56 | designating the type once,
when I instantiate each object.
| | 05:00 | But later when I call the method
getOrigin(), I know that that method will be
| | 05:04 | there because of the contract created
by the abstract class, and I called the
| | 05:09 | correct method because it is
implemented as a concrete method in the
| | 05:13 | appropriate subclass.
| | 05:14 | Finally, let's go back to the
declaration where I tried to instantiate the
| | 05:18 | superclass directly.
| | 05:20 | I mentioned that you typically don't
instantiate abstract classes directly, it
| | 05:24 | is possible to do it though, as
long as you satisfy the contract.
| | 05:28 | I will remove this comment,
and I am going to recode this.
| | 05:31 | I will backspace over the semicolon
and the parenthesis, and then press
| | 05:35 | Control+Space, and I will choose
Olive as the constructor method.
| | 05:39 | Notice the notation Anonymous Inner Type.
| | 05:42 | I will double-click to select, and
take a look at what Eclipse generates.
| | 05:47 | It allows me to instantiate the Olive
class directly, but only if I implement
| | 05:51 | the abstract method getOrigin().
| | 05:53 | So I am satisfying the contract
again, but in a different way.
| | 05:57 | Instead of an explicit subclass, in
its own class file, now I am creating a
| | 06:02 | subclass inline as something
called an anonymous inner type.
| | 06:06 | I am not actually going to do this in
the application, so I will select that
| | 06:10 | code, and then comment it out, save my
changes, and run the application one last time.
| | 06:16 | So that is a look at how you
can use abstract classes in your
| | 06:19 | inheritance architecture.
| | 06:21 | Again, they combine the best
features of interfaces and of
| | 06:25 | concrete superclasses.
| | 06:26 | They support a better programming
contract then the concrete superclasses, but
| | 06:31 | have a lot more flexibility
and power than interfaces.
| | Collapse this transcript |
|
|
11. Working with FilesManaging files with the core class library| 00:00 | Once you've learned the core
principles of Java, you'll find that expanding
| | 00:04 | your knowledge of the language is a
matter of learning about more classes and
| | 00:07 | their functionality.
| | 00:09 | One of the most common tasks that all
programmers need to know how to do in any
| | 00:12 | programming language is how to work with files.
| | 00:16 | So in this chapter, I'll go through a
number of different programming tasks
| | 00:20 | including copying files, deleting them,
writing them from scratch, and so on.
| | 00:25 | And I'll start with how
to copy an existing file.
| | 00:28 | I'm going to be using a number of
classes from the core class library called the
| | 00:33 | input stream, file, and output stream.
| | 00:36 | My project, FileManagement, has a
single text file and it just has some
| | 00:40 | nonsense text in it.
| | 00:42 | My goal is to write some code that
copies this file and create a new file
| | 00:46 | with the same contents.
| | 00:48 | I'll do all the work in the Main
method of this class, CopyFile.
| | 00:52 | The first step is to create objects
that represent your existing file and the
| | 00:56 | file you want to create and for this
purpose, we use a class named file.
| | 01:01 | I'll type in the name of the class and
press Ctrl+Space and choose the version
| | 01:05 | of file from java.io and I'll name it f1.
| | 01:10 | I'll instantiate class and I'll
pass in the name of the existing
| | 01:13 | file, loremipsum.txt.
| | 01:17 | When you're working with a console
application, you can assume that the file
| | 01:21 | is in the project directory that is the root
directory where the whole project is stored.
| | 01:26 | If you are working in another
programming environment such as Java Enterprise
| | 01:30 | Applications that is web
applications, the rules for where the current
| | 01:34 | directory is may differ;
| | 01:36 | check the documentation for that environment.
| | 01:38 | Next I'll create a second file variable
and I'll have this file object refer to
| | 01:43 | the file I want to create,
I will call it target.txt.
| | 01:48 | So a file object can refer either to an
existing file or when you want to create.
| | 01:54 | Next, I'll create classes
called input and output streams.
| | 01:57 | An input stream can read the contents
of a file and an output stream can write
| | 02:02 | the contents of a file.
| | 02:04 | I'll declare a variable data typed as
InputStream, I'll press Ctrl+Space and
| | 02:09 | choose InputStream from java.io.
| | 02:11 | I'll name it in and I'll
instantiate it using a specific class
| | 02:16 | called FileInputStream.
| | 02:18 | The Java.io package has many
versions of the input stream class.
| | 02:23 | This one is specifically for files and
when I instantiate the file input stream,
| | 02:28 | I'll pass in the file reference.
| | 02:31 | Next, I'll create an output stream.
| | 02:34 | I'll follow the same pattern, I'll
type the name of the class and press
| | 02:37 | Ctrl+Space and be very specific hear;
| | 02:40 | there's more than one version of the
output stream class available to you, you
| | 02:44 | want the version in java.io.
| | 02:47 | Name the output stream out and
instantiate it using FileOutputStream.
| | 02:55 | Once again I'm making sure I select the
class from the list so I get my import
| | 02:59 | statement, and I'm referencing file number 2.
| | 03:03 | You'll see that there are errors over on
the side, don't worry about them from now;
| | 03:07 | we'll take care of them at
the end of all the programming.
| | 03:10 | The next step is to create objects that we
can use to read the contents of the file.
| | 03:15 | In Java, in order to copy a
text file, you copy a byte by byte.
| | 03:21 | There is no single method in the core
Java class library to say copy a file
| | 03:26 | and you have a choice of reading one byte at
a time or using a chunk of bytes at a time.
| | 03:32 | It's more efficient to use a chunk of
bytes, but you don't want to use too many
| | 03:36 | bytes because you don't want to chew up memory.
| | 03:38 | So in the next step, I'm going to
create an array of bytes and give it a
| | 03:43 | specific size, large enough but not too large.
| | 03:48 | I'll declare a variable as a byte array,
I'll give it a name of buf for buffer,
| | 03:52 | and I'll instantiate it using new byte [1024].
| | 03:59 | That's a nice little number.
| | 04:00 | It means that I'm going to
read 1024 bytes at a time.
| | 04:04 | Next, I'll declare a variable named
len for length, data type as in int.
| | 04:09 | I'll use that to determine how
many bytes I get back each time I read
| | 04:14 | something from the file.
| | 04:15 | If I'm just starting to read the file,
the byte array will contain 1024 bytes.
| | 04:21 | When I get to the end of the file, len
will return the total number of bytes
| | 04:25 | remaining and this will make sure that
I don't try to write bytes to the target
| | 04:29 | file that I don't have.
| | 04:31 | Now I'll create a loop with the while keyword.
| | 04:34 | I'll use off while loop with
condition and here's the condition.
| | 04:39 | I'll start with an open parenthesis
then len = in.read(buf), and then I'll
| | 04:49 | compare the return value to 0,
and close the whole condition with a
| | 04:54 | closing parenthesis.
| | 04:56 | So this part of the expression means
reading of information from the source file
| | 05:01 | to fill the byte array that will be 1024
bytes maximum and then return the total
| | 05:07 | number of bytes that you actually
got to the integer variable, len.
| | 05:12 | If the value that's returned is greater
than 0 then that means we got something.
| | 05:17 | If the value returned is 0 that means
we're done, we're at the end of the file.
| | 05:22 | Once again, you'll see an error;
| | 05:23 | again, don't worry about it.
| | 05:24 | We'll deal with that at the end.
| | 05:26 | So now I have an array of bytes that I
can use to write content to the target
| | 05:31 | file and I'll use this syntax, out.
write, I'll pass in the buffer byte array,
| | 05:39 | a beginning point of 0 of the byte array and
len, the number of bytes that I want to output.
| | 05:46 | And that's it;
| | 05:47 | I'm done copying the file over.
| | 05:50 | Before I can really be finished
though, I need to close my streams.
| | 05:55 | Input and output streams can use resources.
| | 05:58 | Not all output streams and input streams
actually use resources, but it's a good
| | 06:02 | practice to call a method
on each of them called close.
| | 06:06 | So I'll use in.close and out.close and
finally, I'll output a message saying
| | 06:16 | that the file was copied.
| | 06:23 | Now let's get to all these errors;
| | 06:25 | if you move the cursor over all the
error indicators, you'll see that they're
| | 06:29 | all saying that they are unhandled exceptions.
| | 06:32 | Some of them indicate
IOException and some of them indicate
| | 06:35 | FileNotFoundException.
| | 06:38 | You can handle all these exceptions with
a single try catch, I'm going to select
| | 06:43 | all the code, right click, and then
choose Surround With>Try Catch Block.
| | 06:49 | And you'll see that there are catch
blocks added for both possible exceptions;
| | 06:54 | FileNotFound and IOException.
| | 06:57 | So now my code should be ready
to run and we'll see what happens.
| | 07:00 | I'll run the application, I
get the message, file copied.
| | 07:06 | I'll go over to the Package Explorer,
right-click, and choose Refresh and I see
| | 07:11 | my new target file has
been successfully created.
| | 07:14 | Now, you might be thinking that's an
incredibly complex way to copy a file.
| | 07:20 | But this is how you do it
using the core Java class library.
| | 07:24 | The good news is that there are
libraries out there in the world from the Apache
| | 07:29 | Commons project that make this
kind of process a whole lot easier.
| | 07:33 | I'll show you how to download and use
that particular library later in the
| | 07:36 | course, but it's important to know how
to do this in the raw form in Java so
| | 07:42 | that if you have to write your
own specific code, you'll know how.
| | Collapse this transcript |
| Managing files with Apache Commons FileUtils| 00:00 | In our previous video, I described how
to copy the contents of the text file to
| | 00:05 | a new text file, using tools that are
available from the Java class library.
| | 00:10 | I'm working in a copy of that project
now called ApacheFileUtils that's a part
| | 00:14 | of the exercise files for this course.
| | 00:17 | In this application, I had to create a
whole bunch of different objects two file
| | 00:23 | object representing the existing file
and the target file, an input stream and
| | 00:28 | an output stream, a byte array, an
integer, and then I had to loop through and
| | 00:34 | read the file one set of bytes at
a time and write out the new file.
| | 00:37 | To all new Java developers, this seems
a bit cumbersome and almost everybody
| | 00:42 | asks the question isn't there an easier way.
| | 00:45 | The reality of the Java class library is
that it tends to give you tools in very
| | 00:50 | small pieces, and it's up to you the
developer to figure out how to plug those
| | 00:54 | tools together to get your work done,
but the good news is that the Java
| | 00:59 | programming language has been
around a long time and the Java developer
| | 01:03 | community has done a great job figuring
out what were the most common tasks that
| | 01:07 | everybody needs to do and those tasks
tend to be encapsulated and delivered in a
| | 01:13 | project called the Apache Commons.
| | 01:16 | You can get to the Apache Commons
website at http://commons.apache.org.
| | 01:23 | This project contains fully tested
reusable Java components that are completely
| | 01:28 | free and licensed for use on either Open
Source or commercial applications, most
| | 01:34 | of the components in the Apache
Commons can be used in any Java development
| | 01:38 | environment including console
applications like the ones I've been showing here,
| | 01:43 | but also including Java Enterprise
Edition applications that is web applications
| | 01:48 | and Android mobile applications.
| | 01:50 | To get to the Commons project we need,
go to the Commons Proper from the
| | 01:55 | homepage, you'll see that there are a
whole bunch of different projects you can
| | 01:58 | work with and we're going to
work with this collection IO.
| | 02:03 | On the IO page, you can click into
utility classes and then scroll down in the
| | 02:08 | list of classes, and you'll see a
class listed there called File Utils.
| | 02:13 | This is the class, that I'll be working with.
| | 02:15 | The first step to using the class is to
download the Commons IO package, I'll go
| | 02:21 | back a couple steps in my browser,
back to the IO page and in the Commons IO
| | 02:26 | menu on the left, you'll
click the download link.
| | 02:29 | There are two binary versions of the
download a tar.gz version and zipped version.
| | 02:35 | The zipped version should work
fine for either Windows or Mac.
| | 02:38 | Now, I've already downloaded and
extracted the file to my desktop, I'll open the
| | 02:43 | extracted folder and drill
down, until I see these files.
| | 02:48 | The zip file contains three jar files,
I don't need the Java docs and I don't
| | 02:53 | need the source files, what I need
are the binaries, they will have a file
| | 02:57 | extension of dot jar and the name
commons-io and the version number.
| | 03:03 | I'm using version 2.1 but any later
version should work pretty much the same.
| | 03:08 | Now, to use this file in your project
copy it to the clipboard then go to the
| | 03:14 | folder that contains your project,
I'm using Windows so I'll use Windows
| | 03:18 | Explorer and I'll go to the 11 files
folder and from there to ApacheFileUtils,
| | 03:22 | now you can place this file anywhere
on your disk you want to, but most Java
| | 03:28 | developers place existing
libraries into a folder named Lib, L-I-B.
| | 03:34 | So I'll create a new folder and I'll
name it Lib or Lib or L-I-B, I'll drill
| | 03:40 | down into that folder and paste the jar
file, then I'll switch back to Eclipse.
| | 03:45 | I'll go to the Package Explorer and
refresh the view and show that the Lib
| | 03:50 | folder and the jar file are now there.
| | 03:53 | Now here's how you incorporate the jar
file into your application, you have to
| | 03:58 | add the jar file to
something called the build path.
| | 04:01 | A new Java project always includes
these jar files that are a part of the
| | 04:06 | Java runtime environment system
library something I sometimes refer to as the
| | 04:10 | Java class library.
| | 04:12 | You're adding your own jar file to the
build path and here is the easiest way to do it.
| | 04:17 | Right click on the jar file, choose
Build Path, Add to Build Path and now, all
| | 04:23 | the classes that are in that jar
file are available to your project.
| | 04:27 | Now we're going to replace some of
the existing code, I'll double-click the
| | 04:31 | editor to expand it to full screen and
then I'm going to select starting at the
| | 04:36 | input stream declaration
and ending at the close calls.
| | 04:40 | You're still going to need to create
references to your files, the source file
| | 04:45 | and the target file, but all this
other more complex code won't be needed
| | 04:49 | anymore you can just delete it.
| | 04:52 | Next, I'll call a method of the file
utils class that's a member of the Apache
| | 04:57 | Commons Library that I added
to my project's build path.
| | 05:01 | The particular method I need is a
class method or a static method.
| | 05:05 | So I'm going to call it directly from
the class library, it'll be FileUtils.
| | 05:12 | and here is a whole list of everything
you're able to do with the class library,
| | 05:16 | including copying files, getting
directory information, moving files, reading
| | 05:22 | files, and writing files.
| | 05:24 | And I'm going to use a method called copy file.
| | 05:27 | There are a few different versions of
it, it's an overloaded method but I'm
| | 05:31 | going to use this version
that accept two file references.
| | 05:34 | There are two required methods,
the source and destination.
| | 05:38 | I'll set the first to f1 and the second to
f2 and that's it, that's all the code I need.
| | 05:45 | I remove these TODO commons because I
really don't need to do anything else,
| | 05:48 | I'll save and run the application
and I get the message file copied.
| | 05:55 | I'll go back to my Package Explorer
and I'll Refresh and I see my new target
| | 06:02 | file has been successfully created.
| | 06:04 | Now the magic of the Apache Commons
approach is that you eliminate a whole
| | 06:08 | bunch of complexity from your
application, you'll notice that my application is
| | 06:13 | showing these warnings about all the import
statements my file still has but I'm not using.
| | 06:19 | These are all the classes that were
required when I was using the Java class
| | 06:23 | library approach, that is, I was
limiting myself to using only the tools that
| | 06:28 | are available in the JRE.
| | 06:30 | But when you expand your world to
include the Apache Commons, life gets a whole
| | 06:35 | lot easier, I'm going to organize my
imports by choosing Source > Organize
| | 06:40 | Imports, and now I see that the only
classes I'm using are the File class and
| | 06:46 | the Exception classes.
| | 06:47 | The code within the Commons class still
might throw those exceptions, so I still
| | 06:52 | need to refer to them but
everything else is greatly simplified.
| | 06:56 | I strongly encourage you to take a look
through the documentation for the Apache
| | 07:00 | Commons Libraries, for example, in the
IO page, there's a link for the Java doc
| | 07:06 | for version 2.1 and the class that we
are using FileUtils has a listing of all
| | 07:11 | the methods that are available, but
you'll also see that there are dozens and
| | 07:15 | dozens of other classes available.
| | 07:17 | And this is just one of the projects in
Apache Commons, using the Apache Commons
| | 07:22 | project can make your coding much
simpler and your process of learning Java and
| | 07:27 | making it useful for your
applications a lot faster.
| | Collapse this transcript |
| Reading a text file from a networked resource| 00:00 | The class library that's a part of
the JDK includes a rich set of classes
| | 00:05 | designed for network communications.
| | 00:07 | Among the tasks that they support, they
give you the ability to easily retrieve
| | 00:12 | and read files over the web.
| | 00:14 | I'll show you one approach to doing this,
using the classes of the Java class library.
| | 00:18 | I'll mention before I get started, that
there are easier ways that require less
| | 00:22 | code if you use the Apache Commons
Library, but it's good to know what's
| | 00:27 | available in the core class library first.
| | 00:29 | I'm working in a project called
NetworkFiles and a class called Read network
| | 00:33 | file and I'm working with an empty main method.
| | 00:38 | The first step in getting a
network file is knowing its location.
| | 00:42 | You should wrap the location in the file
in an instance of a class named URL for
| | 00:46 | Uniform Resource Locator.
| | 00:48 | I'll type in the name of the class
which is all uppercase and I'll press Ctrl +
| | 00:52 | Spacebar, and choose the
version in the package java.net.
| | 00:57 | I'll name that variable url, all
lowercase and then instantiate it, using the
| | 01:02 | URL constructor method, I'll
start with a pair of quotes.
| | 01:07 | Now the purpose of the URL class is to
wrap a string that indicates the location
| | 01:11 | of the file, so now I need the file.
| | 01:14 | I'll go to Internet Explorer, I'm going to
be retrieving a dynamic XML feed from the web.
| | 01:19 | Here is the URL http://services.
explorecalifornia.org/RSS/tours.php.
| | 01:31 | When you view this file in a browser, its
format will differ from one browser to the next.
| | 01:36 | In the Internet Explorer, it might be
formatted the way you see here on the
| | 01:39 | screen or if you're working in
Chrome or Firefox, it might have a
| | 01:43 | hierarchical presentation.
| | 01:45 | But regardless of how it's
presented visually the actual format is XML.
| | 01:50 | You can see this in any browser by
right clicking and choosing view source or
| | 01:55 | some similar menu choice.
| | 01:57 | That will open the raw format of the
retrieved content and you'll see that it's
| | 02:02 | an XML file and you also
see that it's in RSS format.
| | 02:06 | RSS is the format that's
used for syndicated content.
| | 02:10 | For example, if somebody has a site
that's based on WordPress, typically you'll
| | 02:15 | be able to get an RSS feed of
their content from that site.
| | 02:19 | So now that I've confirmed that this
URL provides a valid XML feed, I'll copy
| | 02:24 | the URL to the clipboard and return to Eclipse.
| | 02:27 | I'll place the cursor inside double
quotes that I use to pass in the value to
| | 02:32 | the URL and I'll paste in the URL string.
| | 02:35 | I'll maximize my editor
so we can see all the code.
| | 02:38 | You'll see an error occur over on the
left, it's telling you about a potential
| | 02:42 | unhandled exception, we'll deal with that later.
| | 02:45 | The next step is to create an
instance of a class named InputStream.
| | 02:50 | I worked with this class in an
earlier video, when I opened a file from
| | 02:53 | the local file system.
| | 02:55 | It's the same data type but this time I
am going to create the reference to the
| | 02:59 | object by calling a method of
the URL class using URL.openStream.
| | 03:06 | So now I have my
connection to the file on the web.
| | 03:09 | I'll place the cursor after InputStream,
it looks like I didn't get my import
| | 03:13 | statement and then press Ctrl +
Spacebar and I'll make sure that I'm choosing
| | 03:17 | the input string class from
Java.I/O and there is the import.
| | 03:21 | Next I'll create an object which is
an instance of BufferedInputStream.
| | 03:26 | I'll type the beginning of the class
and then press control space and Eclipse
| | 03:30 | automatically auto completes it and
I'll name that object buff for buffered and
| | 03:35 | I'll instantiate it using the class'
constructor method new BufferedInputStream
| | 03:40 | and I'll pass in the stream object.
| | 03:42 | The purpose of the BufferedInputStream
is to do the same sort of looping that I
| | 03:47 | did in the file, allowing me to read
one or more bytes at a time as I loop.
| | 03:53 | Again, there is an indication of an
error over on the left, don't worry about
| | 03:57 | that I'll handle it later.
| | 03:58 | Now we are ready to loop
through the content of the file.
| | 04:02 | I'm going to be reading the file this
time one byte or one character at a time.
| | 04:07 | In order to collect that data
I'll create an object based on the
| | 04:11 | StringBuilder class.
| | 04:12 | I showed you how to use
this class in an earlier video.
| | 04:16 | The purpose of StringBuilder is to let
you append content or insert content into
| | 04:20 | a string without having to
constantly rebuild the string object.
| | 04:25 | I'll name the StringBuilder
object sp and I'll instantiate it with
| | 04:28 | its constructor method.
| | 04:33 | Now I'm ready to loop through the
file and read it one byte at a time.
| | 04:37 | I'll create a while loop, I'll type the
word while and press Ctrl + Spacebar and
| | 04:42 | choose while loop with condition.
| | 04:44 | And I'll set the condition to the
keyword true, that means I'm going to keep
| | 04:48 | on looping until I call the break command and
that will cause the flow to jump out of the loop.
| | 04:54 | Each time through the loop, I'm going to
read a single character from the stream.
| | 04:58 | The BufferedInputStream class has a
method called read which returns a single byte.
| | 05:03 | It will be returned as an integer
initially, so I'll declare a variable named
| | 05:08 | data and declare it as an int and
I'll get its value from buf.read().
| | 05:13 | The rules are that as long as there is
an available character to read in the
| | 05:17 | stream the read command will return
an integer value representing that
| | 05:21 | character, but if it's gotten to the
end of the stream, and the end of the file
| | 05:26 | it will return a value of negative one.
| | 05:28 | So I'll take a look at the value that
I just received, I'll use an if command
| | 05:33 | and this will be an 'if' statement and
the condition will be data has a value of
| | 05:37 | negative one, if that condition is
true that means that I'm at the end of the
| | 05:41 | document and so I'll
break out of the while loop.
| | 05:45 | But otherwise which I'll put into the
else block down here I'll append the
| | 05:50 | value that was returned first converting it to
a character using the syntax sp.append(data).
| | 05:58 | But before I can pass that data value,
I have to convert it to a character
| | 06:02 | otherwise it'll be converted as a numeric.
| | 06:05 | So I'll use casting syntax, I'll place the
cursor before the data value and put in (Char).
| | 06:13 | That means take the integer convert it to a
character and then append it to the string.
| | 06:18 | I'll place the cursor after the while
loop and finally I'll output the value
| | 06:24 | that I've collected using system.out.
println and I'll just output the value of
| | 06:30 | the StringBuilder object.
| | 06:32 | You could if you prefer convert the
StringBuilder to a string, if you're going
| | 06:36 | to keep it around in memory for a while.
| | 06:38 | Now I've still got these
errors up I have to deal with.
| | 06:41 | Each of the errors indicates that
there is an unhandled exception that could
| | 06:44 | occur, as with all such conditions
you deal with them by wrapping the code
| | 06:49 | inside a TryCatch block.
| | 06:51 | So I'll select everything that I've
coded inside the main method, I'll right
| | 06:55 | click, I'll chose surround with TryCatch block.
| | 06:59 | And Eclipse figures out which
exceptions could occur and creates catch
| | 07:04 | blocks for each of them.
| | 07:05 | I will remove the TODO comments and
my application should be complete.
| | 07:09 | I'll Save and Run it and there is the result.
| | 07:12 | The XML file is retrieved over the
web and displayed in the Console.
| | 07:17 | So again, this is one approach to
retrieving files over the web and dealing
| | 07:22 | with their content.
| | 07:23 | Once you have the content in memory,
you could save it to the local file
| | 07:27 | system, you could display it on the
screen in whatever sort of application
| | 07:30 | you're working in, or because it's structured
XML, you could search for and extract its data.
| | 07:36 | This sort of coding using the class
library of the JDK will work in any Java
| | 07:42 | environment, regardless of whether
you're working with Console applications,
| | 07:46 | Web applications, Android applications,
it's all the same code because it's all Java.
| | Collapse this transcript |
| Parsing an XML file with DOM| 00:00 | There are many ways to read XML
files in Java, there are many programming
| | 00:05 | interfaces and packages available.
| | 00:07 | They are known by their acronyms,
there is JDOM and Stacks and Sacks, but the
| | 00:12 | most venerable, the one that's been
around the longest is known as DOM or
| | 00:17 | Document Object Model.
| | 00:18 | The Document Object Model approach to
reading XML isn't the most fun or the most
| | 00:23 | concise, but it's the most
deeply embedded in the Java libraries.
| | 00:27 | And so that's the version
I'm going to show you here.
| | 00:30 | I'm not going to show you everything
about DOM that's something that would
| | 00:33 | require a whole separate course, but
I'll introduce you to some the most
| | 00:36 | critical classes that are available.
| | 00:39 | And as with the classes that I've
shown you to read files from the local
| | 00:42 | file system and from the network these
are classes that are available in the
| | 00:46 | core Java class library.
| | 00:49 | As with the previous video, I'm
going to be working with this XML feed at
| | 00:53 | services.explorecalifornia.org/rss/tours.php.
| | 01:00 | The code I'll show you will work with
any RSS feed because the structure of an
| | 01:04 | RSS file is standardized.
| | 01:07 | So let's start with this empty glass.
| | 01:09 | So the first step in reading an XML
file is retrieving it and when you're
| | 01:13 | working in the document object model world,
your first goal is to create a document object.
| | 01:19 | It takes a few classes to get there.
| | 01:21 | I'm working in an empty project
named parsexml in its class read XML and
| | 01:26 | its empty main method.
| | 01:28 | The first step is to create an instance
of a class called document builder factory.
| | 01:33 | I'll type outside DocumentBuild and
press Ctrl + Spacebar and I'll choose the
| | 01:38 | DocumentBuilder factory
class from Javax.xml.parsers.
| | 01:43 | And I'll name the variable factory.
| | 01:45 | Now this code is going to get a little
bit wide, so I'll maximize my editor and
| | 01:50 | then I'll press Enter or Return
and go to the next line and the
| | 01:54 | DocumentBuilderFactory class is a
class that you instantiate by calling it
| | 01:58 | Static Method New Instance.
| | 02:00 | So I'll call
DocumentBuilderFactory.newInstance().
| | 02:04 | Now I have an instance of that class
and I am ready to go onto the next step,
| | 02:08 | creating an instance of a
class called DocumentBuilder.
| | 02:11 | I'll type in the name of the
class and I'll choose the class from
| | 02:14 | Javax.xml.parsers the same
package as the factory class.
| | 02:20 | I'll name this one builder
and I'll get its reference from
| | 02:23 | factory.newDocumentBuilder.
| | 02:26 | Now I'm ready to create my XML document object.
| | 02:30 | The data type for this will be
document, I'll type in the name of the class
| | 02:34 | and press Ctrl + Spacebar and I'll
make sure that I'm choosing the document
| | 02:38 | class from org.w3c.dom.
| | 02:42 | This document class implements the
document object model programming interface
| | 02:47 | as defined by the W3C.
| | 02:50 | It's the same programming interface
that you might use in JavaScript and in
| | 02:54 | other programming languages, but
it's specifically implemented for Java.
| | 02:57 | I'll name this variable doc and I'll
get its reference by calling the document
| | 03:03 | builder classes parse method like this
builder.parse and then I'll pass in the
| | 03:10 | URL to the parse method.
| | 03:12 | I'll go back to my browser, I'll copy
the URL to the clipboard, I'll return to
| | 03:17 | Eclipse, type in a double quote, paste in the
URL close the string and close the statement.
| | 03:24 | When you call the parse method, it takes
care of the downloading of the file and
| | 03:29 | parsing the document and turning it
into a hierarchical set of objects that you
| | 03:34 | can traverse using
document object model programming.
| | 03:38 | Once you have the document in memory,
the next step is to get the data, you
| | 03:42 | could walk down the XML tree one level
at a time, but there's a really great
| | 03:47 | convenience method that's a part of the
document class named get elements by tag name.
| | 03:52 | If you know the tags that is the
element names in your XML file, then you know
| | 03:57 | how to get the data out.
| | 03:59 | So I'm going to create an object
which is data typed as NodeList.
| | 04:04 | In DOM a node list is kind of like an
array, it's an ordered collection of objects.
| | 04:10 | It has its own API which is a little
bit different from an array as you'll see
| | 04:14 | in a moment, I'll type in NodeList and
press Ctrl + Spacebar and choose the Node
| | 04:19 | List from org.W3C.dom.
| | 04:23 | I'll name the variable list, and
I'll populate it using the syntax
| | 04:27 | doc.GetElementsByTagName and I'll
pass in the name of an element I'm
| | 04:32 | looking for, title.
| | 04:34 | In RSS, each news item is named an
item and each item element has a sub
| | 04:41 | element named title.
| | 04:43 | For this exercise, I'm only
interested in the titles of the news articles.
| | 04:48 | So that's what I'm retrieving.
| | 04:49 | And now let's find out
how many items we got back.
| | 04:56 | I'll output a string, "There are" and
then here's a way in which the node list
| | 05:01 | class is different from an array.
| | 05:04 | With an array, you determine the size
of the array with its length property.
| | 05:08 | With the node list you call a getLength method.
| | 05:12 | It looks like this list.getLength I pressed
Ctrl + Spacebar to auto complete the code there.
| | 05:19 | Then I'll append the string items.
| | 05:23 | I'll save my changes and see if there
are any errors, I see one right here
| | 05:27 | that I need to fix.
| | 05:28 | It tells me that there's a syntax
error here and I just missed my plus
| | 05:31 | operator, here we go.
| | 05:33 | I'll save that change, and see that
there are errors from unhandled exceptions
| | 05:37 | as I've done earlier exercises, I'll
handle that by selecting the code and then
| | 05:42 | surrounding the code with a Try Catch block.
| | 05:45 | There are three possible exceptions and
Eclipse generates catch block for each of them.
| | 05:50 | I'll get rid of the TODO comments to
shorten the code and then I'm ready to save
| | 05:55 | and run the application.
| | 05:56 | And I'm told that there are 27 items.
| | 05:59 | So now, the next step is to go get
the text value of each title element.
| | 06:04 | In the document object model, each
part of the XML file is seen as something
| | 06:08 | called a node, and each
node is of a particular type.
| | 06:13 | So for example, let's say that you
had an XML node that looked like this
| | 06:17 | starting with title and ending with
title and then between those tags some text.
| | 06:24 | In the document object model, that's actually
two separate notes, one parent and one a child.
| | 06:31 | Title is an element node and the text
within it is a text node, and if you know
| | 06:38 | then you know how to get
the text out from the title.
| | 06:42 | I'm going to create a loop.
| | 06:43 | I'll use a for loop to loop through the
node list contents, I'll choose iterate
| | 06:49 | over array and I'm going to keep on
looping as long as my counter variable
| | 06:54 | doesn't exceed the length of the node list.
| | 06:57 | So I'll change args.length to lists.getLength.
| | 07:00 | Within the for loop, I'll
get the item in the list.
| | 07:04 | I am going to data type the item
that I'm retrieving as an Element.
| | 07:08 | Once again, this is a
class of the DOM interface.
| | 07:13 | I'll name the object item and I'll
set its value using casting syntax.
| | 07:19 | I'm going to be retrieving an item from
the list, the node list will return it
| | 07:23 | as a note, the superclass but I
know it's an element the subclass.
| | 07:29 | I'll retrieve it, by calling the item
method and passing in the "I" counter variable.
| | 07:35 | Finally, I'll output the
value within the element.
| | 07:39 | To do this, I'm going to walk down the
XML tree from the Element Node down to
| | 07:43 | its Child Node, the Text Node.
| | 07:46 | I know it's the first child of the
element, because text nodes always are.
| | 07:51 | So I'll use system.out.println and I'll
output item.getFirstChild and then from
| | 07:58 | there I'll call a method called getNodeValue.
| | 08:02 | When you're working with a Text Node, the
GetNodeValue method returns the string value.
| | 08:07 | I'll save and run the
application and there is the result.
| | 08:11 | A listing of all the titles, from
all the items within the RSS feed.
| | 08:17 | Now if that seems like a lot of code,
just to get titles you're right, it's more
| | 08:22 | code than is really needed and if you
switched over to one of the third-party
| | 08:26 | libraries for working with XML and
Java such as JDOM you'd find your code was
| | 08:31 | significantly smaller and easier to
work with but it's important to know what's
| | 08:36 | available in the Java class library.
| | 08:39 | When you're working with XML in the
class library that's a part of the SDK the
| | 08:43 | document object model is always available.
| | 08:45 | It works in all Java development
environments, Console applications, Web
| | 08:50 | applications, mobile applications
for Android and Blackberry, because as
| | 08:55 | always it's just Java.
| | 08:57 | There is obviously a lot to learn just
about working with the document object
| | 09:00 | model, but you can choose between that
approach and the other libraries that are
| | 09:05 | available in the Java community.
| | Collapse this transcript |
|
|
12. Preparing an Application for DeploymentCreating your own JAR files| 00:00 | The process of packaging a Java
application for deployment is radically
| | 00:04 | different from one platform to the next.
| | 00:06 | You don't package a console
application and a web application the same or a
| | 00:10 | mobile application or a desktop
application, they each have their own rules, but
| | 00:15 | the one thing that all Java platforms
have in common is the use of JAR files.
| | 00:20 | A JAR file is a Java archive file, a
compressed file in zip format that contains
| | 00:26 | compiled Java classes, but
has a file extension of .jar.
| | 00:30 | I'm going to show you how to
create a jar file from within Eclipse.
| | 00:35 | You can also do the same thing from the
command line using the JAR command from the JDK.
| | 00:40 | I'm working in a version of my
application called CreateJAR, and the first thing
| | 00:44 | I'll do is Run the application and
make sure that it runs correctly.
| | 00:48 | This version of the application
outputs the names of the olives that I'm
| | 00:51 | crushing and how many units of oil I
have and where the first all of this from.
| | 00:57 | I do this before I try to package the
application to make sure I'm running valid code.
| | 01:02 | Now, to create the JAR File, go to
the menu and choose File, Export.
| | 01:08 | In the Export dialog choose
Java, JAR File and click Next.
| | 01:13 | Make sure you've selected your
entire application including all of the
| | 01:16 | applications packages, but deselect
the options for the class path and
| | 01:21 | project files on the right.
| | 01:23 | These are Eclipse configuration
files that you don't need to include in
| | 01:26 | your deployed JAR File.
| | 01:28 | The first option here in this list
should be selected, Export generated class
| | 01:33 | files and resources.
| | 01:34 | For a console application that doesn't
include any graphical assets or other
| | 01:38 | files, you can deselect everything else.
| | 01:41 | Next, indicate the location
and name of your JAR file.
| | 01:44 | I have already filled in the value with
my project name and the name of the JAR
| | 01:48 | file I want to create, separated with
a slash character, use a backslash on
| | 01:52 | Windows and a forward slash on Mac,
alternatively you can click Browse and
| | 01:58 | select a location anywhere on
your disk to create the file.
| | 02:01 | I am creating my JAR File in my project
folder, Create JAR and I'm giving it a
| | 02:06 | name of olivepressapp.jar.
| | 02:09 | You can name the file anything you want,
just make sure you don't include any
| | 02:12 | spaces or special characters,
but you must use a .jar extension.
| | 02:17 | I've selected the option to
compress the contents of the JAR File and
| | 02:21 | deselected the other options.
| | 02:23 | I'll click Next and show you these two options.
| | 02:26 | For debugging I recommend selecting
these options, Export class files with
| | 02:31 | compile errors and warnings.
| | 02:34 | For final production, you might
want to deselect these options.
| | 02:37 | And on this final screen, there
are options for the manifest file.
| | 02:42 | A manifest file is a text file
that's automatically included in your JAR.
| | 02:46 | It includes metadata about your
application, but again, for a simple console
| | 02:51 | application, you can accept all of
these default values, click Finish and your
| | 02:56 | new JAR File will be created.
| | 02:58 | If you created it in your project
folder as I did, it should show up right away
| | 03:02 | in the package Explorer.
| | 03:03 | Now let's take a look at
the contents of the JAR File.
| | 03:06 | I'll go to my desktop to my Exercise
Files folder, from there I'll go down to
| | 03:10 | 12 Deployment to the Create JAR Folder and
here's the .jar file that I just created.
| | 03:17 | I'm going to copy it and paste it so
that I create a new version, and then I'm
| | 03:22 | going to rename this version of the
file and give it a file extension of .zip.
| | 03:26 | This will allow me to easily extract
its contents, so I can see what's inside.
| | 03:32 | Next, I'll extract its contents.
| | 03:34 | On Windows, I'll right-click and
choose Extract All and Extract.
| | 03:40 | On Mac, just double-click on the file.
| | 03:43 | If you have any special archive
utilities installed on your system, such as
| | 03:47 | WinZip on Windows, you can
extract the file with that tool.
| | 03:51 | Here is the contents of the JAR File,
there is a folder called MetaINF in and
| | 03:56 | within that the manifest file.
| | 03:58 | I'll open that up with a text editor
and show you that for a simple console
| | 04:02 | application like this, it's pretty much empty.
| | 04:05 | Now I'll go back to the main folder
and show you that your packages have been
| | 04:09 | translated to folders within the JAR file.
| | 04:12 | Here is com, Lynda, olivepress, my main package.
| | 04:17 | Here is my main compiled class and
then within the press package, there is
| | 04:21 | olivepress.class and within the
olives package my three olive classes.
| | 04:27 | So that's all a JAR File is. It's a zip file;
| | 04:30 | it has a file extension of .jar,
and its purpose is to package up your
| | 04:34 | application for deployment.
| | 04:36 | If you're using Java in another
development environment such as say Android,
| | 04:41 | take a look at the documentation for
that development environment to learn about
| | 04:45 | deployment options for that platform,
regardless of how you're deploying your
| | 04:49 | Java application, JAR Files are
almost certainly going to be involved.
| | Collapse this transcript |
| Understanding the classpath| 00:00 | Once you've packaged up an application
as a JAR File you're ready to run it from
| | 00:04 | the command line, but in order to run
it from the command line, you need to
| | 00:08 | understand how the
concept of the class path works.
| | 00:11 | I'll described how to use the class
path and how to set it on both Mac and
| | 00:15 | Windows in this exercise.
| | 00:16 | I'm working in the class path project,
a version of my olivepress application
| | 00:21 | that I've already compressed into a JAR File.
| | 00:24 | If you have access to the Exercise
Files you can use this file or you can use
| | 00:28 | any other JAR File that you want to create.
| | 00:31 | I'm going to copy this file to my
desktop, so I don't have to worry about the
| | 00:35 | specific folder in which it's
located, once I go to the command line.
| | 00:39 | I'll right-click on the file and copy,
then I'll go to the desktop and paste.
| | 00:44 | Now, I'll open up a command window, on
Windows, I'll run the cmd application
| | 00:50 | and on Mac, open terminal, and then
switch to your desktop folder, do a
| | 00:55 | directory listing, type dir on
Windows or LS on Mac, and you'll see the
| | 01:01 | OlivePressApp.jar file there.
| | 01:04 | Now, to run the application you need to
know the complete path of the Main class.
| | 01:09 | I'll go back to Eclipse briefly, and
show you within Main.java that the package
| | 01:15 | is com.lynda.olivepress, and the class is main.
| | 01:21 | In order to run the class from the
command line you need to know both of
| | 01:24 | those bits of information, you'll put
the package and the class name together
| | 01:28 | separated with a dot, and that's how you
launch the application using the Java tool.
| | 01:33 | I'll go back to the command window and I'll
try running the application the first time.
| | 01:39 | I'll type java com.lynda.olivepress.Main,
and I get the error could not find or
| | 01:48 | load Main class and then the
full path of the class that I typed.
| | 01:52 | Now I typed that correctly, but the
problem is that Java doesn't know where to
| | 01:57 | find the class, here's how you tell it.
| | 02:00 | You tell Java where the class is that
you want to run by setting the class path.
| | 02:05 | The class path is a list of file locations.
| | 02:08 | Typically it starts with a single dot,
meaning the current directory, and then
| | 02:13 | lists all of the folders and JAR
Files that contain compiled classes.
| | 02:18 | You can set the class path either
as part of the Java command or as an
| | 02:22 | environment variable and I'll show you both.
| | 02:25 | Here's how you incorporate the class
path into the command that starts the
| | 02:28 | application, start with Java and then -
classpath, you can shorten that to -cp
| | 02:36 | if you prefer, then type in a
dot for the current directory.
| | 02:40 | On Windows, add a semicolon on Mac or
Linux add a colon, and then type in the
| | 02:47 | name of your JAR File.
| | 02:48 | I'll start by typing olive and then I'll
tab, and on either Mac or Windows, that
| | 02:53 | should auto complete the class path.
| | 02:55 | Now type in the full path of your
starting class com.lynda.olivepress.Main,
| | 03:02 | make sure you spell it exactly
correctly, it is case-sensitive, regardless of
| | 03:07 | whether you're working on Windows
or Mac press Enter or Return and the
| | 03:11 | application should run.
| | 03:12 | Now you can also set the class path
as an environment variable, this works
| | 03:17 | pretty much the same way on either
Windows or Mac, but again the difference will
| | 03:21 | be how you separate the values.
| | 03:23 | You use a semicolon to separate the
values on Windows and colon on Mac.
| | 03:28 | This time I'll type SETCLASSPATH put it
in all uppercase, it doesn't matter on
| | 03:34 | Windows, but it does on Mac, and then
an equals operator, and then just as I
| | 03:39 | did before I'll type in a dot, then a ;
on Windows or a : on Mac, and then the
| | 03:45 | name of the file, and once again, I can type
the beginning of the file name and press tab.
| | 03:50 | I'll press Enter or Return and then
this time I won't need to add the -class
| | 03:56 | path argument to the command,
because the value was already set in the
| | 04:00 | environment variable.
| | 04:01 | I'll type in java com.lynda.olivepress.
Main, and now my application works again.
| | 04:09 | When you set an environment variable
this way, you're setting it only for the
| | 04:13 | current command window session.
| | 04:15 | For command on Windows or terminal on Mac,
and when you close the command window
| | 04:20 | or you close terminal,
that setting will be lost.
| | 04:23 | You could set this permanently in
what Windows calls the system environment
| | 04:27 | variables, or through a special file
on Mac that I don't recommend doing it.
| | 04:32 | It's better to create a batch file or a
bash script to set these values if it's
| | 04:37 | something you need to do over and over
again, but again, you can set the class
| | 04:41 | path either as part of the Java
command, or as an environment variable,
| | 04:46 | whichever works best for you.
| | 04:48 | Once you know how the class path works,
you can get started on your own Java
| | 04:52 | applications, running them either
from within Eclipse as we've been doing
| | 04:55 | throughout the entire course, or in the
command window, if that works better for
| | 05:00 | your debugging purposes.
| | Collapse this transcript |
| Documenting code with Javadoc| 00:00 | Java docs are files that you can
generate out of your source code to document
| | 00:05 | your code, because a well-designed
Java application can contain dozens,
| | 00:09 | hundreds or even thousands of Java
classes, documentation is critical for
| | 00:13 | long-term maintenance.
| | 00:15 | As you code, it's a good idea to add
comments to your code to describe how the
| | 00:19 | classes are designed to work.
| | 00:20 | Then later on you will be able to look
at the documentation and figure out how
| | 00:24 | the application was architected.
| | 00:27 | The first step to generating Java
docs is to add what are known as element
| | 00:32 | comments into your code.
| | 00:33 | An element comment is a comment that
applies to a particular element of the
| | 00:37 | code, such as a class, a
method, a field and so on.
| | 00:40 | Here's how you add an element comment.
| | 00:42 | I'm working in a version of the
project called Java docs and I'm in the Main
| | 00:47 | class, I'll double-click the name of
the class and then I'll go to the menu and
| | 00:51 | choose source, generate element comment.
| | 00:54 | Notice that there's a
keyboard shortcut available for this.
| | 00:58 | By default, Eclipse adds an
annotation my name as the author.
| | 01:03 | An element comment is like a block
comment, it starts with a / and then *, but
| | 01:08 | then it adds another * on the first line,
that double asterisks is the indicator
| | 01:13 | that this is an element comment that
should be used by the Java Doc system.
| | 01:18 | You can add other
annotations to your element comments.
| | 01:20 | I'll place the cursor on the next line
and type in @ character and I'll get a
| | 01:25 | list of the known annotations, and I'll
choose version, and I'll set it to 1.0.
| | 01:31 | You can also add your own comments.
| | 01:33 | These typically go before the annotations.
| | 01:36 | I'll place the cursor on the first line
of the comment and press Enter or Return
| | 01:40 | and I'll say This is the main class for my app.
| | 01:45 | I'll Save that change and scroll down a
little bit and show you that all of this
| | 01:49 | class has a main method and I'll
decide, I don't need to comment anymore of
| | 01:53 | this, but I do want to add
comments to some of my other code.
| | 01:57 | So I'll go to the Olive class.
| | 01:59 | I'll double-click the class name and
choose Source, Generate element comment,
| | 02:04 | I'll decide I don't need to put in my
author information, I already have that in
| | 02:08 | the Main class, but I will add a comment,
This is a superclass for all olives.
| | 02:15 | You can also add element comments for
fields and methods, I'll double-click
| | 02:20 | BLACK and choose Source, Generate
element comment, and say This is for black
| | 02:26 | olives and I'll double-click GREEN and
generate the comment and say This is for green olives.
| | 02:32 | I'll scroll down and select the crush
method and add a comment for that and say
| | 02:42 | call this to crush a single olive.
| | 02:46 | Finally, I'll go to the kalamata.java
file, and I'll comment this particular
| | 02:52 | method which was only
implemented on this particular class.
| | 02:55 | I'll select the method name, add a
comment, and I'll add This method is
| | 03:01 | unique to kalamata olives.
| | 03:06 | Now I'm ready to generate my Java docs.
| | 03:09 | I'll make sure I saved all of my
changes and I'll go to the menu and
| | 03:12 | choose File, Export.
| | 03:15 | In the Export dialog I'll select Java
and then Java Doc and click Next, in this
| | 03:21 | screen I'm asked what the Java.command is?
| | 03:24 | If this value is blank, click the
configure button and navigate your JDK
| | 03:29 | installation folder, and then to
the bin folder, and the java.command.
| | 03:34 | Next, indicate what types you are
going to generate Java docs for?
| | 03:38 | I'd recommend selecting the entire application;
| | 03:41 | this will make sure that you're generating
Java docs for all packages and all classes.
| | 03:46 | You can also be specific about which
access modifiers you're creating Java docs for.
| | 03:50 | I'd recommend the default of public.
| | 03:54 | Next, Browse and indicate where
you want to generate your docs.
| | 03:58 | I've selected a new folder named doc
under my project folder that value may
| | 04:02 | appear by default on your system, but
if it doesn't, browse and select it.
| | 04:07 | Now I'll click Next, and here I'm asked
if I want to include referenced archives
| | 04:11 | and projects, I'll leave these all unselected.
| | 04:15 | If you were to select any of these, you
would also get Java docs for classes in
| | 04:19 | the core Java class library, and
you probably don't want to do that.
| | 04:23 | You can also set an explicit document
title and indicate which of these tags
| | 04:28 | you want to document.
| | 04:29 | I'll click Finish and it will take just
a few moments to generate the Java docs.
| | 04:35 | I'll close the window and here's my
new doc folder in my project folder, if
| | 04:39 | you don't see it there, try refreshing,
right-click on the project and choose Refresh.
| | 04:46 | I'll open the doc folder and I'll see a
whole bunch of files that have been generated.
| | 04:51 | The beginning file is named index.
html working in Eclipse you can just
| | 04:56 | double-click it, and it
will open in a browser view.
| | 05:00 | I'll double-click the tab of the
browser view to expand it to full screen and
| | 05:05 | here's all my documentation.
| | 05:07 | I'll click into the olivepress
package and see my main class and here's my
| | 05:11 | comment "This is the main class for my app."
| | 05:14 | Here is my version and here
is the author information.
| | 05:18 | Now, I'll go to the olives package over
here and I'll click into the olive class
| | 05:24 | and I'll see the comment, This is a
superclass for all olives, and I'll also see
| | 05:29 | the comments for my black
and green static long fields.
| | 05:32 | And finally I'll go to Kalamata, where I
added the comment for the custom method.
| | 05:37 | I'll scroll down to get
origin, and there is my comment.
| | 05:41 | Now, because this is being generated in
HTML, you can use a certain small set of
| | 05:46 | HTML tags to mark up your comments.
| | 05:50 | I'll close the browser view and I'll
go back to Kalamata, and I'll place the
| | 05:55 | cursor before Kalamata and I'll add a
beginning b tag, and then after Kalamata,
| | 06:01 | I'll add a closing tag.
| | 06:03 | I'll Save and then I regenerate the
Java docs, I'll go to File, Export, Java
| | 06:09 | Doc, Next, I'll make sure that I
selected the entire Java docs application
| | 06:14 | again, and then I'll click Finish and
that will overwrite the existing files.
| | 06:21 | I'll go back to my Doc folder, I'll
open index.html, I'll go to Kalamata and
| | 06:28 | scroll down, and there is the result.
| | 06:31 | The word, Kalamata is bolded.
| | 06:34 | So the last thing I'll show you is that
in Eclipse there's a Java docs tab which
| | 06:38 | will show you Java docs
information for classes in your application.
| | 06:42 | When you're working with classes from
the Java class library, all you need to do
| | 06:47 | is place the cursor in the name of the
class and then look in the java.tab, and
| | 06:51 | if everything is configured correctly,
which it should be by default, you should
| | 06:55 | see simple Java docs displayed there,
but once you've generated your own Java
| | 07:00 | docs, this will work for
your application as well.
| | 07:03 | I'll go to the Kalamata.java file and
I'll click onto the getOrigin method
| | 07:08 | and I'll see the Java doc comment
that I just generated, this method is
| | 07:12 | unique to Kalamata olives.
| | 07:14 | It's a good idea as a Java programmer
to get used to adding element comments as
| | 07:19 | you create new methods, fields, and classes.
| | 07:22 | That will then ensure that when
you're ready to generate the Java docs, you
| | 07:26 | don't need to go back and add all that
documentation later on, that's a tough thing to do.
| | 07:32 | If you do it in small pieces as you
code, and as the purpose of the elements
| | 07:36 | is fresh in your mind, it'll result in
well-documented and well maintainable applications.
| | Collapse this transcript |
|
|
ConclusionGoodbye| 00:00 | Hi! David here again.
| | 00:02 | Thanks for watching this
course, Java Essential Training.
| | 00:05 | Learning the language is just the
beginning, you're now ready to move on and
| | 00:09 | learn how to build applications for a
wide variety of Java development and
| | 00:13 | runtime environments.
| | 00:15 | If you're interested in mobile
applications check out Lynda.com's course,
| | 00:19 | Android App Development with Java
Essential Training, or you might be
| | 00:23 | interested in building web
applications for Java Enterprise Edition Servers,
| | 00:27 | such as JBoss and Tomcat.
| | 00:29 | The Apache Commons project, which I
described in the chapter about working with
| | 00:33 | files has an enormous amount of
existing code you can use to get your
| | 00:38 | applications working quickly.
| | 00:40 | However you plan to use Java, I hope
this course gave you the information you
| | 00:44 | needed to get started.
| | 00:45 | Thanks and happy coding!
| | Collapse this transcript |
|
|