navigate site menu

Start learning with our library of video tutorials taught by experts. Get started

Java Essential Training
Mark Todd

Java Essential Training

with David Gassner

 


Join author David Gassner as he explores Java SE (Standard Edition), the language used to build mobile apps for Android devices, enterprise server applications, and more. This course demonstrates how to install both Java and the Eclipse IDE and dives into the particulars of programming. The course also explains the fundamentals of Java, from creating simple variables, assigning values, and declaring methods to working with strings, arrays, and subclasses; reading and writing to text files; and implementing object oriented programming concepts.
Topics include:
  • Understanding the history and principles of Java
  • Installing Eclipse and Java
  • Compiling and running from the command line
  • Managing memory and performing garbage collection
  • Declaring and initializing variables
  • Writing conditional code
  • Building and parsing strings
  • Debugging and exception handling
  • Using simple arrays
  • Creating custom classes
  • Working with encapsulation, inheritance, and polymorphism
  • Managing files
  • Documenting code with Javadocs

show more

author
David Gassner
subject
Developer, Programming Languages
software
Android , Java , Eclipse
level
Beginner
duration
7h 17m
released
Dec 14, 2011

Share this course

Ready to join? get started


Keep up with news, tips, and latest courses.

submit Course details submit clicked more info

Please wait...

Search the closed captioning text for this course by entering the keyword you’d like to search, or browse the closed captioning text by selecting the chapter name below and choosing the video title you’d like to review.



Introduction
Welcome
00:04Hi! My name is David Gassner.
00:06And I'd like to welcome you to Java Essential Training.
00:09If you want to build native Android apps, dynamic web applications for use on a
00:13Java Enterprise Edition Server or applets that are delivered through a web
00:18browser, you need to know Java.
00:20In this course I'll show you how to download and install the Java Development
00:24Kit on Windows and Mac OS X and how to get started with Eclipse, the free
00:30cross-platform IDE for Java developers from the Eclipse Foundation.
00:34I'll introduce you to the basics of the programming language including its data
00:39types, keywords and best practices.
00:42Since Java is a peer object-oriented language I'll describe how it implements
00:46concepts like encapsulation, inheritance, and polymorphism.
00:51The goal of this course is to get you started with Java so you can go on to
00:55build mobile, desktop, Web or other types of applications.
01:00So let's get started learning Java.
Collapse this transcript
Is this course for you?
00:00This course, Java Essential Training is designed to teach you the basics of the
00:05Java programming language.
00:07You might be asking yourself whether this is the right course for you, and here
00:10are some questions to ask.
00:12First of all, what kind of software do you want to create?
00:15Java is used to program a variety of applications.
00:19You can use Java to build Web-based dynamic applications using programming
00:24models known as servlets or Java Server Pages, also known as JSP.
00:29Java is also used to program mobile applications, that is, applications that are
00:34for the Android or BlackBerry mobile platforms, both phones and tablets.
00:39And there are many other types of applications you can build with Java, and I'll
00:43explain some of these in later videos.
00:45There are some things however that Java is not.
00:48Java is not JavaScript.
00:50JavaScript is the dynamic scripting language that's incorporated into all modern
00:55Web browsers and is used to create dynamic applications where the application
01:00code is executed by the browser itself.
01:03Even though Java and JavaScript share the term Java, they are very
01:07different languages.
01:09They have some similarities in their syntax and appearance, but the way you use
01:13them and the way they work internally is completely different.
01:17So if your goal is to learn how to build dynamic webpages, where the code is
01:21executed in the browser, you should be learning JavaScript.
01:25Java is also not used to build native mobile apps for all platforms.
01:29It isn't used to build native iOS applications that is applications for
01:34the iPhone and iPad.
01:35For that you should use Objective C and the Xcode IDE, and it's also not used to
01:41build native Windows Phone applications.
01:44Windows Phone is the operating system of the new phone platform from Microsoft.
01:49For those types of applications you should use either C# or VB.NET and some
01:54version of the Visual Studio environment.
01:57Some people think that Java isn't the easiest language in the world.
02:01It is a compiled language and it has very strict data typing rules.
02:05And in order to be effective in Java you need to understand something
02:09about object-oriented programming, but I'll be teaching you all that
02:12during this course.
02:14And the other thing that's true of Java is that it's not the most difficult
02:17language in the world.
02:19Java is an incredibly consistent language.
02:22Once you learn the rules of Java, once you learn how to think in the
02:25languages' terms you will find that you can extend your tools and your
02:29capabilities very, very quickly.
02:32So who is the target audience for this particular course?
02:36The course is designed for anybody who wants to build software using the Java
02:39programming language, but specifically it's designed for those who already have
02:44a basic programming vocabulary.
02:47Software developers as with many trades have their own unique vocabulary
02:52incorporating terms that they all understand.
02:55Many of these terms have different meanings from one programming language to
02:59another, but programmers can talk to each other.
03:02So if you are not sure whether you have that vocabulary already in place,
03:06here is a little test.
03:08Can you answer these questions?
03:10You don't have to answer them in the context of Java, but can you answer these
03:15very simply in reference to any programming language?
03:18First, what is a programming statement?
03:21What is a variable?
03:22What is a function, and what is a condition or a logical condition?
03:27If you can answer these questions then you are ready for this course.
03:31I'll show you how these terms are used in Java and how they are implemented in
03:36this particular programming language.
03:39If these terms are foreign to you and you haven't worked with any programming
03:43languages before, you might first want to watch this course.
03:47Foundations of Programming: Fundamentals.
03:50This Lynda.com course explains these terms and shows you how they are
03:54implemented in a variety of programming languages, including Java;
03:58and after you watch this course you'll be completely ready for Java
04:01Essential Training.
04:04For those who can answer those questions and who might have worked in at least
04:07one previous programming language, you'll find that certain programming
04:11languages get you ready for Java more easily than others.
04:15Java is a C-Style language, that is, its syntax and basic appearance look very
04:21much like the language C and there are a number of programming languages who
04:25share these characteristics.
04:28If you've worked in any of these languages you'll recognize Java very, very quickly.
04:33They include C, C++, C#, JavaScript, and even PHP.
04:42All of these languages share basic syntax rules, and you'll be able to adapt
04:47your existing knowledge to Java very fast.
04:50If you've worked in any other languages those languages might not match the
04:54basic appearance of Java.
04:56These might include Visual Basic or VB. NET or ColdFusion developers, ColdFusion
05:02Markup Language or Assembly language and many others.
05:06If you know any of these languages or any others that don't share C-Style
05:11syntax, you should still be ready for this course because along the way I am
05:15going to explain Java syntax and Java concepts, and how to use Java variables
05:22statements, functions, and conditional logic.
05:25As long as you've worked in some programming language and can answer those basic
05:29questions, you are ready.
05:31So let's get started learning the Java programming language.
Collapse this transcript
Using the exercise files
00:00If you are a premium member of the lynda.com Online Training Library or if you
00:04are watching this course on a disc, you'll have access to the Exercise Files
00:08that are delivered with the course.
00:10I've copied the Exercise Files to my Desktop, but you can place them anywhere on your system.
00:15The Exercise Files for this course consists of a set of Java project files built
00:20for use in Eclipse, but the source code in these project files can be used in
00:24any Java development environment.
00:26On my system there is a file named .metadata.
00:29You won't see it on your system if you haven't opened Eclipse yet, but it will
00:33be created automatically as you work through the course's exercises.
00:37Each chapter is represented by a folder in the main Exercise Files folder.
00:41So for example Chapter 03 has a set of four subfolders.
00:46Each of these subfolders is an Eclipse project.
00:49For example the APIDocs folder contains an Eclipse project for learning
00:54about API documentation.
00:56Within this folder you'll see a source folder that contains the actual Java
01:00source code and a bin folder where the application is being compiled.
01:06If you are working on Windows you'll also see these two files .classpath and .project.
01:11These are files that are generated by Eclipse and that are used to configure
01:15the Eclipse project.
01:17If you are working on Mac you might not see these files in Finder but they are still there.
01:22Here is how you use each project.
01:27I'll open Eclipse, which I'll show you how to install very early in the
01:30course, and I'll show you that in this copy of Eclipse I already have four projects open.
01:35Now I am going to import another project.
01:38From the menu I'll choose File> Import>Existing Projects into Workspace.
01:44I'll click Browse and navigate to my Exercise Files.
01:49If I choose this folder as my root folder I'll see all available projects
01:54throughout the entire folder including all of the beginning projects and all of
01:59the solution projects.
02:01Alternatively you might decide you just want to import one chapter's worth of projects.
02:06I'll choose 04_Primitives and now I'll see a much shorter list.
02:11Or you can choose to import just a single project.
02:15This time I'll choose 04_Primitives> Booleans and click OK, and I'll see only the
02:21project in that folder.
02:22Whether you import one project at a time or a whole chapter or all the projects
02:27for the entire course it's completely up to you.
02:31When you are done with a project I recommend that you at least close it or
02:35optionally delete it from Eclipse.
02:37To close a project right-click on it in the Package Explorer and close the project.
02:43If you prefer to get rid of the project completely just select the project
02:47folder and press Delete.
02:49You'll be prompted to remove the project from the Eclipse workspace.
02:54Don't check this option and then the project will still be there on disc.
02:58If you do check the option you are actually deleting the project and all of
03:02its source code from the disc and you'll have to extract it from the Exercise Files again.
03:07So that's a look at how to work with the exercise files for this course.
03:11If you don't have access to the Exercise Files you can use your own Java code.
03:16In each video in the course I'll show you all of the code that I am working with.
03:20So you can either copy that code into your application or you can create
03:24your 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:00The Java programming language has a long history.
00:03It started in 1991 when Sun Microsystems began something called The Green Project.
00:10The goal of The Green Project was to create a new portable programming language,
00:15one that could be used to create applications that could be run on multiple
00:18operating systems without having to recompile or port the code.
00:23The original name of the language was Oak, for a large oak tree that stood
00:28outside the windows of the developers' offices.
00:30But between the time the project began and the time the language was released,
00:34it was renamed as Java supposedly because of the amount of coffee that the
00:39developers were drinking.
00:41Java was first released to the public in 1995 and thereafter saw a rapid
00:46evolution and change.
00:48Starting in 1995 the phrase Write Once, Run Anywhere was popularized.
00:54Again the goal of Java was that you'd be able to write a program, you'd be able
00:58to compile it once and then run it on UNIX, on Windows, on Mac, and other
01:05operating systems for which there was a Java virtual machine.
01:09Java evolved swiftly.
01:12In the early years there was a new release about once a year.
01:16In 1996, Sun released the first complete Java Developers Kit or JDK supporting a
01:22broad range of application development tasks, version 1.1, the following year
01:28saw improvements to the object- oriented nature of Java with Inner classes and
01:32JavaBeans, the JDBC API for talking to databases, RMI or Remote Method
01:39Invocation for distributed systems, and Reflection for improving the dynamic
01:45capabilities of the language.
01:47In 1998, Java was rebranded as J2SE or Java 2 Standard Edition.
01:55The Standard Edition distinguished it from Enterprise Edition which was the
01:59framework for building large scale Web applications.
02:03The version number was Java 2, version 1.2.
02:07A little confusing, and the 2 after the J stuck around for many, many years, but
02:12the versions were incremented using point numbers.
02:15Java2SE 1.2 included the swing graphical API for building Desktop applications,
02:23the collections framework for managing multiple data elements, and new tools
02:28including the Just-In-Time compiler and the Java Plug-in which standardized the
02:33version of Java across Web browsers.
02:35A couple of years later J2SE 1.3 added new tools including the HotSpot JVM,
02:42a new version of the Java Virtual machine, the Java Sound API and improved debugging.
02:48In 2002 version 1.4 added new tools in the language, and then in 2004, a major
02:56new release came out J2SE 5.0.
02:59This version was known both as 1.5 and 5.0.
03:03But subsequent new releases would just use the major numbers.
03:07So it'd become 5.0, 6.0, 7.0 and so on.
03:10J2SE 5.0 was a major new change for the language, a new feature called Generics
03:17was implemented that lets you strongly data type collection elements.
03:22Enumerations, variable arguments, and looping with for-each were all improved.
03:28And in terms of language syntax this was really the last major change to the language.
03:34Everything since then has been nibbling around the edges.
03:37In 2006 Java 6.0 came out.
03:41It improved performance for database connectivity, improved graphical
03:45programming and added other small features to the language.
03:49And then the pace of change slowed, from 2006 to 2010 Sun Microsystems released
03:57occasional maintenance releases to the language.
03:59So you'd have Java 6.0 Maintenance Release 10, 11, 12, and so on.
04:04And as of this recording Java 6.0 Maintenance Release 29 is the most recent
04:10version of that version of Java.
04:12Then in 2010 a major event occurred. Oracle bought Sun.
04:17Sun Microsystems and all of its assets including the Java programming language
04:22became a part of Oracle.
04:24And as of the time of this recording Oracle Corporation manages Java along with
04:29JCP, the Java Community Process that Sun began.
04:34In 2011 J2SE 7 was released.
04:38It included minor changes in the language listed here and some other small scale tools.
04:44And we are expecting another version of Java down the road, possibly known as
04:49J2SE 8.0 and it would include many things that were deferred from the version
04:537.0 effort including something called Lambda expressions or closures.
04:58If you don't know what those are, don't worry about it, they are not currently a
05:02part of the Java language.
05:04So that's what's happened in the world of Java since it began.
05:08Java has been around in strength since 1995 and it's been used in a lot of
05:13programming environments, and I'll talk about some of those programming
05:16environments in the next video.
Collapse this transcript
Understanding the principles of Java
00:00The Java programming language has been developed over the years following some
00:04very strict principles.
00:06The five principles of Java as declared when Java was created include, first,
00:11that it's a simple, object- oriented, and familiar language.
00:14Its simplicity lies greatly in its consistency.
00:18Once you learn how to do one thing in Java, you know how to do it the same
00:21way throughout the language because it never deviates from the way the
00:25language is architected.
00:27It's an object-oriented language.
00:29So once you understand the principles of encapsulation, inheritance, and
00:34polymorphism and how those are implemented in the Java programming language,
00:38you'll have a much better sense of how to architect your applications.
00:42And for developers who've worked with C-Style languages like C and C++, the
00:48syntax of Java is very familiar.
00:51Java was created to be robust and secure.
00:54Its robustness lies greatly in its object-oriented characteristics, because
00:59you're designing everything as an object, everything has methods or functions
01:04and properties also known as fields.
01:06And you create applications by combining multiple classes together.
01:11This lets you create your code in small chunks and it makes it easy to debug and
01:16maintain your applications over time.
01:19Java was designed to be portable, so that you'd be able to compile it once and
01:23then run your application on multiple operating systems and processors.
01:27Java was created to be high-performance.
01:30The original version of the Java Virtual Machine wasn't as fast as C++
01:34applications, but over the years it's been improved enormously, and today
01:39Java applications run just as fast or sometimes even faster than applications built in C++.
01:46And finally Java was created as an interpreted language, it supports
01:51multithreading and it's dynamic.
01:53Interpreted, means that the application is compiled to a format that's
01:57interpreted at runtime rather than being run as machine code directly, this is
02:03what makes the applications portable.
02:05It's multithreaded, and it makes it easy to build applications that do more than
02:09one thing at the same time.
02:11And it's dynamic, in that it can change data types at runtime as long as those
02:16data types are compatible with each other.
02:19Here is the runtime architecture of Java.
02:22Again, it's an interpreted language, the application is compiled to
02:26bytecode rather than machine language, and that's what makes it portable
02:29between operating systems.
02:30Here is the software stat that's used at runtime when you run your application.
02:37You start with the operating system.
02:39You can run Java applications on Windows, Mac, Linux, Solaris, and any other
02:45operating system for which there is a usable Java Virtual Machine.
02:49The Java Virtual Machine you use most of the time will be the one provided by
02:53Oracle, the one that was created by Sun Microsystems, but there are other JVMs
02:58out there provided by IBM, the Virtual Machine that's provided for Android by
03:03Google and many others.
03:06On top of the Virtual Machine you add the core runtime and additional libraries.
03:11The core runtime is sometimes called the Java Class Library, and it consists of
03:16all of the functionality that's provided with the core Java developer toolkit.
03:21And finally your application runs on top of all that once again as compiled bytecode.
03:28So let's compare Java to a couple of popular languages.
03:31First C++, Java was originally created by C++ developers and they had in mind
03:38improving the developers' lot.
03:41Here are some ways in which Java is different from C++.
03:44If you're a C developer all of your code can be run in C++ as well.
03:49The two languages are compatible with each other, that's not true for Java.
03:53Even though Java has syntax that's very similar to C and C++, its code is unique.
04:00It has its own rules and its own syntax.
04:02I have mentioned earlier that C++ is compiled to native machine language and
04:08while that makes it very fast and gives it access to low-level functions, it
04:12means that your application has to be recompiled for each operating system and
04:17processor that you want to target.
04:19Java is compiled to bytecode.
04:22Because C++ is compiled to native machine language, it allows direct calls
04:27to the native system.
04:28In Java there is an interface called Java Native Interface sometimes called JNI,
04:34that lets you call those native functions through the JVM.
04:37C++ lets you write once and then as long as you followed standard C++ syntax you
04:44can recompile for each operating system you are targeting, whereas the
04:48principles of Java say that you can write once and run anywhere.
04:52Java runs in a protected virtual machine environment, and again, you have to go
04:57through that JNI interface to make those low-level system function calls.
05:02Here's a way in which the two languages are very different.
05:04C++ requires explicit memory management and uses pointers.
05:09C++ applications as a result can have memory leaks and it's up to the developer
05:15to make sure that they've sealed up all the holes in their application.
05:19In Java, memory is managed for you.
05:22When you create instances of classes or objects, the Java Virtual Machine
05:27automatically allocates the memory.
05:29And when you're done with the objects the JVM sweeps up the memory by destroying
05:34dereferenced objects, this is called the Garbage Collector.
05:38This means that in Java applications you don't have to know specifically how
05:42much memory is being used at any given time, you still have to pay attention to
05:46making sure that you only create the objects you need.
05:50And in C++ you can use multiple inheritance, this means that when you define an
05:56object you can inherit functionality for multiple super classes.
06:00The Java inheritance model is single inheritance so you can only inherit
06:05directly from a single superclass.
06:07This makes it easier to figure out where there are problems when your
06:10application has bugs.
06:13Let's also compare Java to JavaScript.
06:16Even though the names of these languages share the term Java, they are really
06:20not closely related.
06:22Java again wasn't compatible with previous languages even though it
06:26borrowed syntax from C.
06:28Java has morphed into a standard known as ECMAScript or ECMAScript.
06:34Other languages that are based on the ECMAScript standard include Adobe's
06:38ActionScript 3.0 and JScript from Microsoft and a number of others.
06:44Java is compiled to bytecode and interpreted at runtime.
06:48JavaScript is interpreted directly from source code.
06:52Java can make native function calls through the JNI interface, while in
06:56JavaScript at least as it's implemented in a browser, is restricted to something
07:01called a browser Sandbox.
07:03It can only play in the Sandbox, and it can't make native function calls.
07:09Java is write once, run anywhere.
07:11JavaScript is even more portable in the sense that it has brought compatibility
07:16in many browsers and many operating systems.
07:19Java runs in a protected virtual machine but you have to explicitly have that
07:24virtual machine installed.
07:26And in a similar fashion JavaScript is executed by the browser and restricted to
07:31that browser sandbox for security.
07:34Both languages manage the memory for you, neither requires that you specifically
07:39allocate or deallocate memory.
07:41And in terms of inheritance, Java uses a traditional class-based inheritance
07:47where you define classes and then inherit their functionality.
07:51JavaScript uses something called prototype-based inheritance.
07:55This model allows you to add functions, properties, and other functionality to a
08:00pre-defined class at runtime, something Java doesn't allow you to do.
08:05So that's a look at the principles of Java and how you might compare this
08:09language to C++ and JavaScript.
08:13In the continuum of languages you might play C++ at the strictest level, Java
08:19somewhere in the middle, and JavaScript at the most dynamic.
08:23And you typically use Java when you want to build applications that rely on that language.
Collapse this transcript
Java compilation and syntax
00:00When you download and install Java from Oracle you are installing a number
00:05of development tools.
00:06The package is called the Java SE Development Kit or JDK and it includes the
00:12runtime, a compiler, and many other tools.
00:15The first tool you'll be using is the compiler.
00:18It's an application called javac.
00:21And the name of the application will be the same, regardless of whether you are
00:24working on Mac, Windows, Linux or any other operating system.
00:29When you run javac you are provided with the names of your source code files and
00:33the resulting output will be a set of bytecode files.
00:37To run an application you use the command java.
00:41Again it looks the same on any operating system.
00:44When you run the java command, you'll provide it with the name of the class that
00:48you want to start with.
00:50I'll show you an example of that in a few moments.
00:53The JDK also includes many other tools.
00:56The jar tool lets you package up your applications.
01:00A complete Java application will typically consist of many classes, and when you
01:04compile the classes, you end up with a whole bunch of files.
01:08But it's a lot more convenient to deliver the application as a single file, and
01:12so you use the jar application to do that packaging.
01:15When you package up the files you end up with an archive file in zip format, but
01:20with the file extension of .jar.
01:23The javadoc application lets you create documentation based on comments in your source code.
01:29I'll show you how to use this in a later video in the series.
01:33And there are many other command line tools that are a part of the JDK.
01:37So how do you get started?
01:39Well your Java applications are built in source code files that are pure text files.
01:45You can create these text files in any Text Editor, although, I'll be using the
01:49Eclipse Integrated Development Environment throughout this course.
01:53Here is a classic Hello World application.
01:56If you've worked in other programming languages, you might be accustomed to
02:00Hello World applications being just a single line of code.
02:03That's not the case in Java.
02:05In Java everything is encapsulated in a class of some kind, including
02:11your start-up code.
02:12So this bit of code that I have on the screen represents the simplest
02:16possible Java application.
02:18The first line of code is called the package declaration.
02:21It indicates the location of the source code file within your project.
02:26The package declaration is typically a dot separated string, the beginning of
02:30the package frequently is your domain name in reverse order, so lynda.com
02:36might become com.lynda.
02:38And then the rest of the package indicates what type of application it might be
02:42within your organization.
02:44The next line of code is called the class declaration.
02:47If you create a file called HelloWorld. java it can contain one public class and
02:54the name of the class must match the name of the file, so the HelloWorld.java
02:58file contains a public class named HelloWorld and notice they match exactly.
03:04Java is a case-sensitive language and you must match these strings precisely.
03:09Within the class there is something called a main method.
03:13When you run a Java application from the command line Java will look for this
03:18particular method and execute it automatically.
03:21The name of the method or function must be main lower case.
03:25And the three keywords previous to the function name public, static, and
03:30void are also required.
03:32I'll explain what they mean later on.
03:35The main method must receive something called an argument and it must be
03:39an array of strings.
03:41This allows you to pass an information to the application as you run it from the command line.
03:46We call that the args argument.
03:49Finally within the main method, you place your executable code.
03:54This application simply outputs the text Hello World to the command line using
03:58the command System.out.println or print line.
04:03Notice that this string is ended with a semicolon.
04:07The semicolon is like a period in English, it means this is the end of the statement.
04:12So System.out.println("Hello World") means output the string Hello World to the command line.
04:20So you create that source code file and you place it somewhere in your project folder.
04:26Now in this case I have declared a package named com.lynda.javatraining;
04:31and so I have to place the source code file in an equivalent
04:34subfolder structure.
04:36If HelloWorld is the name of my project folder, then com\lynda\javatraining is
04:42my package folder, matching the dot separated package as declared in the source code.
04:49The name of the file as I have indicated before is HelloWorld.java.
04:54The .java extension is required in all of your source code files.
04:59To actually compile that file, I would start at the project directory
05:03HelloWorld, I would execute the javac command and I'd reference the Java source
05:08code file HelloWorld.
05:10Notice that I am prefixing the name of the file with a slash separated syntax,
05:15com\lynda\javatraining\ and then the name of the file.
05:20This screenshot comes from Windows, so I am using backslashes, but if you were
05:24working on Mac you would use forward slashes.
05:27After compilation you end up with a new file, the original source code file was
05:32HelloWorld.java, the resulting compiled file is HelloWorld.class.
05:38The .class file is your bytecode file, and because this is an application that
05:42only has the single class, that .class file comprises your entire application.
05:48So 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:56Now to run the application from the command line I would use the java command.
06:01I would once again start in the project directory HelloWorld and I'd call the
06:05class using dot separated syntax, just like the package was declared in the
06:10source code, com.lynda.javatraining.HelloWorld.
06:16And notice that when I run the application I am not referencing the file
06:20extension .class, I am only referencing the class name, HelloWorld.
06:26The application runs and the resulting output appears in the console.
06:31So that's a look at basic Java syntax and how you would compile and run a very
06:36simple application from the command line.
06:38Now throughout the rest of the course, I'll be showing you how to do this in the
06:42Integrated Development Environment called Eclipse.
06:45And for the most part you'll be protected from compiling and running directly
06:49from the command line, but it's important to know that if you want to work in
06:52this way you certainly can.
06:54So once you've learned how to work in Java, where can you use it?
06:58Well Java is implemented in many environments and used for many different
07:02kinds of applications.
07:04You can use Java for Desktop applications either actually installed on the
07:08Desktop or delivered through browsers as Java applets embedded in HTML pages.
07:14These are called Graphical Java applications and they use libraries called Swing
07:19and AWT to build their visual presentation.
07:23You can also use Java to build dynamic Web applications, that is, applications
07:28that are delivered to the browser as HTML, dynamically generated at runtime on a server.
07:34These are sometimes called J2EE or simply Java Enterprise Edition
07:38applications and they are executed within server environments such as Tomcat
07:43from Apache or JBoss.
07:45The code is written using models called servlets and JavaServer Pages.
07:50It's exactly the same language as you might use on the Desktop but it's simply
07:54modeled a little bit differently.
07:56And one of the most popular recent uses of Java is on mobile devices.
08:00The Google Android environment uses its own compiler called Dalvik and tools
08:06provided by Google that run in Eclipse to build applications that run on
08:10Android phones and tablets.
08:12The BlackBerry Operating System also uses Java, so you can use Java to write
08:17applications that run on BlackBerry phones, and you can use Java in many other
08:21mobile environments as well.
08:24You can in fact use Java to build all sorts of applications, games, mobile apps,
08:29cloud computing applications, distributed systems, databases, websites embedded
08:35systems, image management, enterprise information management, and many more.
08:39So now that you've had a sense of how Java is architected its history, its
08:44principles, its syntax and how you compile and run Java applications, it's time
08:50to get started with installing Java and writing your own code.
Collapse this transcript
Choosing a development environment
00:00One of the first things you should do when you are working with Java is
00:03to choose an editor.
00:05A product you can use to create your Java source code files and which if it's a
00:09completely Integrated Development Environment can also help you build and
00:13compile your applications.
00:15The truth is, Java source code files are just text files, so you can really use
00:20any Text Editor you are comfortable with.
00:22If you know how to use older developer editors such as Vi or Emacs or if you are
00:28a Windows developer and you love notepad, those will do fine.
00:32But there are many Integrated Development Environments or IDEs available
00:36for Java developers.
00:37One of the first questions you should ask is, which operating system do you
00:41want to develop on?
00:42Java applications are designed to be write once, run anywhere.
00:46So once the application is built you should be able to deploy it on multiple
00:50operating systems, but you as a developer probably have your favorite operating
00:54system that you like to work on.
00:56So perhaps you are looking for an editor that's specifically designed for Mac
00:59OS X or maybe you are a Windows developer and you have no plans ever to work on Mac or Linux.
01:06But you will find in the world of Java that many of the best development
01:09products out there are cross- platform and work on all operating systems
01:14including Windows, Mac, Linux and other variants of UNIX.
01:19Another question you should ask is, am I willing to pay a license fee?
01:23Many of the best development environments are completely free, including
01:27Eclipse and NetBeans, but when you start looking at some of the paid options
01:32you might find advanced features that are worthwhile, especially if you are
01:36going to be working in a team development environment where you're building
01:39very large scale applications.
01:42I think that if you are a new Java developer you'll find that one of the free
01:46IDEs does everything you need when you are getting started.
01:49And later on when you start building very large scale applications it's worth
01:53checking out some of the paid options.
01:55Here are some of the options that are available exclusively on Mac OS X. The
02:00first one might be a bit surprising, it's Xcode.
02:04We know Xcode as the primary development environment for building Mac and iOS
02:09applications, Xcode is completely free and available from the Mac App Store and
02:15it does have rudimentary Java support.
02:18It's best for small scale projects though.
02:20It doesn't have a lot of the capabilities that development environments that are
02:24designed for Java have.
02:26And also because Apple has been pulling back from support for Java over the last
02:30couple of years, for example the latest version of Mac OS X Lion is delivered
02:36without a Java runtime environment already installed, we don't know how much
02:40support there will be for Java in the future.
02:43But if you are already comfortable with Xcode and know how to navigate around
02:46it, it's worth checking out.
02:49Other options that are unique to Mac OS X are two products that are related
02:53called BBEdit and TextWrangler.
02:55These products are both from the same company and they support syntax coloring,
03:00function scanning, and other tasks that are common to programmers, editors.
03:05Neither of these tools is a specialist IDE for Java, that is, they weren't
03:09designed specifically for use with Java, but again if you are already
03:13comfortable with these tools and you like products that really take seriously a
03:18Mac style interface these are worth looking at.
03:21BBEdit is a commercial product and requires a paid license, while
03:25TextWrangler is free.
03:27Both products are available from www. barebones.com and at least TextWrangler is
03:33available from the Mac App Store as well.
03:36If you are a Windows developer and you have no plans to work ever on Mac or
03:40Linux, you can check out some of the light-weight Java development environments
03:44that are specifically built for Windows.
03:46One of the most popular is called JCreator.
03:50There are two editions, one free and one paid, and it has a very similar
03:54interface to a Text Editor called TextPad.
03:57It has the same layout of panels, menus, and configuration options, but both of
04:02these products are specifically designed for use with Java.
04:05JCreator is a very light-weight application, it starts up incredibly quickly
04:11compared to products like Eclipse and NetBeans.
04:14And both versions JCreator LE and JCreator Pro are available
04:19from www.jcreator.com.
04:22And speaking of TextPad, you can also use this very popular shareware product to
04:27build small scale Java applications.
04:30TextPad has the ability to hook into the JDK commands, such as java and javac
04:35the compiler to compile and run small Java applications.
04:40It's shareware, not free, but it's pretty inexpensive, and it's available
04:44from www.textpad.com.
04:48So that's a look at products that are unique to Mac and Windows.
04:52But most of the Java developer community uses cross-platform Java IDEs.
04:57The whole idea of Java is portability.
05:00The idea that you can build a single application and then run it on multiple
05:04platforms without recompiling and being able to do the same thing, move
05:08among operating systems and use basically the same IDE is very appealing to Java developers.
05:15So here are two free IDEs that work on Mac, Windows, Linux, and other platforms.
05:21NetBeans was originally created by Sun Microsystems and is now owned and offered by Oracle.
05:28In addition to Java, NetBeans has editions that support C, C++, and PHP.
05:34Some distributions of NetBeans have an included Java Enterprise Edition server.
05:39So if your goal is to build Java-based Web applications, NetBeans gives you the
05:43ability to get everything you need in a single download and installation.
05:48You can download NetBeans from netbeans.org.
05:51Eclipse is one of my favorite cross- platform IDEs for Java and is the IDE that
05:56I'll be using throughout this course.
05:59Eclipse is open source and completely free.
06:02It was originally built as a Java Development Environment By IBM, before IBM
06:06gave it to the Eclipse Foundation.
06:08But now Eclipse is also used for many languages and development environments.
06:13For example if your goal is to build Android applications with Java, I highly
06:18recommend Eclipse because the Android developer tools from Google are also
06:23delivered as an Eclipse plug-in.
06:25So you can take your Eclipse installation for Java, add-in the Android SDK tools
06:30and you'll have everything you need in one development environment.
06:34You can download all the different distributions of Eclipse
06:37from www.eclipse.org.
06:40And like NetBeans you'll see that there are distributions available from many
06:43operating systems including Windows, Mac, Linux, and so on, and also support for
06:49many programming languages.
06:51Once you move out of the completely free IDEs, you start getting into a set of
06:56products that are really designed for large scale team development.
07:00IntelliJ Idea is the first one.
07:03There is a free version known as community and a paid edition known as
07:06Ultimate of IntelliJ Idea.
07:09IntelliJ Idea has its own support for Android development, and again it's
07:13cross-platform like Eclipse and NetBeans, so you can install it for Windows,
07:17Mac, or Linux, and you can take a look at it at www.jetbrains.com/idea.
07:24And finally there is JBuilder.
07:27At one time JBuilder was the dominant Java developing environment in the world.
07:32That was in the late 90s though, and since that time with the introduction of
07:35Eclipse and NetBeans things have evened out quite a bit.
07:39But JBuilder remains a very powerful Integrated Development
07:42Environment primarily used by large development teams on large scale
07:46enterprise applications.
07:49JBuilder was originally created by Borland, and again it was designed for
07:52enterprise-level development.
07:55You can take a look at JBuilder at www.embarcadero.com/products/jbuilder.
08:03This survey of IDEs for Java gives you a sense of the amount of variety that's
08:08out there, and there are many programmers, editors that I haven't mentioned that
08:12could work fine for Java development.
08:15I encourage you to look at these options and other options you might find on the
08:18Web and choose the development environment that's best for you.
08:22As you work through this course, I'll encourage you though to use Eclipse, the
08:26same IDE that I'll be demonstrating the code with because it will let you
08:30follow along and do the exercises using the same look-and-feel as you see on the screen.
08:35And once you get into building your applications though, choose any of these
08:39IDEs for your own Java development.
Collapse this transcript
2. Installing the Software
Installing Java on Windows
00:00If you're working on Microsoft Windows, the first step is to download and
00:04install the Java Development Kit from Oracle.
00:07You can get the Java Development Kit from this URL java.oracle.com.
00:13This link will take you take you to the current homepage for the Java technology.
00:18On this screen, look under Software Downloads and locate the link for Java SE.
00:23This is the Java SE Downloads screen, take a look at the list of
00:27available downloads.
00:29The most recent version of Java will be listed at the top.
00:32As of the time of this recording, the most recent version of Java was Java SE 7u1.
00:39Notice that there are two different download links one for JDK, the Java
00:44Development Kit and one for JRE, the Java Runtime Environment. You want the JDK.
00:50It actually includes both downloads in one package, you'll be able both to
00:55develop Java applications and run them.
00:58Now, even though Java 7 was finalized for Windows as of the date of this
01:02recording, there was not a similar final version of Java 7 for Mac OS X. So for
01:07this course, I'm primarily using Java 6 to make sure that both operating systems
01:12can run all the code I'll be showing.
01:15To get Java 6, scroll down a little bit further and you'll see a link for the
01:19most recent version of Java 6, which as of this point is Update 29.
01:24Click the Download link under JDK.
01:28Here's a listing of all the installers for the Java Development Kit version 6.
01:33You'll need to accept the License Agreement before you can download anything.
01:36But then for Windows, take a look at the options.
01:39There are three versions.
01:41Most developers will want either the 32- bit which is Windows x86 or the 64-bit
01:47versions, which is Windows x64.
01:50If you're not sure whether you're running 32 or 64-bit Windows you can find out
01:54from the Control Panel.
01:56Go to the Start menu, choose Control Panel and if you're working on Windows
02:00Vista or Windows 7, follow these steps.
02:03Go to System and Security and then to System.
02:07If you're working on Windows XP, you can just click System in the Control Panel.
02:12Take a look at the System type.
02:14If it says 64-bit Operating System, that's the version of Java you want and if
02:19it says 32-bit that's the version you want.
02:22Now that you know which version of Windows you're running, go back to the Oracle
02:26webpage and download the right version of Java for your version of Windows.
02:31I've downloaded the 64- bit version to my desktop.
02:35Now, I'm going to run the installer.
02:37If you're working on Windows XP, you can just double click it and if
02:40you're working on Windows Vista or Windows 7, right click and choose Run as administrator.
02:46When you're prompted, click Yes to allow the program to run.
02:50The rest of the process is pretty straightforward.
02:52On this option screen, you're asked which element of the Java Development Kit you want.
02:57I recommend accepting everything and clicking Next.
03:01The first part of the installation is copying over the files you need for
03:04development that is the commands such as java, javac, jar, javadoc and others.
03:11Once this primary installation is done, a secondary installation will pop-up and
03:16that will be for the Java Runtime Environment or JRE.
03:20When you're prompted for the installation of the JRE, once again click through
03:23the process and allow the installation to complete.
03:28When you see this screen, the installation is complete.
03:31Click Finish and if you're prompted in a web browser to register, you can either
03:36choose to register or not.
03:38I'm just going to close the browser.
03:40Now, let me show you where Java is installed.
03:43I'll go to Windows Explorer, from there I'll go the C:\program files folder and
03:49under there you'll see a folder named Java and within that folder two subfolders
03:54for the Development Kit and the JRE.
03:57The jdk folder has a folder named bin or b-i-n and this folder contains all of
04:03the development applications.
04:05Java, which is used to run applications from the command line, javawm, which
04:10is specifically designed to run applications on Windows, javac the compiler and many others.
04:17Now you're going to want to add this folder to your system path to make it easy
04:22to run applications from the command line.
04:24So on Windows Vista or 7, I'm going to click on the folder icon here and that
04:29turns the folder structure into a string I can copy to the clipboard.
04:34Now I'll add that string to my system path.
04:37I'll go back to the Control Panel again.
04:39Now, you can set your environment variable from a screen that's fairly well
04:43buried in the Control Panel, but an easy way to get there is to click into the
04:47search box, this works only on Vista and Windows 7 not on Windows XP, and type
04:52in environment or some part of that string.
04:56This will take you to links for system environment variables.
04:59I recommend setting the system environment variables for the entire computer
05:03not just your account.
05:04I'll click the link and that takes me to this screen.
05:08If you're working on Windows XP, you can just go to the Control Panel's System
05:12Panel and you'll find a very similar option.
05:16Click Environment Variables, scroll down in the list of System variables
05:20and locate the path.
05:22Click and then edit.
05:25Place the cursor at the end of the string.
05:27Make sure that there is a semicolon at the end so that it terminates whatever is
05:31the last value in this variable.
05:33Paste in the location of the bin folder at the end and then for housekeeping add a semicolon.
05:39Click OK, click OK and click OK again.
05:44Now to test your path and to make sure you're running the right version of Java,
05:49go to a command window.
05:51I'll go to the Start menu and type cmd.
05:54If you're working on Windows XP, choose the appropriate option to open a command window.
06:00That opens up a command window on my system.
06:03I'll first test Java the applications that you run.
06:05I'll type java-version and that tells me that my runtime Java is 1.6.0.29 that
06:15is Java 6 Update 29.
06:18Now, I'll check my compiler, javac - version, and once again I see that I'm
06:25running the right version of Java.
06:28If you can execute the runtime command java and the compiler command
06:32javac, you're ready.
06:34You've installed Java on your system and you're ready for the next step
06:39installing a development environment.
Collapse this transcript
Installing Eclipse on Windows
00:00Once you've installed and verified your copy of Java, the next step is to
00:04install an Integrated Development Environment.
00:07While you can program and compile Java applications directly from the command
00:10line, an IDE such as Eclipse will make things a whole lot easier.
00:14I'll be using the Eclipse IDE throughout this course.
00:17You can download a free copy of Eclipse from www.eclipse.org/downloads.
00:25On this screen, you'll see a listing of the various distributions of Eclipse.
00:29I recommend that you use the Eclipse IDE for Java Developers.
00:33You'll also see a larger distribution for Java EE or Enterprise
00:37Edition Developers.
00:38Because we won't be building Enterprise web applications in this course, you
00:42don't need all the tools that are a part of that distribution.
00:45Over on the right, you'll see that there are 32-bit and 64-bit versions of Eclipse.
00:50As with Java, make sure you know which version of Windows you are running and
00:54choose the matching version of Eclipse.
00:56I've downloaded the 64-bit version of the Eclipse IDE for Java Developers to my desktop.
01:02Eclipse is delivered as an achieve file in zip format.
01:06To install it, you simply extract the contents of the zip file.
01:10I don't have any special zip utilities installed on my system, so when I double
01:14click on the zip file it just opens it up in Windows Explorer.
01:17Now, I am going to drag this off to the right and dock that window on the right
01:21side, that's one of my favorite little Windows 7 tricks and then I am going to
01:25drag and drop the eclipse folder on to my desktop.
01:28This is a fairly large file, so it's going to take a few minutes for it
01:32to extract completely.
01:33Once it's extracted though the installation is really complete.
01:37You can either leave the eclipse folder on your desktop or if you want to
01:41follow the conventions of Windows you might move that eclipse folder into your
01:45Program Files directory.
01:47It's completely up to you though, you can run Eclipse from anywhere on your system.
01:52Once the files are finished being extracted, I'll move them into my
01:55Program Files directory.
01:57I'll open Windows Explorer and go to C:program files.
02:02Once again, I'll dock over to the right and then I'll simply drag and drop this
02:06eclipse folder and move it into the Program Files folders.
02:09If prompted for administrator permission click Continue.
02:12Now to run Eclipse, double click the eclipse folder and then double click eclipse.exe.
02:18Depending on your Windows configuration, you might not see the .exe file
02:21extension but you should see this graphic.
02:24When I double click, I am prompted to run the application.
02:28For convenience, I'll uncheck the option to ask before opening the file every
02:31time and then I'll click Run.
02:34When Eclipse opens for the first time it will prompt you for something called a
02:37workspace directory.
02:39I'll talk more about workspace directories in a later video, but for now you can
02:43simply accept the default, which is a new directory named workspace all
02:47lowercase under your home directory.
02:50I also recommend that you check this option, Use this as the default and don't
02:53ask again and that will let Eclipse launch more easily later on.
02:57I'll click okay and then after a few moments, after Eclipse loads all of its resources;
03:03it will open on the screen.
03:04When you first open Eclipse, you'll see this welcome screen.
03:08You don't need it though so you can just close that screen and you'll now see
03:11the default Eclipse configuration.
03:14If 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:00If you are working on older versions of Mac OS X that is version prior to 10.7
00:05Lion, Java should already be installed on your system.
00:09But you want to make sure it's installed and you should make sure you know which
00:12version is installed.
00:13The easiest way to find out which version of the Java you have is to go to the
00:17Applications folder, then to Utilities, and then to Java Preferences, an
00:22application that lets you see what you have on your system.
00:25In the General tab of the Java Preferences application I see that there is both
00:29a 64 and a 32-bit version of Java and they are both Java 6.
00:34Notice that the internal Version is 1. 6 rather than just 6, but the marketing
00:39version is version 6.
00:40So I have Java Standard Edition version 6.
00:44The version at the top of the list is my default JDK.
00:48And when I build my code whether it's on the command line or in Eclipse or any
00:52other IDE, this is the version that I'll be using.
00:55Now if you don't have this version of Java you can go get the version you want.
01:00Go to a browser and try one of these links.
01:03If you are working on Snow Leopard or 10.6 go to this page
01:07support.apple.com/kb/DL1360.
01:12There is a Download button there click the button and follow the instructions to
01:16download and install the most recent version of Java for this version of Mac.
01:21If your one version back from there on Leopard or 10.5 try this page
01:25support.apple.com/kb/DL924 again there is a Download link.
01:32You may notice that the maintenance version on this download is only version 15, that's fine.
01:37As long as you are using any version of Java 6, you'll be able to follow along with course.
01:43Finally, if you want to be on the bleeding-edge you can try Java 7 on Mac.
01:47At the time of this recording the port of Java 7 to Mac was not complete but it
01:52was in Public Beta or Preview at Oracle.
01:55To try it out go to this page jdk7.java. net/macportpreview, you'll see that it's
02:03clearly identified as a preproduction developer preview release.
02:07That means you shouldn't use it for production application or depend on it for
02:11robust mission critical applications, but if you want to try it, just follow the
02:16instructions on this page for download and installation.
02:19Either way, you should have either Java 6 or Java 7 installed before you
02:24continue with the rest of this course.
Collapse this transcript
Installing Java on Mac OS X Lion
00:00If you are working on Mac OS X version 10.7 or Lion, you'll find that Java is
00:05not installed by default on this version of the operating system.
00:09It's up to you to go get Java and install it.
00:12This is pretty easy to do, just go to the Apple website at this URL,
00:16support.apple.com/kb/DL1421.
00:23Click the Download link and follow the prompts to download the software.
00:28I've downloaded the installer to my desktop.
00:30It's a dmg file and when you open it up it shows a conventional installer package.
00:36Run the installer and walk through all the prompts to install Java.
00:40There are no options to take care of, so the installation is fairly automated.
00:44This version of the installer is for Java SE 6, 1.6.0.26, the latest version of
00:51Java for Mac as of this recording.
00:54Once you've completed the installation the next step is to test it.
00:58I recommend using Terminal for this.
01:00I'll go to the Lion Launchpad application which opens up my applications.
01:04I'll go to Utilities and then to Terminal.
01:08Now to test the installation of Java, first type java, all lower case, then a
01:13space and -version, press return and you should see an output showing you which
01:19version of Java is installed on your system.
01:21Again I am running Java 6 maintenance release 26.
01:25You should also test to make sure you can get to the Java compiler type javac
01:30space -version and once again you should get a little bit of output.
01:34This time just showing the version number.
01:37If you can do this much you are in great shape and you are ready to go to the
01:41next step installing Eclipse, but before you finish up this video, I'll show you
01:46where Java is actually installed.
01:48You'll need to know this location for certain configurations tasks during this video course.
01:54In Terminal from the command line type cd space /System, make sure that you
02:01are using an uppercase S because Mac OS X is case sensitive, then /library, then /frameworks.
02:10Press Return and the type ls Ja* and that will show you a listing of everything
02:18starting off with the word Java.
02:20I am looking for the items at the bottom of the listing under JavaVM.
02:24Framework so I'll type cd then JavaV, with an uppercase V, and I'll press tab
02:32and let Terminal auto complete the directory name.
02:35I'll press Return then I'll issue the Clear command to clear the screen and then
02:39ls to see what's in here.
02:41You'll see that there are directories for Classes, Frameworks, JavaVM and so on.
02:46The directory you are interested in is commands.
02:50So I'll type cd space Commands and return and then ls and there are all the Java
02:56commands including Java, javac, javadoc and many, many others.
03:02Again you'll need to know this particular directory location later on in the
03:06course when you configure Eclipse to tell it where certain tools are such as
03:11the javadoc command.
03:13So now you have installed Java, you've tested it to make sure you can run both
03:16the Java Virtual Machine and the compiler and you've seen where the Java files
03:21are installed and you are ready for the next step in the process installing
03:25Eclipse on your system.
Collapse this transcript
Installing Eclipse on Mac OS X
00:00Once you have checked your version of Java on Mac OS X, you are ready to install
00:04Eclipse, the IDE I'll be using throughout this course.
00:08Go to the webpage, www.eclipse.org/downloads.
00:13You'll see a number of distributions of Eclipse are listed.
00:16There is the one at the top for Java Developers, that's the one I'll be using,
00:19but there are many others available.
00:21You'll need to install the version of Eclipse for your copy of Mac OS X,
00:25either 32 or 64-bit.
00:28If you are not sure which version of Mac you're using, go to the Apple Menu and
00:33choose About This Mac.
00:35On this dialog, click on More Info.
00:38That opens the System Profiler Application.
00:42Now, scroll down in the left hand panel and click on Software.
00:46Check the Property 64-bit Kernel and Extensions.
00:50If it says Yes, then you're running 64-bit Mac.
00:53If it says No, then you're running 32- bit Mac, and that's the version of Eclipse
00:58you'll want to download.
00:59I'll click into Mac OS X 64-bit.
01:04The file is delivered to you as a compressed archive, with the file extension of tar.gz.
01:10Now, I've already downloaded that file to my Desktop, and to install Eclipse
01:14there are just two steps.
01:16First, extract the file.
01:18If you don't have any special archive utilities installed on your system, you
01:22can extract this file simply by double clicking it.
01:25Mac will unarchive the file and place the resulting folder on your Desktop.
01:31The name of the resulting folder is simply eclipse.
01:34I'll double click into the folder and show you that it contains the Eclipse
01:37application, that's the version that has an uppercase initial character, and the
01:42graphic, and all of Eclipse's supporting files.
01:45Now, technically, you've already installed the application and you could start
01:49using it, but I prefer to put Eclipse where all of the other applications are on
01:53my Mac, in the Applications folder.
01:56So I'll click on the background and then press Command+N, that opens a new
02:00Finder window, and I'll see that Applications is here in my Sidebar.
02:05If you don't see Applications in your Sidebar, just open up that folder.
02:08Then, I'll click on the Eclipse folder and drag and drop it on to the
02:13Applications folder.
02:14Then to get to Eclipse, I'll go to Applications, I'll scroll down to the Es,
02:18there it is, I'll click the eclipse folder, and then double click the
02:23Eclipse application.
02:25If I am prompted to make sure I want to open a downloaded application, I'll click Open.
02:30When Eclipse opens for the first time, it will ask you where it wants to put
02:34something called a workspace.
02:36I'll describe how workspaces work later, but for now, just accept the default,
02:41which will be Documents/workspace under your Home folder, and click OK.
02:46It will take a few more moments for Eclipse to load up all of its tools and then
02:50it will open to this Welcome Screen.
02:53Close the Welcome Screen and you'll be in the Java Development Environment.
02:57If you have gotten this far, you are ready to start writing code in Java.
03:02And in the next chapter, I'll show you how to write a Hello World application
03:06and show you what basic Java syntax looks like.
Collapse this transcript
3. Getting Started
Creating a Hello World application
00:00Now it's time for that traditional first programing task: building an application
00:04that says Hello World.
00:06If you don't already have Eclipse open, you should open it now.
00:10I'm going to show you a little trick on Windows and you can do something similar
00:14on Mac OS X. I am going to create a shortcut on my Desktop to make it easier to
00:18start Eclipse in the future.
00:20I'll go to the Eclipse folder under Program files, and if you are working on
00:24Mac, go to \applications\eclipse and locate the Eclipse command with the little graphic.
00:31Now I am going to right click on it.
00:33And on Windows I'll create a shortcut and on Mac create an alias.
00:38I'll then drag that shortcut or alias out to the Desktop and then I am going to rename it.
00:44On Windows, I'll press F2, on Mac I'll press Enter, and I'll simply call it Eclipse.
00:51And now I'll be able to start up Eclipse easily from my Desktop whenever I need it.
00:56Now, double click the shortcut or alias and that starts up Eclipse on my system.
01:02Before you create the Hello World application, you should set up your workspace.
01:08A workspace is a folder that tracks all of your Java projects.
01:12It contains all of your user configurations, pointers to your projects
01:16regardless of whether they are actually physically in the workspace folder, and
01:21adds other capabilities to your Java development environment.
01:24To switch your workspace, go to the Menu and choose File, Switch
01:28Workspace>Other, it will show you your current workspace.
01:33I am going to change my workspace to my Exercise Files folder.
01:37If you have access to the Exercise Files for this course you can do the same, or
01:42you can create your own Exercise Files folder.
01:46I'll Browse, I'll go to my Desktop, and from there I will go to Exercise
01:51Files, and click OK.
01:54Now, when you click OK from this screen, Eclipse is going to close and then reopen.
01:59This allows Eclipse to let go of any file locks it may already have.
02:04And when it opens it will be ready to get started building your applications.
02:08I'll maximize Eclipse and once again close the Welcome Screen, and now I am
02:12ready to create my first application.
02:15When you create Java applications in Eclipse, they are always inside Java project.
02:20So the first thing to do is to create a project.
02:23From the Menu choose File>New>Java Project.
02:28Give your project a name.
02:30I'll name it HelloWorld.
02:32I recommend creating your project names without any spaces or
02:36special characters.
02:37The default location for your project will be a folder of the same name under
02:42your Workspace folder, in my case under the Exercise Files folder.
02:47If you prefer, you can uncheck the option, Use default location and place the
02:51project anywhere you like.
02:53For the JRE, you can choose either a specific JRE, or I recommend using the default JRE.
03:01This will give your project maximum portability between systems.
03:05So for example, if you say Use default JRE and your system currently has JRE
03:106.0, and then you take that same project and move it to a system where the
03:14default JRE is JRE 7.0, the project will still compile and run just fine and you
03:21won't have to go into your Java project settings and change the environment,
03:25accept all the other default settings and click Next.
03:28On this screen you are asked for Java build settings.
03:32The default setting is to create your source code files in a folder named SRC
03:38under the project folder.
03:39And down at the bottom it shows that the output folder, that is the folder where
03:44you will be creating your output binary files or class files, is named bin.
03:48So your files aren't all stored in one single folder.
03:52Accept the default and click Finish.
03:56Your project starts out empty, that is, there aren't any Java code files in it.
04:00You have to create the applications explicitly.
04:03Every Java application is built inside a class.
04:07This makes it very different from other programming environments such as
04:10say Perl or Python, where an application can be as a little as a single line of code.
04:17In Java, everything is an object, and an object is created from a class, so you
04:22have to define a class.
04:23The good news is Eclipse makes this pretty simple to do.
04:27Right-click on your source folder and choose New>Class.
04:31This is the new Java Class wizard.
04:35The Source folder is set explicitly to HelloWorld/src, that is the project
04:41folder and the SRC subfolder.
04:43For now, leave the Package blank.
04:46You'll see a warning when you do that, Eclipse thinks that you should put every
04:49class in a subfolder or package of some kind, but to keep things simple for
04:54your Hello World application we're going to leave it in the default Package or the project route.
05:00Give the class a name of HelloWorld, you could also name this class Main or
05:05anything else you want, but to follow good Java conventions, the first character
05:10of the class name must be uppercase.
05:13If you create a class name with a lowercase initial character it will still
05:16work, but it will violate conventions that are very strongly held in the
05:20Java development world.
05:23For the Modifiers, accept the default of public.
05:26Don't check the checkboxes for abstract or final, again, we'll talk about those
05:30later in the course, and leave the Superclass set to Java.lang.Object.
05:36In fact, there is only one other change to make here.
05:39To make this a valid startup class, check the option labeled public static void main.
05:47This will create a method or function that will be called automatically when you
05:51start up the class by the Java Virtual Machine. That's it.
05:55Click Finish.
05:58Once the class has been created, it will open in an editor.
06:02Now, to make this a little easier to read, I am going change my font.
06:05I'll go to my Preferences dialog, which on Windows you can get to through
06:10Window>Preferences, and on Mac you can get to through Eclipse>Preferences.
06:15In the Preferences dialog, I'll click on General>Appearance>Colors and Fonts,
06:22and then in the Colors and Fonts list I'll choose Basic, and scroll down to the
06:27bottom of that list and choose Text Font, and then I'll click Edit.
06:31I am just going to expand the size of my Font to 14 pixels and click OK,
06:38and click OK again.
06:40And that should make the code easier to read on the screen.
06:42I am going to clean up the code a little bit, removing things I don't need.
06:47I don't need this commenting section, so I am just going to select and delete
06:51it, and I don't need this TODO comment either.
06:54This is added to the main method by Eclipse when you generate the code.
06:58You can either select and delete it or you can use this little icon over on the
07:03left with the checkbox.
07:04I'll click the icon, and from the Task List I'll choose Remove task tag, double clicking.
07:12I'll press tab once and now I am ready to add some executable code.
07:16Here is the code to output a string to the console.
07:20Start with System with an uppercase S. System is a Java class and it's a part of
07:26the core Java Class Library that's included with your installation of Java.
07:31Now type a period and you will see a list of all of the properties and objects
07:36that are a part of the system class. Choose out;
07:39you can either type it or simply double click it.
07:42Out represents an object which implements something called a
07:46PrintStream interface.
07:48A PrintStream object allows you to output text to some sort of environment.
07:53In this case, it will output to the console.
07:56Type another dot or period, and now you will see a list of all of the functions
08:01that are a part of the PrintStream named out.
08:03I am going to choose one called Println.
08:06There is a Print and a Println;
08:08the Println function or method will output something to the screen and add a
08:12line feed at the end.
08:14I'll type in an opening parenthesis and then a double quote and notice that
08:19Eclipse is closing the parenthesis and the quotes as I type, and then I'll type
08:24in the string "Hello World!"
08:26I'll move the curser to the end of the line and put in a semicolon.
08:31In Java, the semicolon is like a period in English, it completes the
08:35statement, and it's required.
08:38In some C style languages, such as ActionScript, if you don't put in the
08:42semicolon you will be okay.
08:44In Java you have to put the semicolon in or the compiler will complain.
08:49That's my finished Hello World application.
08:51I'll save my changes by pressing Ctrl + S on Windows or command S on Mac.
08:56Now, I am going to run the application for the first time.
09:00To run an application, go to the Toolbar and look for the Run button, it's a
09:05little arrow pointing to the right.
09:07Click the Down Arrow next to the Run button and choose Run Configurations.
09:12In the Run Configurations screen choose Java Application, and then up on the
09:16Toolbar click the Plus button.
09:18This will create a new Run Configuration for this application.
09:23The name of the Run Configuration will match the name of the class, HelloWorld.
09:27There are many options for the Run Configuration, but you don't need any of them for now.
09:31Just go down to the bottom of the dialog box and click Run.
09:35If all of your code works okay, you should see a rectangular area down at the
09:39bottom of the screen called the Console View appear, and it should contain the
09:43output of your application, Hello World!
09:46Now, once you've created the Run Configuration for the first time on a
09:50particular application, you don't need to go through the whole process again.
09:54So I am going to add a couple of exclamation marks here so that I can just
09:59modify the application in some way.
10:01I'll save the changes by pressing, once again, Ctrl+S or Command+S, and this
10:07time to run the application I don't need to pull down the list and go into the
10:10Configuration screen, I just need to click the Run button.
10:14And down at the bottom in the Console I see the output.
10:18So that's your HelloWorld Java application.
10:20As I've previously mentioned, Java is a little more complex than certain
10:24scripting languages that allow you to say Hello World with a single line of code.
10:29In Java, all code must be wrapped in class definitions and code that you want to
10:34execute must be wrapped inside a function of some kind.
10:38This main function is called automatically by the Java Virtual Machine.
10:43It must have the words public, static, and void at the beginning, and it must
10:48accept this value between the parenthesis, String, open and closed bracket, and the name of a variable,
10:55which is traditionally named args.
10:57I'll talk more about that main method and specifically about how those values
11:02are being passed into the function, known as arguments, in a later video.
Collapse this transcript
Exploring the Eclipse IDE
00:00Before we continue on with learning about the Java programming language, I'd
00:04like to give you a tutorial on how to navigate around the Eclipse IDE.
00:09Eclipse has its own vocabulary, how to refer to various areas of the Eclipse
00:14interface and how to configure it.
00:16I am going to start with showing you how to import existing projects.
00:21If you have access to the Exercise Files for this course, you'll see that they
00:25are stored in Chapters.
00:26For example, the projects for the current chapter Getting Started are in this
00:30folder, 03_GettingStarted.
00:34Each of these folders constitutes an Eclipse project.
00:38I'll double click into one of them named ExploreEclipse.
00:41You'll see that it contains a source folder;
00:44that's where your Java files go, and a bin folder;
00:47that's where the compiled classes are placed.
00:50There are also two files named .classpath and .project.
00:55If you are working on Windows, you should see them in Windows Explorer.
00:59If you are working on a Mac, you won't see the files with the dot prefix
01:03displayed in Finder, but they are there.
01:05These are XML files that are used to configure the current project.
01:10You can actually work with these files outside of Eclipse very easily, but I've
01:14configured them to be importable into Eclipse so you can get started with each
01:19lesson very quickly.
01:20Here is how you would import that project into Eclipse.
01:24From the Eclipse Menu, go to File>Import.
01:28In the Import dialog, go to General, and then Existing Projects into
01:33Workspace, and click Next.
01:36You can import projects from two formats;
01:38an exploded project, where you can see the actual files on disk, that's the kind
01:43of projects that I am using;
01:45and archived files that are in ZIP format.
01:47I won't be using those during this course.
01:50So I am going to choose a root directory of an existing project. I'll click Browse.
01:55I'll navigate to my Exercise Files, 03_ GettingStarted folder, and I'll chose
02:01ExploreEclipse, and click OK.
02:03Eclipse detects that there is a project in that folder and it displays the
02:07project and checks it by default.
02:10All I am going to need to do is click Finish.
02:12But before I do, I'll show you that there is an option labeled Copy
02:16projects into workspace.
02:18If you leave that option unselected, you'll be importing the existing project
02:23into the workspace so that it's displayed in the Package Explorer on the left
02:27side of the Eclipse UI, but you'll still be working with the original code.
02:31If you check this option, you're making a copy of the project, and the project
02:36will be copied into the root folder of the workspace itself.
02:39I'll be leaving this option unchecked throughout this course so that I am
02:43working with the actual files that I am delivering in the Exercise Files bundle.
02:47I'll click Finish, and that imports the project.
02:52I can now open the project, open its source folder, its default package, and
02:58there is the code, HelloWorld.java.
03:01Now, notice I now have two projects opened and they both have classes named HelloWorld.
03:06How do I know which one I am looking at?
03:08Here is a little trick, if you move the cursor over the tab, you'll see the
03:14entire path, starting with the project name, so this file is for the
03:18ExploreEclipse project.
03:20I'll open the class from the HelloWorld project and move the cursor over that
03:24tab and show that the pop- up help shows HelloWorld.
03:28So when you have multiple classes of the same name, sometimes with more than one
03:32project, sometimes within different directories or packages within the same
03:36project, you can easily find out which one you are working with.
03:40Now, I typically try to keep only one project open at a time.
03:44So I am going to go back to my original HelloWorld project, I'll right click on
03:49it and choose Close Project.
03:51And now I'm only left with the HelloWorld.java file from ExploreEclipse.
03:57Here are some important terminologies as you work with Eclipse.
04:00Each of the rectangular areas is called a View.
04:03You might think of those as panels if you've worked say with Adobe or Microsoft
04:07software, but Eclipse calls them Views.
04:10By default, there is a Package Explorer View, down at the bottom there is
04:15Problems View for displaying code problems, a Javadoc View, a Declaration,
04:20a Console, and so on.
04:23Over on the right there is something called the Task List View.
04:26This is a part of a plug-in called Mylyn, that's delivered automatically with
04:31this distribution of Eclipse.
04:33We won't be using this plug-in during this course, so I am just going to get rid
04:36of it by clicking the Close icon.
04:38The other view that appears on the right side by default is called the Outline
04:42View, this one is very useful because it lets you navigate around in your code
04:46without having to scroll up and down.
04:48As your code gets more complex and you have a lot more of it, it's a lot easier
04:53to find the code by using the Outline.
04:56Even though this is a very simple class, I can demonstrate this by clicking on
04:59the main method, and you'll see that, that method name is highlighted and the
05:04cursor moves to that location in the code.
05:06So we'll keep the Outline View open.
05:09As you work with your code and you have wider lines, you might want to expand
05:13the Editor so that it's Full Screen.
05:16To do this just double click on the tab at the top of the Editor and that will maximize it.
05:22Double click again and it will restore to its original size.
05:25I'll also show you that you can expand any of the views, not just the Editor.
05:30I'll maximize the Package Explorer and restore it;
05:35I'll maximize the Problems View and restore it, and so on.
05:39Every view behaves exactly the same.
05:41Another concept that's important to know about in Eclipse is Perspectives.
05:46A Perspective in Eclipse is a particular arrangement of views.
05:50So the Java Perspective, which is the default Perspective when you first open
05:54this Eclipse distribution, has the Package Explorer on the left, the Editor in
05:59the center, the Problems, Javadoc, and Declaration View at the bottom and so on.
06:04You can create your own custom Perspectives.
06:07So for example, I have the Console View open now, because I've run an application;
06:12it's not typically open when you first start the Java Perspective.
06:16I have also closed the Task List View.
06:20Now I am going to save this as my own custom Perspective.
06:23I'll go to the Menu and choose Window> Save Perspective As, and I'll call this
06:29CustomForJava, and click OK.
06:33I can now switch between different Perspectives.
06:36I can go to the Menu and choose Window> Open Perspective, and I'll see a couple
06:42of default Perspectives here;
06:43one called Debug and another one called Java Browsing.
06:47I'll click Other and I'll see a whole bunch of different Perspectives listed.
06:51Java was the default, I'll choose that, and you'll see that the original
06:56Perspective or layout returns, including the Task List.
07:00But up in the upper right hand corner I now see my CustomForJava
07:04Perspective displayed.
07:06You can actually move the cursor to the left of the Perspectives and drag this
07:10out, so you can see as many Perspectives as buttons as you have available.
07:15And you can easily now switch between them by clicking the appropriate button.
07:19I'll typically be using this CustomForJava Perspective throughout the course,
07:23but you can create your own Perspective and layout the application however you like.
07:28I'll show you one more trick.
07:30You can detach any of the views and have them float above the rest of the Eclipse UI.
07:35This is particularly useful if you have more than one monitor and you want to
07:40move one of the views off to the second monitor.
07:42To do this, you right click on the tab for the View and choose Detached.
07:47Now, you can move the view around, you can expand it, and if you have that
07:52second monitor, you can move it off to the second monitor.
07:55To reattach it, right click on the tab and deselect Detached.
08:00The view might drop into an area you don't want.
08:03For example, the Outline View just dropped into my bottom dock.
08:08But you can click on the tab and drag it wherever you want.
08:11So now I've placed it back in its original location.
08:15And if at any point you've really messed up your views in a way that doesn't
08:18work for you, for example, I am just sort of randomly moving things around now
08:22to really mess up my system, you can always reset a Perspective.
08:28Go to the Menu and choose Window>Reset Perspective, and click Yes to confirm.
08:35And your original Perspective will return.
08:37So that's a look at how to navigate around the Eclipse user interface.
08:41I've shown how to use Views and Perspectives, how to create your own custom
08:45Perspective, and how to detach views and move them around if you prefer, and
08:50finally 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:00Throughout this course I'll be using the Eclipse IDE to program, compile, and
00:05run my Java applications.
00:08But it's important to know that you can also compile and run from the command
00:11line and there are things you can see on the command line a little bit more
00:15easily than in the IDE.
00:16I'm going to use an existing project.
00:19I'll import the project from the Exercise Files folders using the Import command
00:25and selecting the root directory under Exercise
00:28Files>03_GettingStarted>CommandLine.
00:32I'll complete the Import process.
00:36I'll open the application that's in the default package of the project, and this
00:40time the name of the class is Main rather than HelloWorld.
00:44You can name this Main class anything you want, the only real requirement is
00:49that the initial character be uppercase;
00:51in this case the letter M, but you can name it anything you want as long as you
00:55follow Java naming conventions.
00:57You can't use any spaces or special characters and that initial character really
01:01should be uppercase.
01:03Once again, this is an incredibly simple application;
01:06it's outputting a string to the command line.
01:08With the application open, I'll click the Run button, the application runs, and
01:13the console displays the outputted string.
01:16Now let's go to a command window.
01:18On Windows 7 and Windows Vista, click the Start Menu and type cmd and press
01:24Return, that will open up a command window.
01:27If you're working on Mac, go to the Applications folder, to the Utility
01:32subfolder, and open the Terminal application.
01:35In either Windows or Mac, you should start off at your Home Directory,
01:39Users\, and your username.
01:42If you're working on Windows XP, you should start off at the Documents and
01:46Settings folder and then your username.
01:48Now, change to the Desktop folder, type cd Desktop.
01:54On either Mac or Windows you can type the beginning of a folder name and
01:57then press the Tab key.
01:59So now, I'm going to move to the Exercise Files folder by typing cd and then
02:05Ex, and then press Tab.
02:08If you're working on Windows, the case doesn't matter, but if you're working on Mac, it does;
02:13Mac is case sensitive.
02:15So now I'm in the Exercise Files folder, and I'll move down a directory into the
02:20Chapter 03 folder, typing cd 03, pressing Tab, and now I'll adding a slash.
02:27If you're working on Windows, use a backslash, and if you're working on Mac use
02:31a forward slash, and type the beginning of the project name, com, press Tab
02:36again, and then press Enter or Return and you're in the CommandLine folder.
02:41Type dir on Windows or ls on Mac and you'll see a listing of the files in the directory.
02:48You should see two files starting with the dot;
02:50the classpath and the project files, and a folder named bin and one named src.
02:56List the contents of the src folder.
02:59Type dir on Windows or ls on Mac, then a space, and src, and you should see that
03:06it contains the one Java file, Main.java.
03:09Now switch to that directory, type cd src and press Enter or Return.
03:15So now, I'm going to show you how to compile the application from the command line.
03:20First I'll clear the screen, type cls on Windows or clear on Mac and press Enter or Return.
03:27To compile an application use the javac command.
03:31I'll type javac, all one word, and then a space, and then the name of the Java
03:36file, including the file extension, Main.java.
03:41Regardless of whether you're working on Mac or Windows, this is case sensitive.
03:45Even though Windows is a non case sensitive file system for the most part, Java
03:50is a highly case sensitive language, so type the name of the file exactly as it
03:54exists, with the uppercase M. Then press Enter or Return.
03:59If you don't see any output, that's good news.
04:02Now, list the contents of the directory again and you should see that the class
04:06file was created in the same directory as the source code file.
04:10Now, to run the application, type java space, and then the name of the file, but
04:16without the dot class extension, and press Enter or Return and the application
04:21should execute and the string should be output to the command line.
04:25Notice that when you execute the application, you're referring to the class as a
04:29class, not as a file.
04:32That's why you don't include the dot class extension.
04:34When you compile, you're dealing with the file;
04:37when you run, you're dealing with the class.
04:40Now, when you compile in Eclipse, you may have noticed that you're creating
04:44the class file in a different directory, not in the same directory as the source code file.
04:49You can do the same thing from the command line.
04:52The javac command has a whole bunch of different options available.
04:55You can see those options by simply typing javac, without passing any values,
05:00such as filenames, just type javac and press Enter or Return, and you'll see a
05:05listing of all of the different options.
05:07I'm going to use this one, -d, specifying where to place generated class files.
05:13So I'm going to clear my screen again, cls on Windows or Clear on Mac.
05:18Then I'll type javac.
05:19I'll once again follow that with the name of the file, Main.java, but then I'll
05:25type -d ..\bin, using a backslash for Windows or a forward slash for Mac.
05:34The result will be that the class file is generated in the bin folder.
05:38I'll type cd ..\bin, I'll list the contents of the directory, and I'll see the
05:46new copy of Main.class.
05:48Now, because I've changed my current directory to bin, I can run the class from
05:53here, with java Main.
05:57Let's switch back to the source folder, cd ..\src.
06:03And I'm going to show you one incredibly valuable thing that running from the
06:06command line will let you do.
06:07I'll once again clear my screen.
06:10Now, this time when I compile I'll use the verbose parameter, -verbose means
06:16tell the compiler to tell me what it's doing in the background.
06:19When you have issues with your Java code that you can't solve in Eclipse,
06:23sometimes seeing what the Java compiler is doing can be useful.
06:27Here is the syntax, javac, then the name of the file, Main.java, and then after
06:33a space, -verbose, all lower case.
06:37Press Enter or Return and you'll see that the class is being compiled, but you
06:43will see a whole listing of what's going on in the background.
06:46Up at the top it says parsing started Main.java and then parsing completed.
06:52So it takes a moment first to read your file and figure out what it's supposed to do.
06:57Now it looks for supporting files, the search path for class files is called the
07:02classpath, and by default it includes all of the jar files and classes that are
07:09a part of the core Java Class Library.
07:11Those are the files that are included with the JDK.
07:14Next, it starts loading classes that it needs.
07:18I've asked to use the String class and the System class and also the PrintStream
07:23class, which has its own set of dependencies.
07:26So the compiler goes through all of its archived files and finds the classes
07:31that it needs to build this program.
07:34Not just my class, which is called Main, but all of the supporting classes as well.
07:39Finally, it finishes the compilation and writes Main.class to the file system,
07:44and tells you how long the whole thing took;
07:47less than a second.
07:48So that's a look at some of the things you can do working from the command line.
07:52You can do many of these things also in Eclipse, by adding parameters in your
07:56run configuration, and I will show you some of those options in the next video.
Collapse this transcript
Passing arguments to the application
00:00When you create a Main class, that is a class that you want to start up when
00:04the application begins.
00:06It always has a main method when you are running Java from the command line or the console.
00:11The syntax for this can differ from one platform to another.
00:14For example, you don't use a main method in a Java Servlet, you use other
00:18kinds of methods, but when you are running from the command line, it's always called main.
00:23The signature or syntax of the main method always looks like this:
00:28it has the keywords public, static, and void.
00:32Public means that the method can be called from anywhere.
00:36Static means that you don't have to create an instance of the class.
00:40And void means that you are not returning anything from the class.
00:44Now, I'll talk more about these keywords in later videos, but for now what
00:48you need to know is that these three keywords are required as part of the
00:53main method declaration.
00:55The other thing that the main method has to have is this syntax, String, open/closed bracket,
01:02and then the name of the variable, which by default is set to args by
01:06Eclipse, but could be anything.
01:08This is a value that's passed in by the Java Virtual Machine as the
01:13application starts up.
01:15The brackets means that the argument is an array, an ordered collection of values.
01:21And these are the command line arguments or values that are passed into the
01:25application when it starts up.
01:27Now, you can pass arguments in from Eclipse or from the command line.
01:31It will make most sense if we start from the command line though.
01:35So open up a command window;
01:38on Windows use the cmd command and on Mac use terminal, and then change to bin
01:44folder underneath the project arguments that I've imported into Eclipse.
01:48I'll type cd Desktop\Exercise Files \03_GettingStarted\Arguments\bin.
01:59List the contents of the directory using dir on windows or ls on Mac, and you
02:04should see that there is a class there called Main.class.
02:08Now, I am going to run the application.
02:10First I'll clear my screen.
02:12Then I'll type java Main.
02:15And I don't see any output, that's because my source code for the moment doesn't
02:20have anything in the main method.
02:22I'll switch back to the command window using Alt+Tab on Windows or Command+Tab
02:26on Mac, and this time I'll type java Main arg1 arg2.
02:34Again, there is no output, but let's add some code to the application to detect
02:39and report the arguments.
02:41I'll go back to the main method.
02:43The args variable is an array, and in Java every array has a property called
02:49length, which returns numeric value indicating how many items there are in the array.
02:54So I am going to add a little bit of output that looks like this.
02:58System.out.println, and then I'll put two values together, one string and one number.
03:06The 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:16operator and then args.length.
03:20The length property is numeric.
03:22When you take a string and a numeric value and put them together using the plus
03:26operator, that's called concatenation, and in Java the numeric value will be
03:31automatically converted to a string.
03:33I'll talk about the mechanics of that in a later video.
03:38I'll finish the statement with the semicolon at the end and I'll Save my changes.
03:42Now, by default when you Save your changes to your code, Eclipse automatically
03:47recompiles the application for you.
03:50This is because under the Project Menu there is an option labeled
03:53Build Automatically.
03:54It's checked by default.
03:56If you want to you can uncheck that option and only compile or build when you
04:01say so, but I'll keep it on, so whenever I Save my changes the .class files
04:06are recreated for me.
04:09So now I can switch back to the command window and I'll repeat the same command
04:14by pressing the Up Arrow and then either Enter or Return, and I should get the
04:19output, Number of args: 2.
04:21So now I know that I am receiving the arguments from the command line and that I
04:26have exactly the number that I typed in.
04:28Let's go back to the code and add a little bit more.
04:31Place the cursor after that initial statement and press Enter or Return a couple
04:35of times to make a little bit of blank space in your code.
04:38Now, I am going to add a little bit of code that loops through the arguments and
04:42report the value of each argument in turn.
04:45This takes a little bit more complex code, but the good news is that Eclipse
04:49will write the code for you.
04:51Try this, type for, the word for, then hold down the Ctrl key and press Space.
04:58This keyboard shortcut is the same on both Windows and Mac.
05:02It brings up a list of available options.
05:04Choose the first option, for - iterate over array by pressing Enter or Return,
05:10and Eclipse adds a bunch of code that will loop through the array.
05:14Now, I am not going to describe the exact syntax of this code right now, we'll
05:18save that for later, but all you need to know is that when you use a for
05:22command and you provide all this information, you are looping through the
05:26contents of the declared array, in this case args, and you can deal with each
05:31item of the array in turn.
05:34I'll click into the for loop, between the braces, and once again I'll use
05:39System.out.println and then I'll pass in the value of the current argument using
05:47the syntax args, open bracket, i, closed bracket, and I'll remember to put in my semicolon at the end.
05:55i is a variable that was declared inside the for loop, when I said int i = 0,
06:01it's initial value is 0, and each time through the loop it's incremented by 1.
06:06The first item in the array is item 0, the second one is item 1, and so on.
06:11I'll press Command+S or Ctrl+S to save my changes, switch back to the command
06:16line, and pressing the Up Arrow run the application again.
06:20And now I see the total number of arguments and I see the value of each argument
06:25output one at a time.
06:27When you pass arguments from the command line, each argument is delimited and
06:31separated from the other by a space character, but if you want to include a
06:35space character and a value, just wrap the value inside quotes.
06:39So I'll press the Up Arrow to bring that command back again, but I'll move the
06:44cursor over and add quotes around the two words, arg1 and arg2.
06:49Then I'll run the application again, and this time I am told I only have one
06:54argument, and the value of the argument is the entire string.
06:58So that's how you pass in the arguments from the command line.
07:01How would you do the same thing directly in Eclipse?
07:05I'll go back to Eclipse and I'll go into my Run Configurations.
07:08I'll go to the Toolbar, pull down the Run Menu and choose Run Configurations.
07:13I'll add a new Run Configuration by clicking Java Application and clicking Plus,
07:20and the new name is going to be Main (1).
07:23And over here I'll click on the Arguments tab.
07:26I can pass in as many arguments as I want.
07:29I'll list these arguments one per line, so this will be arg1 and arg2 and arg3 and arg4.
07:39Then I'll click the Run button, and down here in the Console View I'll expand
07:44the Console so we can see all the output.
07:46I see Number of args:
07:474 and then each of the arguments listed one at a time as the code loops through
07:53and deals with each item in turn.
07:55So that's the purpose of the args parameter that's passed into the main method.
08:00It allows you to receive and process values that are passed into your Java
08:04application at runtime, either on the command line working in the command
08:08application in Windows, or in terminal on Mac, or from within Eclipse from a Run
08:14Configuration that's set up for this purpose.
Collapse this transcript
Using the Java API documentation
00:00As you've seen so far in this course, when you work in Java you are highly
00:04dependent on the classes that are a part of the Java Class Library.
00:08You can find documentation about these classes in the API documentation that's
00:13hosted on the Oracle website.
00:15One way to get to that documentation is simply through a browser.
00:19You can download the documentation locally, but by using the version that's on
00:23the Oracle website, you'll be sure you are looking at the most recent version.
00:27I am going to go to Google and search for Java 6 API docs.
00:33You can also look for Version 7 if that's the version of Java you want to use.
00:38This link takes you to the documentation.
00:41You'll see that there are literally thousands of classes to choose from, shown
00:45in this list in the lower left hand corner.
00:48You can filter the list if you know the package or group that a class is a member of.
00:52For example, one of the most commonly used packages in Java is called java.lang.
00:59A package is a group of classes that have common characteristics or work
01:04together in some way.
01:05I'll click on java.lang and I'll see a list of all sorts of classes that you'll
01:10use frequently in your Java programming.
01:13So for example, here is the String class.
01:16If I click on the link, it shows me all the documentation about the String
01:20class, the class that represents a string value.
01:24I've also used the System class so far, and that's also in java.lang.
01:28Now, you can also get to this documentation easily through Eclipse.
01:33You'll still need to be connected to the Internet, because you'll be referring
01:36to the same files up on the Oracle website, but you'll be able to get to what
01:40you want much more quickly if you know a couple of little tricks.
01:43So I am going to return to Eclipse, and let's say, for example, that I want to
01:48learn about the String class.
01:49I am going to move the cursor over the word String and after a moment Eclipse
01:54pops up a little bit of documentation.
01:57Notice in the lower right hand corner of the pop-up window it says press F2 for focus.
02:03So I'll press F2 and now I can expand and scroll through this set of documentation.
02:10And not all of the documentation that shows up in this window will contain links
02:13to get to the full docs for a particular class.
02:16So here is another way to do it.
02:18I am going to double click the word String to select it.
02:20Then I'll go to the Menu and choose Help>Dynamic Help.
02:26I see a new view appear on the right, the Help View.
02:30And I see a link, javadoc for 'java.lang.String'.
02:35When I click the link, that takes me to the full documentation for
02:39that particular class.
02:40I'll double click the Tab of the Help View and now I can scroll through and read
02:45everything about the String class;
02:47all of the different methods, properties, constructive methods, and
02:51everything else about it.
02:52I'll close the Help View and return to the main Perspective.
02:56Finally, I'll also show you that when you are working with a property of a
03:00class, and that property is an instance of a particular Java class, you can
03:05frequently get to the Javadocs for that class very simply.
03:09Just move the cursor over the property name and wait for a moment until the
03:13pop-up window appears.
03:15Then press F2 to give it focus.
03:18You can once again expand and scroll through the contents, and you'll see that
03:22the out property of System is an instance of a class called java.io.PrintStream.
03:29When you click the link, that takes you directly to the documentation for that class.
03:34And you can once again expand to Full Screen and read everything you want about
03:39the class and how to use it.
03:41So that's a look at how to get to the Java API documentation.
03:45Again, you can get to the complete documentation set through the browser;
03:48you'll be looking at documentation from the Oracle website.
03:51Or you can look at the documentation directly from within Eclipse, by using the
03:56dynamic Help feature or by using the F2 pop-up window that gives you direct
04:01access to the documentation for the classes that you are working with.
Collapse this transcript
Memory management and garbage collection
00:00One of the great charms of the Java programing language is that even though
00:04it's a compiled language, it manages memory for you, unlike languages like C,
00:11C++, Pascal, and others.
00:13You as the programmer don't have to explicitly allocate and de-allocate memory
00:18whenever you create an object.
00:20The Garbage Collector is a major feature of the Java Virtual Machine.
00:23I am going to describe how the Garbage Collector works and how little attention
00:28you as the programmer need to give it.
00:30When you create a variable that references a complex object, the object itself
00:35is stored in an area of memory called heap memory.
00:38There are two types of memory; stack and heap.
00:42The stack memory is somewhat faster;
00:44heap a little bit slower, but heap is more dynamic.
00:47When you create primitive variables, depending on their context, they might be
00:52stored in stack or heap, but complex objects are always stored in heap.
00:57As long as any variable references an object in memory, that object will be
01:02retained, it won't be eligible for garbage collection.
01:06So if you create a variable and it points to a string, a date, an array, a
01:11collection, or any other complex object, as long as that variable can be
01:16addressed in your code, the object will be available.
01:19When all references to the object expire, that is when you can't get to
01:24the object through your code anymore, then that object is eligible for
01:27garbage collection.
01:29So when do references expire?
01:31There are two models that you can look at.
01:34First of all, when you declare a variable that's local to a function or to a
01:38code block, as soon as the function or code block is done executing, that
01:42variable is no longer available to you, and so it has expired and is eligible
01:47for garbage collection.
01:49Within this function there are two scopes.
01:51Variables declared directly within the function are available as long as the
01:55function is executing.
01:57So the variable in function would be available until the function is done, and
02:02then it would expire.
02:03I've spoken previously about the fact that in Java, scope is also defined by code blocks.
02:09So in the second part of the code, in the for loop, I am declaring an integer as
02:14a part of the for loop, the name of the variable as i, and as soon as that for
02:18loop is done executing, that variable is no longer in scope and it's eligible
02:23for garbage collection.
02:25For variables that are more persistent, such as fields within objects, you can
02:30explicitly expire them by setting their value to null, N-U-L-L.
02:35So for example, here is string named expireMe, and if I want to make it eligible
02:41for garbage collection, I simply set its value to null.
02:44The object in memory can't be reached in my code anymore and therefore it's
02:49eligible for garbage collection.
02:51So when does garbage collection happen?
02:53The Garbage Collector runs in its own thread, so it doesn't affect your applications.
02:58As long as the system on which your application is running has adequate
03:01resources, you shouldn't notice that the Collector is running.
03:05And the Garbage Collector has incredible autonomy.
03:08The Java Virtual Machine runs the Garbage Collector when it thinks it needs
03:11to, and when the Garbage Collector identifies an object that no longer has any
03:15references, it has the option of either destroying it and reclaiming the memory or not.
03:21It has its own algorithm, its own logic, for figuring out how to manage the
03:25memory, and it's not up to you.
03:28You as a programmer cannot force garbage collection in Java.
03:31There are methods available in the language, such as System.gc() and
03:36Runtime.gc(), gc stands for Garbage Collector.
03:40These are methods that send messages to the JVM, that say it might be a
03:44good idea to collect garbage right now, but there is no guarantee that it will happen.
03:49And in fact, many Java developers recommend not using these functions.
03:53It can mislead you into thinking that you are getting all your memory back right
03:57away, but that's not necessarily what's going to happen.
04:00If you're running a complex application and you are challenging the available
04:05memory on the system, you will know, because the Java Virtual Machine will
04:09throw an error called OutOfMemoryError, and you will see these errors happen in
04:13more complex applications where an application is running on low memory devices or systems.
04:19You can manage the memory of the Java Virtual Machine by setting certain
04:23parameters when you start up an application.
04:26You can also tune your application by minimizing the number of objects that you create.
04:31As you've seen in many of the examples in this course, there are different ways
04:35of architecting Java code, so that you can create a whole bunch of objects, or
04:40you can reuse objects that you've already created.
04:42In general, it's better to reuse.
04:45If you're concerned about memory usage, you can use these methods to find out
04:49how much memory is available:
04:51Runtime.maxMemory(), Runtime. totalMemory(), and Runtime.freeMemory().
04:57Take a look at the Java docs for these methods to find out what information
05:00they are giving you.
05:01And you can use command line options to manage the amount of available heap memory.
05:07You can manage the memory in three areas;
05:10in the initial heap size, in the maximum heap size, and in the heap size for
05:15what are called young generation objects;
05:18objects that have just been created.
05:20If you want more information about memory management, take a look at the
05:24documentation for the Java programing language on the Oracle website.
05:29You will find that there is an enormous amount of information available.
05:32But when you're writing your first simple Java applications just know that the
05:37Garbage Collector is highly automated and as long as you are not running out of
05:41memory, you might not need to worry about it.
Collapse this transcript
4. Using Primitive Data Types
Everything is an object
00:00As you learn how to program in Java, keep this idea always in mind,
00:04everything is an object.
00:06As you design your applications, you'll be placing your code inside class
00:10definitions and wrapping that code inside functions known as methods.
00:15Let's take a look at a very simple application the Hello World!
00:18application I've shown previously.
00:20This time I've given the starting class a different name SimpleApplication.
00:25Notice that the main method though looks the same as before.
00:28That syntax is required, and as stated previously, the executable code is
00:34inside the main method.
00:36It outputs the string "Hello World!" to the console.
00:38You can diagram your Java applications using a syntax known as UML or
00:44Unified Modeling Language.
00:46This diagram shows that the name of the class is SimpleApplication and that
00:50it has a single method or function named main and it returns void which means
00:55it returns nothing.
00:56It doesn't return any value at all.
00:58Now, from this simple class, you might not get the idea that everything is an object.
01:03So let's expand the application a little bit to two classes.
01:07In this version of the application there are two classes, the starting class is
01:10still called SimpleApplication.
01:12It's the starting class because it's the one with the main method, and as the
01:16application starts up, the main method is called and the code in that method
01:21creates an instance of another class called Welcomer.
01:24That class is shown at the bottom of this screen.
01:27Shift your attention down to the welcome request.
01:29It declares a variable named welcome outside of any methods.
01:33We call those either instance variables or fields.
01:37In this case, there is an instance variable named welcome, it's a string,
01:42and it's private to the class which means that it can only be read by the
01:45code within that class.
01:47Its value is Hello.
01:49When, the function sayHello is called from that class, that class is responsible
01:53for outputting the string to the console.
01:55From the main application we create an instance of that class using the syntax
02:00Welcomer, that's the uppercase version, that's the data type and then the
02:04lowercase version is the name of the variable and we say that it's equal to the
02:08new instance of the Welcomer class that's an object and the object can have
02:14methods and properties.
02:16We call the object sayHello method and the result is to output the string to the command line.
02:21Once again, you can diagram this application using UML, in this case there are
02:26two classes SimpleApplication and Welcomer.
02:29This first class simply has the main method;
02:31the second class has both an instance variable or a field and a method named sayHello.
02:37Once again sayHello returns void or nothing, but it takes the action of
02:42outputting a string to the console.
02:44In Java, we say that everything is an object because it's very common to
02:48create an instance of class to execute some code and that code will be wrapped inside the class.
02:54As we actually get into coding some classes, I'll describe what's an object,
02:59what's a variable, and what's a field.
03:01Here is another way in which Java sees everything as objects.
03:06You can declare a String variable by declaring the data type String and then
03:10the variable name, in this case the variable name is welcome and then you can
03:13say that that variable has a value of a string wrapped in double codes, but in
03:19fact, this is shorthand.
03:21Here is the bit of code that's the longhand version.
03:24We declare the data type, we say what the variable name is, but now we say that
03:28we're creating a new instance of the String class and we pass in the string that we want.
03:33This is the longhand version and these two bits of code are exactly
03:37functionally identical.
03:39They do the same thing.
03:40They create an instance of the String class and so welcome is an object.
03:45But you can go further with this idea, because within a string object there is
03:49actually an array of individual objects, one for each character.
03:53So you can say that welcome is a String, Hello or you can say that welcome is an
03:58array of six object, H-e-l-l-o-!
04:03And here is a bit of code that breaks it down even further.
04:06I'll start off with an array of characters. char, bracket, bracket means create an array of
04:12characters. The name of the array is chars, C-H-A-R-S, and then the following
04:17syntax with the individual characters each wrapped in single quotes and then all
04:22then all six characters wrapped inside braces, means create an array.
04:26I can take that array of characters and wrap them inside a new string called s
04:31and now once again I have either an array of six objects or a single object the
04:37String s. When you start seeing everything as an object, you see that you can
04:41break things down to their smallest components in Java;
04:45a String is really an array of characters.
04:47A primitive numeric value is an individual value, but a complex object can
04:53reference many objects.
04:55By breaking things down into small pieces in Java, it makes it easy to find the
04:59code that you want to expand on or fix.
05:03The output of this code would be simply Hello!
05:06Because the String class is a complex object, it can encapsulate or offer all
05:11sorts of functionality and in fact the String class, which in longhand is
05:15java.lang.String includes many, many methods.
05:20This is a short list of just a few of the methods that are a part of the String class.
05:24The charAt method lets you pass in a numeric value and get back the character
05:29in the position in the array that's a part of the String class, you can use
05:32compareTo to compare one String to another, the concat to concatenate Strings
05:37together and so on.
05:39We'll be looking at these and many more methods of the String class later on,
05:43but my point is that a string is not simply a string, it's an instance of a
05:47class and that gives you access to all the functionality that's built into
05:52that class as a part of the Java Programming Language and its core runtime,
05:57the Java Class Library.
Collapse this transcript
Declaring and initializing variables
00:00As with all good programming languages, Java supports the use of variables to
00:05store data in memory.
00:06There are two major types of variables in Java known as primitives and complex objects.
00:12Primitive variables are stored in the fastest possible memory, but there is a
00:16very small number of data types that you can store this way.
00:19They include numeric values such as integers and floating decimals, single
00:24characters not complete strings, and Boolean values, variables that equate to
00:29either true or false.
00:31These values can be stored as primitive values and so they are placed in memory
00:36and they can be accessed very, very fast.
00:39Everything else that you might want to store in memory in a Java application is
00:43going to be represented as a complex object.
00:46You have to clear a complex object as an instance of a Java class.
00:51Here are some data types that you might think of as simple values depending on
00:54what languages you might have used before, but in Java, are complex.
00:59These include strings.
01:01Any string value longer than a single character must be stored as a complex
01:06object and not as a primitive.
01:08Date values which can be interpreted as numeric values, the number of ticks from
01:14a particular date, but in terms of Java memory management are stored as complex
01:19objects and everything else that you might want to work with.
01:23As I have mentioned previously, pretty much everything in Java is an object of some kind.
01:29So how do you actually declare a variable in your code?
01:32The syntax looks very similar regardless of whether you are working with
01:36a primitive or a complex object, but there is a significant syntactical difference.
01:41Let's look at primitives first.
01:43You declare your variables in three parts.
01:46The first part is the data type.
01:48Every variable that you declare in Java has to be declared with its data type
01:53and once the data type is set, it can't be changed.
01:57This is how the Java virtual machine determines how much memory needs to be allocated.
02:02The second part is the variable name.
02:05Variable names in Java always start with the lower case initial character which
02:09can be an alphabetical value or an underscore, but not a numeric.
02:13These two parts are required.
02:15The third part is optional and it's the initial value of the variable.
02:19Here is a classic primitive variable declaration int newVariable = 10.
02:26The first part is the data type, int stands for integer, so you are declaring
02:31the variables in integer and you will only be allocating enough memory to store an integer.
02:36You can't just magically change this variable at runtime and turn it into say
02:40a double or a float.
02:43It's always going to be an integer.
02:44The second part of the variable declaration is the name.
02:48The name of the variable can't have any spaces or other special characters in it
02:53and the initial character has to be either alphabetical or an underscore
02:57character, it can't be a number.
02:59The length of the variable name is up to you, but I recommend that you name the
03:03variables so that they mean something to you as a developer.
03:06You'll see variable named i or x in varied limited scopes, but if a variable
03:11is going to stick around and be useful in your application, give it a name that matters.
03:16The last part of the declaration is optional.
03:19This is this assignment of the initial value.
03:22You use the equals operator which is the assignment operator and you pass in a
03:26value that's compatible with the data type that you declared.
03:30The value 10, in this context, is a literal integer.
03:34So I am assigning the value of 10 to the integer and while I can change
03:38the value of new variable later on the value I assign later also has to be an integer.
03:44If you leave the assignment off, then the primitive variable will have its default value.
03:49For numeric, that's always zero.
03:52For Booleans, it's false.
03:54Now let's take a look at how you declare a complex object.
03:57The declaration of a variable as a complex object once again is an instance of a class.
04:03As with primitives, you declare them in three parts;
04:06the required data type and required variable name and then the optional
04:10assignment of the initial value.
04:12When you set the value of a complex object you use the new keyword and a
04:17particular kind of function or method called the constructor method of the class.
04:22The name of the constructor method matches the name of the class.
04:25So if you are declaring something is a string, then you are going to use
04:29a method name String.
04:30Here is what the code looks like.
04:32Once again it will have the data type and the variable name and then
04:36optionally the initialization.
04:38The first part of this declaration is the data type.
04:41I am referring to a class.
04:43How do I know this is a class and not a primitive?
04:46Well, primitive data types are always all lower case.
04:49So int double float Boolean and so on, they will be spelled all lowercase.
04:55When you see a data type within an initial uppercase character, now you are
04:59talking about a class and you know you are working with a complex object.
05:03The variable name once again goes second and the conventions for naming complex
05:08object variables, is the same as for primitives.
05:11The initial character must be an alphabetical character or an underscore,
05:15you can't use numbers for the first character and by very strong convention it's lowercase.
05:20You can use uppercase characters in the middle, a syntax, we sometimes call
05:24camel case to make it more readable.
05:27The optional assignment looks like this.
05:29As with primitives you use the equals assignment operator, but now because you
05:34are creating an instance of a class, you use the new keyword and you call the
05:38constructor method of the class which matches the name of the class.
05:43Some constructor methods are called without passing any values in and some
05:47constructor methods are called and you have to pass values in and in some
05:50cases it's optional.
05:52You'll look at the API documentation for the class you want to use to figure out
05:56what the right syntax is.
05:58For complex object variables, if you eliminate the assignment, the variable name
06:03will exist, but it won't point to anything in memory and we say that that
06:07variable has a value of null, n-u-l- l and I'll show how to deal with null
06:13values, later in the course.
06:15When you need to clear a variable, it's important to know what its scope and lifetime is.
06:20You can either declare a variable inside a function or method or you can declare
06:24it outside the function as a part of the class.
06:27When you declare the variable inside the function, the variable is local to the
06:31function and when the function is finished executing, the variable goes away.
06:36It's no longer available.
06:38We call it being dereferenced.
06:40Here is an example of a string variable which is declared inside a function or
06:45method called doSomething.
06:47The data type is String.
06:49The name of the variable is sayHello and it's an instance of this String class
06:53with the value Hello!.
06:55This code works fine because I am referencing a variable that was declared
06:58inside the same function in which I am trying to output it, but let's take a
07:03look at a bit of code that doesn't work so well.
07:05In the function, doSomethingElse, I am once again declaring a variable and
07:09giving it an initial value of Hello!
07:12But then I try to reference that variable in code that's outside the function.
07:17Because the variable was declared inside the function, it is not available to
07:21code outside the function, it can only be referenced inside the function and
07:26when you type this code and try to save your application, you'll get a
07:29Compile-time error!!.
07:31If you are working in an Eclipse you'll see something in the Problems view that
07:34says I don't know what that variable is, it's not in scope.
07:38There are times when you want variables to be available to more than one
07:42function or method at the same time and there are a few different ways of doing this.
07:46One of the most popular is to use something called a class variable known
07:50officially in Java as a field.
07:53When you declare a variable outside of the function, it belongs to the whole
07:57class and it can be referenced by any function within the class.
08:01Here is an example.
08:02I am declaring a class called MyClass.
08:05Notice that this time I don't have a main method.
08:07So this is not a class that's starting up the whole application.
08:10Within the class, I am declaring a variable and giving it a data type of String,
08:15a name of sayHello and once again an initial value.
08:18The function doSomething can reference that variable because the function and
08:23the variable are both members of the class.
08:27As long as the method and the variable are both part of the same class, the
08:30method can reference the variable and use its value.
08:34So once again this kind of variable is officially called a field in Java.
08:39You will also hear it referred to sometimes as a class variable, but the two
08:43phrases mean the same thing, class variable and field.
08:46And if you look at the documentation for the classes in the Java Class Library,
08:51you'll see that this type of variable is referred to as a field in the API docs.
08:57So that's a brief look at how to declare variables and a little bit about the
09:01differences between primitives and complex objects.
09:05In the next video, we'll do some exercises in Eclipse where we declare some
09:09variables and output their values using the System.out.println syntax.
Collapse this transcript
Working with numbers
00:00In Java, you can represent numbers as either primitive values or as complex objects.
00:05I am going to start by showing you how you represent them as primitives and then
00:09show, how to convert them into complex objects when needed.
00:12A primitive data type is a simple value.
00:15It represents only a single value and not many.
00:18That's one of the big differences between primitive values and complex objects.
00:22A primitive always points to a single value.
00:25Primitive data types are stored in the fastest available memory, whereas complex
00:29objects are stored in heap memory.
00:32When you are running an application, you won't see significant differences, but they do exist.
00:37Primitives can be used to represent numeric, logical, or single character values.
00:42They can't be used to represent strings, dates or other things that have to be
00:46represented as complete objects.
00:48Most of your numeric values will be declared as primitives.
00:51You will only need to use complex objects where you need to do conversions or
00:56you need to guarantee precision when doing certain kinds of calculations.
01:00When you declare a primitive data type, you spell the data type in all lowercase.
01:05So for example int, i-n-t or byte would be spelled all lowercase.
01:10There are also classes with these names, but they will have an uppercase initial character.
01:14Here are the numeric primitive data types.
01:17The byte data type takes 8-bits and can represent numbers starting at -128 and
01:23going to a maximum of 127.
01:26The short integer takes 16-bits and has much greater range and the most commonly
01:32used integer data type int takes 32-bit to memory and has a minimum and maximum
01:38of over 2 million in each direction.
01:40There is also a long integer.
01:42It takes twice the memory that an int does and should only be used when you are
01:46representing very large numbers.
01:48Then there are two primitives that can represent floating values.
01:52The float takes 32-bits and the double takes 64-bits.
01:56You'll see developers represent currency values frequently with doubles, but as
02:01I'll explain later typically, you will want to use a special class called
02:04BigDecimal for that sort of purpose.
02:07When you use primitives, you can set their values directly using literal
02:11representation of numbers.
02:13For the first three primitive data types, byte, short, and int, the syntax of
02:18the number is pretty conventional.
02:20It's just a numeric value without any quotes.
02:23You can't include string values such as currency symbols or commas.
02:27When you get into the larger numbers, the long, the float, and the double, the
02:32syntax is a little different.
02:34For long values, a literal numeric should be followed with the letter l, for long.
02:40You can use either an upper or lowercase l, but because the lowercase usually
02:44looks a lot like a 1, typically developers will use the uppercase L. The float
02:49value takes a lowercase f and the double value, a lowercase d. Again, you could
02:54use uppercase, but most developers use lowercase for these.
02:58If you don't put in those additional alphabetical characters, usually things
03:01will still work out okay, but what's happening internally, may surprise you.
03:06If you don't put in that additional alphabetical character into your code, the
03:09value will be cast, based on a set of rules, that Java follows, for example the
03:14100 would be initially be cast a byte and then it would be up cast to the long.
03:19So you are actually taking more memory than necessary creating two values
03:23where only one is needed.
03:25So it's recommended that if you are explicitly using a literal to represent a
03:29long, a float or a double then use these characters.
03:34In addition to the primitive data types for numbers, there are also a set of
03:38helper classes that are part of the Java Class Library.
03:41Each of these helper classes includes tools for converting and
03:44outputting numeric values.
03:47Here is a listing of the data types on the left and their matching helper
03:50classes on the right.
03:52For the most part the names match, byte is byte, short is short and so on and
03:57the only difference is the initial character.
03:59The primitive data type is all lowercase.
04:02The class name has an initial uppercase character.
04:04The only difference is in the integer where the primitive Data Type is int and
04:10the name of the Helper Class is Integer with an uppercase I. The helper classes
04:15have all sorts of great tools in them and they are always available to your Java code.
04:20Here is an example.
04:21The Double class provides methods and other tools for converting and
04:25managing double values.
04:27Let's say you started off with a literal doubleValue of 156.5d and you assigned
04:33that to a primitive variable of doubleValue.
04:36Well, in order to convert it, the first step would be to create an instance
04:40of the Double class.
04:42This would be the syntax.
04:43The data type has Double with an uppercase D, which means the helper class
04:48and not the primitive.
04:49I am constructing an instance of the Double class and passing in the primitive value.
04:54Now I can convert that value using a set of methods called byteValue, intValue,
05:00floatValue and toString.
05:03These are instance methods or class methods of the Double class.
05:07We'll learn more about what that means in later videos, but for now just take
05:11it to mean that you can call these methods whenever you create an instance of the class.
05:16Because a doubleValue you can have more precision than say a byte or an int,
05:20calling this syntax will result in truncating the value.
05:24So the result of myIntValue would be simply 156.
05:28The result of myByteValue though because 156 exceeds the available range of a
05:33byte, would wrap around and you would actually end up with a negative number.
05:38I'll show you examples of these in some of the codes samples.
05:41When you declare a number, using a primitive data type, if you don't set the
05:46value initially, it defaults to zero.
05:49So for example, here I am declaring a variable called myInt and I am setting it
05:53using the int data type.
05:55I am not including the equals assignment operator or an initial value and so the
06:00result is that myInt is initially assigned as 0.
06:05You'll see that this is true of all the primitive numerics.
06:08Now when you get into complex objects instances of classes, the rules are
06:12different, but we'll talk about that later.
06:15There is one other major issue to know about when you are working with numbers.
06:19If your application requires numeric precision, when you are doing calculations
06:23or rounding, you shouldn't use primitives for this purpose.
06:26The problem is that primitive values are stored in memory in a way that can't
06:30guarantee that precision.
06:32Instead, you should use a class called BigDecimal especially when you are
06:36working with currency values and you need to do certain kinds of math, the
06:40BigDecimal class can help you guarantee that precision.
06:43Here is an example of what can go wrong.
06:46Let's say that you are starting off with a primitive value, in this case
06:49a literal of 1115.37.
06:50I am going to create an instance of the BigDecimal class called payment and I am
06:57constructing it directly from that literal value and then I am going to output
07:02that value as a string.
07:03You might think you would see the value 1115.37 as a string, but in fact you are
07:09going to see something like this.
07:11The exact value is going to vary depending on your system, your processor and
07:15other variables, but internally the number is stored in a very surprising way.
07:20So when you are working with currency values, it's strongly recommend that you
07:24construct your big decimals based on strings.
07:28This guarantees that you are talking about exactly the value you think you are talking about.
07:33Let's say for example that you start off with a double value once again of 1115.37.
07:39Before you create your instance of BigDecimal, you should first get a string
07:43representation of the number.
07:45This guarantees that any additional decimal values are truncated and you are
07:50only working with the value you want.
07:52So the second line of code uses the Double class's toString method and converts
07:56to a value called ds, data-typed as a string.
08:00Now I construct the instances of BigDecimal based on the string and then output
08:05the value and now I get what I expect.
08:07We'll talk more about the BigDecimal class in a later video in the series.
08:12So that's a look at representing numeric values in Java.
08:15For most purposes, the primitive data types do a great job, but in many cases,
08:20you want to use the numeric helper classes that are part of the class library
08:24and specifically when you are working with currency values and doing
08:28calculations and rounding, you should look at the big decimal class.
Collapse this transcript
Converting numeric values
00:00There will be times in your applications when you need to convert values from
00:04one data type to another.
00:06It's important to understand how data types are converted especially when
00:09working with primitives.
00:11Here are the primitive numeric data types arranged in order from the
00:14greatest memory usage and the largest ranges to the smallest memory usage
00:19again the smallest ranges.
00:21So the double takes 64-bits and can handle the greatest precession or as the
00:26byte has the smallest range.
00:28When you convert a value from say a byte to a short, a short to an int or an int
00:32to a long, we call that converting upward, you're taking a value that fits
00:37easily into the next value upward.
00:39You can do this sort of conversion with very simple syntax.
00:43Here I'm declaring an integer value of 120 and then passing that value to a
00:47new variable data typed as a double, the value of 120 can fit easily in either data type.
00:54And so the result is that you have a value of 120, the double version would have
00:58the decimal value of 0, the integer value would be truncated but they would
01:02fundamentally have the same value.
01:04We call this sort of numeric conversion implicit you can simply assign a value
01:09from one variable to another without any special notation and because all of the
01:14conversion is reliable that is the values will fit in both variables easily you
01:18don't have to say anything specific in your code about it.
01:21When you're converting values in the other direction though you can run into
01:25some trouble and so Java requires you to be explicit in these sorts of
01:29conversions, once again here is my listing of the numeric data types, but now
01:34I'm indicating through the arrows that I'm going to do the conversions in the
01:38other direction from a double to a float or a float to a long.
01:42We call these downward conversions.
01:44Here is an example, I'm starting with the double value of 3.99 and then I try
01:49to convert the value to an integer by simply assigning the value to the new variable.
01:54You won't even be able to compile this code because Java knows that you're in
01:58danger of loosing data.
02:00So if you add this code to your Java class and try to save and compile you'll
02:04get a compile-time error.
02:06The compiler will tell you that those two data types aren't compatible with each other.
02:11So you instead have to explicitly tell the compiler that you know what you're
02:15doing and you do this by adding the target data type before the original value
02:20wrapped in parenthesis, here is the added syntax this means take the
02:24doubleValue and cast or convert the value to an integer and then you can pass the value over.
02:30You're still in danger of loosing data;
02:32the value of 3.99 which fits fine in a doubleValue doesn't fit in an integer
02:38value, because integers can't have fractional amounts.
02:41So when you do this you're going to truncate the value, it's going to end up as
02:44the value 3, but you've told the Java compiler that that's what you want to do
02:49and so the compiler will let you do it.
02:51The double value will still be 3 .99, but the integer will be 3.
02:56So the lesson to take from this is that when you converting downward you have to
03:00be explicit in your code and you have to know that you might change the data.
03:05The dangers of downward conversion aren't limited to simply truncating and
03:08loosing values you could actually change values pretty dramatically.
03:12Let's take an example where you start off with an integer and you want to
03:15convert it to a byte.
03:17Well, the ranges of integers and bytes are very different;
03:20integers can handle values in the two millions both positive and negative
03:25whereas bytes can only handle values from negative 128 to positive 127.
03:31So what happens if you start off with an integer say if 128 that exceeds the
03:36range of the byte and then you explicitly tell Java I want to turn this into a
03:40byte what is it going to do.
03:42Well it's going to take the value that exceeds the range of the target data type
03:47the byte and it's going to wrap around and assign an opposite value.
03:52So if you start off with a positive you end up with a negative, the result of
03:56this code would be a Value of b of -128.
04:01Remember the range of a byte goes from negative 128 to positive 127.
04:07I'm trying to assign a value that exceeds that range by 1, so it wraps around
04:12by 1 and becomes negative 128, the smallest possible number instead of the
04:17greatest possible number.
04:18You'll see this sort of conversion this wrapping around whenever you try to
04:22convert a value downward from one data type to another.
04:26Finally, in the discussion of converting numeric values it's worth mentioning
04:30that there are two possible ways of doing it.
04:33When you're converting between primitive data types you can either use this
04:37casting syntax that I've shown or you can use those helper classes, the double
04:41class, the byte class, the integer class and so on.
04:45The simple casting syntax uses the target data type wrapped in parenthesis right
04:51before the original value.
04:52So here I have a double value, a primitive double starting off a 3.99, I
04:57explicitly convert that to an integer using the casting syntax and now I can
05:02assign that to an int.
05:03Again I'm going to truncate values, I'm going to loose data but it's going to work.
05:07So use the helper class approach, the first step is to create an instance of the
05:12helper class wrapped around the primitive value.
05:15So here I'm starting once again with a primitive and then I'm creating an
05:19instance of the double class wrapped around the primitive, I'm calling that double0bj.
05:24Once I have that reference that complex object I can then call any of its
05:29method, so now I'm going to call the intValue method, it's going to return an
05:34integer and I can assign that to the primitive int.
05:37Either of the syntax styles will work fine.
05:39There is a minor advantage to the simple casting syntax clearly it takes less
05:44code, but also you're not adding another object to memory.
05:48When you use the helper class method you are creating an instance of that double
05:51class that you really don't need.
05:53So for the most part the simple casting syntax is preferred and the only time I
05:58would recommend using the helper class approach is when you want to store that
06:02data for the longer term and do multiple things with it.
06:06Convert it to an integer and a byte and a float and so on.
06:10So that to look at issues around converting numeric values from one data type to another.
06:15You can use either the casting of the helper class method syntax and always be
06:20aware of what happens when you try to cast from one data type to another.
06:24When you are converting the data upward through the data types all the
06:27conversions are implicit and safe, when you're converting downward beware of
06:32loosing data, wrapping values around, and also note that you have to be explicit
06:37in your instructions to the compiler.
Collapse this transcript
Understanding operators
00:00Every programming language supports operators, characters or sets of characters
00:05that execute particular operation.
00:07Java remember is C-style language and it uses the same set of operators as
00:12most such languages.
00:14If you already know JavaScript or ActionScript you will find that the operators
00:18in Java are almost identical.
00:20Here are some of the types of operators I'll discuss in this video.
00:23Assignment operators let you set values.
00:26There is a Simple Assignment Operator and then there were more Complex
00:29Assignment Operators that let you assignment and math in a single statement.
00:34There are equality and relational operators that let you compare values to each other.
00:39There are mathematical operators that let you execute common mathematical
00:42process, Conditional operators that let you define complex conditional
00:46processes, and the ternary operator which is a special operator I'll describe in
00:51a later video when I discuss conditional processing.
00:55The most common operator that you'll find yourself using is the
00:58Assignment operator.
00:59The single equals character is the assignment operator.
01:03You put the variable you're assigning to on the left and the value on the right.
01:07You can assign a literal value or a value return from a method or a reference
01:11to a complex object.
01:13Regardless of what you're assigning the single equals operator always is used.
01:17The simple math operators are the same as in JavaScript and ActionScript, the
01:22plus operators is used for math.
01:24So if I start with the value of 10 and I increment it by 5 with the + operator I
01:28get a value of 15, the - character is the traditional minus operator, the
01:34asterisk is used for multiplication and the forward slash is division.
01:39There is another single character operator worth knowing about the modulus
01:42or remainder operator.
01:43Java uses the % character for this.
01:46If you take a value of 10 and you take the modulus of 5 that returns a reminder of 0.
01:53So those are the five primary math operators.
01:56You can combine these math operators with assignment too.
02:00Once again starting with an initial value of 10, let's take look at how you can
02:04increment and decrement values. The ++;
02:07operator means add one, so adding 1 to 10 gives you 11, the - -;
02:12operator goes in the other direction decrementing by one and that would give you a result of 9.
02:17Here is how you can combine math operators with assignment, += means take the
02:23current value of this variable and add whatever is on the right side. So intValue +=5;
02:29would be 15. intValue -=5;
02:31would be 5, *= 5;
02:33equals 50 and /= 5;
02:36would result an intValue having a value of 2.
02:39Be aware that when you use the /= you need to make sure that you're assigning a
02:44value that matches the data type of the original variable.
02:48When you use the increment and decrement operators you can place them either
02:51before or after the variable name, the operational result will be a little bit
02:56different depending on the position of the operator.
02:58Once again starting with the value of 10, a Postfix operator looks like this
03:03intValue ++, when you place the ++ operator after the variable you're saying
03:09first evaluate the variable and then execute the mathematical operation, because
03:14I've wrapped this inside a print line command I'm going to be outputting a value
03:18and changing it's value, but you need to know that with this Postfix syntax the
03:23evaluation happens first and only after that does the math happen.
03:28The result would be an output of 10, but then after the statement is complete
03:33the new value of the variable would be 11.
03:35If you move the ++ operator before the variable name that's called a Prefix or a
03:40Unary operation, this would mean do the math then evaluate the variable.
03:46And in this case the output and the new value would be the same.
03:49Java's relational operators, that is the operators as you used to compare values
03:54to each other look exactly as you would expect.
03:57You have >, <, >= and <= values.
04:02There is also a special operator called instanceof it's all lower case and all one word.
04:07You use the isntanceof operator to determine whether a variable is a member
04:11of particular class.
04:13Here is an example I declare a variable with a data type of String and I set it to some value.
04:19Now, I want to test that variable and ask whether it's an instance of
04:23a particular class.
04:25Typically when you use the instanceof operator you refer to the class by its
04:29fully qualified strength, its package, and its class name.
04:32The String class is a member of the java.lang package, so the complete
04:36evaluation of (s instanceof java.lang. String) means is s a String and if so then
04:45I would output the String that's in the middle of if clause.
04:48One very important thing to know about comparisons is that you can't use the
04:52traditional comparison or relational operators when you're working with Strings.
04:56Let's take a look at this code, there are two Strings named s1 and s2, they have
05:01identical values of "Hello";
05:03and now I put in some conditional code, I ask the question if (s1 ==s2) then
05:10output ("They match");
05:11and otherwise output ("No match!);.
05:13In some languages such as JavaScript you would get a match because in those
05:18languages they're comparing the values of the Strings, but in Java a String is a
05:23complex object and with complex objects the double equal operator is comparing
05:28whether they're the same object, not whether they have the same value and so
05:33this evaluation would result in the output No match!.
05:36If you want to compare two Strings you instead need to use a special method or
05:41function of the String class.
05:42Here is the correct example, once again I'm declaring two Strings named s1 and
05:47s2, now I'm going to use the equals function or method of the String class and
05:52I'm asking whether the values of these two variables match, not whether there
05:56the same object and this time the output is They match!
06:00With primitive variables you can use that double equal operator and you'll be
06:04able to match the values to each other, but with complex objects like the
06:08String you frequently have to use a method of the class to determine whether the values match.
06:14Speaking of equality, here is how you compare values when you're working with primitives.
06:18The equality operator is double equal sign.
06:21Be sure you're using double equals not single equals, if you use single equals
06:25you'll be assigning the value and not comparing it.
06:28The inequality operator is an exclamation mark and the equal sign.
06:33So this syntax is asking if this value is not equal to that.
06:37And finally you can also use the exclamation mark on it's own to reverse the
06:41value of a Boolean Expression.
06:43A Boolean Expression evaluates to either true or false, when you apply the
06:48exclamation mark before it that reverses the value.
06:51If it's started as true it becomes false and if it started as false it becomes true.
06:57You'll hear some developers refer to the exclamation mark as the bang character B-A-N-G.
07:03And so if they were reading this code it would be if bang this then do something
07:10regardless of what you call it bang or the exclamation it reverses the logic,
07:15changing a Boolean value from true to false or vice versa.
07:19Here are some conditional operators that you can use in complex logical operators.
07:24The double ampersand is Conditional AND.
07:27In this code the output would only happen if both this and that are true.
07:32You can also do a Conditional OR using the double pipe character, in this code
07:37the output is going to happen if either of those variables equates to true.
07:42I'll show you more about how to combine these conditional operators with various
07:46types of conditional expressions in later videos, but you should now have a good
07:50sense of the kinds of operators that are available in Java and how similar they
07:55are to other C-style languages.
Collapse this transcript
Working with character values
00:00Java allows you to represent strings in one of two ways as complex objects or
00:05as single character.
00:06When you are working with single characters you can work with either a primitive
00:10data type or with a wrapper class for the data type.
00:13I am working in a project named characters which you can find in the 04 chapter
00:17of the exercise files.
00:19In order to declare variable that uses the primitive card data type you start
00:23off with the keyword car or char.
00:26You don't spell out the whole word character, it just those first four letters
00:30then you assign a variable name as usual and then you can either assign
00:33something that returns a character or you can assign a literal character.
00:38Literal character values are wrapped in single quotes, never double quotes.
00:42I am going to set the value of this character to a numeric value of one
00:46because I want to show you that when you pass in a numeric value but rapid in
00:50those quotes it's no longer really a number and it can't easily be turned into a number.
00:55It can be converted to another variable that's a number, but this variable will
00:59always be a character.
01:00Now I am going to copy and paste this line of code a couple of times and I am
01:04going to rename the second 2 variable as c2 and c3 and change their values to 2 and 3.
01:11Now I am going to output those values to the console.
01:14System.out.print and then I'll pass the values c1.
01:19notice I am using print and not println because I want to output this but not
01:24pass in a line feed at the end.
01:26Now I'll copy and paste that line of code a couple of times, and I will output
01:31c2 and c3 and I'll change the last one to println.
01:35I'll save the changes and run the application and there is the result.
01:401, 2, 3 three characters output right next to each other.
01:44You can also set a character variable using a Unicode literal.
01:48Unicode is a way of describing individual characters in the alphabet
01:52using numeric codes.
01:54You can look up the numeric codes for Unicode on the website Unicode.org, that's
01:58u-n-i-c-o-d-e.o-r-g.
02:02I have looking up the value of the currency symbol the dollar sign and I found
02:06that it's a four digit number of 0024, here is how you could use that code to
02:11set a char variable in Java.
02:13I once again start off with the char data type and I'll name this variable dollar.
02:18To set the literal value with Unicode start with the pair of single quotes as
02:22before but prefix the four digit numeric with \u, then I'll pass in 0024.
02:29Next I'll add another system.out. print at the beginning of the string and I
02:33will output dollar.
02:34I will save the changes and run the application and there is the result.
02:38The dollar sign followed by the 1, 2 and 3.
02:42Again these are four individual characters not a single string but from the
02:46application users point of view it looks like just a string.
02:49As all with primitive data types there is a wrapper class available that you can
02:53use to accomplish all sorts of things.
02:55The name of the wrapper class for char is character.
02:58Now I've already brought up the documentation for this class it's a member of
03:02the Java.link package and is always available to your code.
03:06I'll go to the list of methods that are part of the character class and show you
03:10that there are all sorts of tools for analyzing or changing values.
03:14I'll go to the bottom of this listing and show you that there is a method
03:17called two uppercase.
03:19It's marked as static which means I call it from the class not from an
03:22instance of the class.
03:24We'll talk about static properties and methods later on, but for now whenever
03:28you see the world static just note that you call it from the class name not from
03:32an instantiated copy of the class.
03:34You pass in and instance of the char variable.
03:37So now I'll go back to my code and I am going to go down to the bottom of the
03:41code and add some more characters.
03:44I'll start off with char a1=a char a2= b and char a3=c.Now I'll make a copy of
03:56these three print commands, copy them downward and I'll change the values that
04:01are being output to a1, a2, and a3.
04:04I'll save the changes and run the application and show that I am getting a, b,
04:10c. now I'll use the two uppercase method of the character class.
04:14For each of these values I'll place the cursor inside the print method and
04:18call Character.toUppercase and I wrap the method called around the value that I am outputting.
04:26I'll make a copy of that line of code that will be easier than we typing all
04:29that a couple of times then I'll paste it in a couple of times, change the
04:34variables and change print to print line for the last command.
04:39I'll save my changes and run the application and now I am outputting the
04:43uppercase versions of those character values.
04:45Notice I am not changing the original values, I am only modifying them as I output them.
04:50So the original lowercase versions are still available.
04:54So that's a look at how to use the char also sometimes pronounced char, char, or char data type.
05:01Once again it represents a single alphanumeric character the literal value is
05:05always wrapped in single quotes never double quotes and in your literal values
05:09you can use either the real character or the Unicode equivalent.
Collapse this transcript
Working with boolean values
00:00True and false values are stored in Boolean variables in Java.
00:04You can either use primitive data types or the matching wrapper class also
00:08spelled Boolean with an uppercase B. I am working in a project named Booleans
00:12which you can find in Chapter 04 of the Exercise Files.
00:16I'll declare two variables.
00:18For primitive data types, use the keyword boolean, all lowercase.
00:22My first variable will be names b1 and will have a value of true.
00:27The second variable will be b2 and it will have a value of false.
00:32These are the only two possible literal values for Booleans variables.
00:36Unlike in many languages such as JavaScript, you can't just replace the Boolean
00:40keywords true and false with say numeric values.
00:44There is no built-in logic that says 0 is false and any other number is true.
00:49So you have to use the words true or false.
00:51They are spelled in all lowercase and don't get any quotes or other notation.
00:55If you try to output these values to the console, they will be translated as
00:59their equivalent strings.
01:00So I'll add this code System.out.println (" The value of b1 is-- and then I'll append b1.
01:08Then I'll make a copy of that and paste it and I'll run the application and I'll
01:14see that the value of b1 is true and the value of b2 is false.
01:19You can reverse the value of a Boolean variable by prepending the exclamation
01:23mark or bang symbol.
01:25So for example I'll create a new variable.
01:27I'll call it b3 and I'll use the reverse value of b1 using !b1.
01:35Then I'll make a copy of my println command and I'll paste it in.
01:40I'll change to the b3 variable and I'll run the application and I see that the
01:45result of reversing b1 which started as true is now false.
01:50If you want to evaluate numbers as Booleans, you have to write the code
01:54yourself, but it's actually a pretty small amount of code.
01:57Let's create an integer value named i and set it to a value of 1.
02:02Now again in many languages the #1 would have an equivalent value of true, but
02:06that equivalents doesn't exist already in Java, so we have to code it.
02:10So I'll create a variable named boolean b4 and I'll use this logic.
02:15I'll create a pair of parenthesis and in there I'll use the expression, i != 0.
02:21So the expression comparing the value of the integer to the value 0 is wrapped
02:26inside parenthesis that forces it to be evaluated first and then the Boolean
02:30result which results from asking the question do these values match is returned
02:34to my boolean variable.
02:35Then I'll once again use a println command, I'll put the value of b4 and because
02:42i does not equal 0, I should get a value of true.
02:47If I change the value of int i to 0 then the value of b4 is false.
02:53So this simple expression is a very easy way to take care of the situation where
02:57you want to translate a numeric value to a Boolean value.
03:01Finally, just as with the other primitive data types there is a wrapper class.
03:05It's named Boolean with an uppercase B and as with all the data type wrapper
03:10classes, it's a member of the package java.lang which means it always
03:14available to your code.
03:16The Boolean class has a fairly small set of supporting methods.
03:19I'll show you how to use this one, parseBoolean.
03:22The parseBoolean method accepts a String value and translates it into a real Boolean.
03:26So let's go back to Eclipse and at the bottom of the code, I am going to declare
03:31a String, I'll just name is s and I'll give a value of true.
03:37Then I'll create a boolean variable, I'll call it b5 and I'll call that parsing
03:42method from the Boolean class, Boolean. parseBoolean and I'll pass in the value
03:47of s. And finally, I'll once again copy and paste System.out.println and change
03:55to output the value of b5 and show you that the result is a value of true.
04:02Now the logic that's going on here is pretty interesting.
04:04The parseBoolean method is non-case sensitive.
04:07So I can actually spell the word true with upper or lower case characters, even
04:11though the true keyword in Java is all lowercase.
04:14I'll make that change and show you that evaluation still returns true.
04:19And if I change the value of s2, false, either upper or lowercase, I'll get the
04:25value false, so far as expected.
04:27But what happens if you pass in a value that's neither true nor false? I'll pass in xyz.
04:33When I run the application now, I don't get an error.
04:36Instead, I get back a value of false.
04:39The logic that this method is using is if it's not true then it must be false.
04:43So any version of the word true will return true and any other string will return false.
04:50So that's a look at some of the rules around Booleans in Java.
04:53Once again, you start off with the keywords true and false which are the only
04:57available literals for a Boolean variable.
05:00You can reverse a Boolean variable, using the != operator and you can use the
05:05Boolean wrapper class to parse strings as Booleans and accomplish other tasks
05:09that are common to true and false values.
Collapse this transcript
Outputting primitive values as strings
00:00No matter what kind of value you are working within Java, you can typically
00:04output that value as a string, simply by concatenating it to some other value.
00:08To demonstrate this, I have declared eight variables, one each of the primitive
00:12data types, character, Boolean, byte and so on.
00:16Each of these is using a literal value as its initial value.
00:19Now I'll place the cursor after the declarations and use System.out.println and
00:25first I'll output the character.
00:28I'll save and run the application and I get the letter z, that's pretty expected.
00:33Now one of the great things that Java does for you is that when you want to
00:36translate something into a string, it's usually fairly automatic.
00:40I am going to copy and then paste this line seven times and I'll change the
00:45values that I am outputting in each of these lines using the Boolean, the byte,
00:50the short, the integer, the long, the float, and the double.
00:55I'll save and run the application again and there is the result.
00:59Notice that all the values are output almost exactly as they were set.
01:03The one exception is the double which had so many digits before the decimal that
01:07Java automatically translated it for me.
01:10When you output values using the out object's print or println commands, these
01:15are usually automatically translated to strings.
01:17But the same translation happens whenever you concatenate values.
01:20Let' take one of these values, the short and I am going to output the short
01:24value, concatenate it to a string.
01:26I'll use System.out.println ("The value of s is -- and then I'll use the plus
01:35operator and the value s. I'll save the changes and run the application and I
01:40get what you would expect, The value of s is 32000.
01:43Now, in some languages, it matters when you are concatenating whether the first
01:48value is a string or whether the first value is a number.
01:51In some languages, if the first value is a number, then the plus operator
01:55will be used for math, but if the first value is a string then it will be
01:59used for concatenation.
02:00So let's test that in Java.
02:02I'll take this println command and copy and paste it and I'll reverse the order.
02:06Instead of starting with the string, I'll start with the numeric value, s + "
02:11is the value of s. In some languages, this would cause an error because the
02:16first value was a number and the plus operator should be seen as a mathematical
02:20plus rather than as a string concatenation plus, but in Java, the rule is that
02:25if there is even one string involved then the whole thing will be turned into a string.
02:29I'll run the application and I'll see that that works as well.
02:33You can also combine math and string concatenation.
02:36If an expression starts with a mathematical operation, such as 2+2, the math
02:41will be executed first.
02:42The result will then be converted to a string and concatenated to the rest of the expression.
02:47If you put the math at the end of the expression though, everything will be
02:50treated as a string.
02:52Finally, complex objects are also translated to strings automatically.
02:56If you declare a string and then output a string, that's pretty simple.
03:00You are just getting the value of the string object, but what about dates.
03:04I'll create a new Date object.
03:06I'll use the Date class and a variable name of myDate = new Date and then I'll
03:12use System.out.println ("The new date is -- and then I'll output myDate.
03:21If you see any errors, that means that you have to include a special notation at
03:26the top of the screen called a package.
03:28The Date class is member of a package that has to be explicitly imported.
03:32I'll talk about class importing later, but for now, all you need to do is place
03:36the cursor after the data type Date and press Ctrl+Space.
03:41Then, choose this version of the Date class, Date in java.util, double click
03:47it and at the top of the screen, you'll see a statement added import java.util.date.
03:54That's an instruction to the compiler that says, when I refer to the Date class,
03:59this is the version I mean.
04:00Now I'll save my changes and run the application and I get a long string, the
04:05string representation of the current date and time.
04:09So how is this happening?
04:11Well, every complex class in Java has a special method called toString.
04:15Let's look at the documentation for the Date class.
04:18I'll double-click date and then go to Dynamic Help.
04:22I'll click on Javadoc for java.util. date and maximize that screen, I'll click
04:28the Method list, scroll down and here is the toString method.
04:33Every class has this toString method and the implementation of the method is
04:37going to be different from one class to another.
04:40When you pass a complex object into System.out.println or otherwise
04:45concatenate the object to an existing string, Java automatically looks for
04:49this method, toString, executes it, takes the return value, and that's what
04:55will become a part of the string.
04:57You'll see in later videos when you create your own complex classes that you
05:01can use this model pretty effectively for debugging and other tools in your application.
05:06When you create your own custom classes and you give them a toString method, you
05:10will be able to take instances of those classes, pass them into these methods
05:14that require strings and the translation will happen automatically.
05:18So that's a look at how values are translated from their native data types
05:22into strings in Java.
05:24Again, primitives translate automatically, but complex objects depend on the
05:28toString method which is implemented differently for each class.
Collapse this transcript
Creating a simple calculator application
00:00It's time to put some of what we've talked about to work in a real application.
00:04This is going to be a very tiny almost trivial application that does little
00:07bit of calculation.
00:09It will accept input from the command line and then evaluate values that the
00:13user types in as numbers and add them together, not too complicated, but it will
00:18require setting variables, converting values, and doing a few other things that
00:22I have taught how to do in this chapter.
00:24I'm working in a project named SimpleCalc that's available in the Exercise Files.
00:28The calculative class in this project has a main method that in turn makes a
00:32call to a method called getInput, the getInput method is down here, the purpose
00:37of getInput method is to allow the user to type a value in and then return it as a string.
00:43I'm not going to talk right now about the different classes that are used, the
00:46BufferedReader and the InputStreamReader, and in fact, for this lesson I'm
00:51recommending using this method as a bit of black box.
00:54Just call the method knowing you'll get back a String value and to make things
00:58less complicated I'm going to collapse the code by clicking on the little minus
01:01icon right next to the method name.
01:04And that leaves me with a very small view of my code showing the details of the main method.
01:09and the fact that there is a getInput method that returns a String.
01:12The application in its current state calls the getInput method once and returns
01:16the value as a variable called s1 and then outputs that value to the console.
01:21I'll run the application.
01:23The value I pass into the method enter a value is displayed as a prompt,
01:27I'll type in a value, some value and press Enter and that value is echoed to the console.
01:34So I know that the input method is working correctly.
01:37Now the goal of this application is to receive two numeric values, so I'm going
01:42to change the prompt on this first call to getInput and I'll change the prompt
01:45to Enter a numeric value, then I'm going to copy and paste that line of code and
01:51I'll change the variable that's being returned to s2.
01:55I don't need this output for the moment so I'm just going to commented out by
01:58pressing Ctrl+/ on Windows or Command+/ on Mac.
02:02Now the next step is to convert these Strings to numeric values, I want my two
02:06Strings to turn into two double values.
02:09So I'm going to declare a double value called d1 and I'm going to convert the
02:14String to a double value using this method of the double wrapper class,
02:19Double.parseDouble and I'll parse in s1.
02:22Then I'll do the same thing for the second value double d2=
02:27Double.parsedouble(s2).
02:30And so now I have two numeric values.
02:33Now I'm going to add the two values together, I'll create a third double value
02:38called result and now add d1+d2;
02:42Now because I cast the numeric values as doubles originally, they'll correctly
02:46add together and create a third double.
02:48And then finally, I'll uncomment this command, System.out.println and I'll
02:54change the output to "The answer is" and I'll append result.
02:59So now I'm asking the user to enter a two values both numbers as long as they
03:04can be parsed as double values, the mathematical operation should work.
03:08I'll run the application;
03:10I'll click into the console and type in an initial value of 10 and a
03:14second value of 25.5.
03:15I'm using a fractional value because I know I cast these values as doubles and
03:21they can accept that.
03:22I'll press Enter and there is the result, The answer is 35.5.Now, let's take a
03:28look at what happens if the user types in a non-numeric value, I'll click the
03:32Run button again and this time I'll type in a value of xyz.
03:37So far so good nothing bad is happened and that's because I haven't tried to
03:41parse the String as a number yet, I've just gone to the next line that asks for
03:45another String, so I'll type abc, now when I press Enter the parsing will begin
03:52and I'll get an error, because xyz can't be translated as a numeric value,
03:57specifically as a double value, I get an exception called
04:00java.lang.NumberFormatException.
04:03Now, I haven't shown you the tools you need to handle this exception yet, so for
04:07now this simple calculative will only work if the user types in correct values,
04:12that is String values that can be parsed and turned into numbers without
04:17creating exceptions, but if the users does what they are supposed to do
04:20directly, then the application will work.
04:22In later chapters I'll show you more about Strings and more specifically about
04:27Error Handling, so that you can easily capture this kind of problem and tell the
04:31user what kind of input you need.
Collapse this transcript
5. Exploring Syntax and Flow
Writing conditional code
00:00Java supports a number of constructs that allow you to easily control the flow
00:05of your application.
00:06Conditional Blocks, Switch Statements, Loops, and so on.
00:11I'm going to start in this chapter by showing you how to build a basic
00:14conditional statement using the keyword if.
00:17I am working in a project named Conditional that's part of the Chapter 05
00:22Exercise Files, but it just has an empty class with the basic Main method.
00:26I'll place the cursor inside the Main method and I am going to start by
00:30declaring an integer variable.
00:32I'll give it a data type of int and a name of monthNumber and I'll set it to a
00:38value initially of 3.
00:40Now I am going to evaluate that numeric value and ask the question, does this
00:45month number fall in the range of 1 to 3.
00:48In Java the conditional blocks starts with the keyword if.
00:51You then place a Boolean condition that is a condition that evaluates to true or
00:56false inside of set of parenthesis, and then within the pair of braces, you put
01:01in the code you want to execute if the condition is true.
01:05Now rather than hand coding all that, Eclipse will the model the code for you.
01:09After typing the word if, without any spaces after it press Ctrl+Spacebar and
01:15you will get a list of available code templates.
01:17Choose the first item in the list, if statement, an Eclipse fills out the rest
01:22of the conditional block, the required parenthesis around the Boolean condition
01:27and the braces in which you will place the executable code.
01:30Now the question I want to ask is does the month number fall between 1 and 3.
01:34So I am going to put in a complex condition here.
01:37I'll start off with a Boolean expression of monthNumber>=1, and then I'll use
01:43the double ampersand which is the conditional end and I'll complete the
01:47expression with monthNumber <=3
01:51Notice that as I type there is a little rectangle that's wrapping the condition.
01:56When I am done typing in the condition I can press the tab key and the cursor
02:00will drop between the braces and I can start writing the executable code.
02:05Within the if clause, I'll use System.out.println.
02:10and I'll out put the string "You're in Quarter 1."
02:13I'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:20Now once you've used an if clause, you can also use one or more else-ifs.
02:26The structure of else-if is the same as an if, but it can only follow in an initial if.
02:31So I am going to make a copy of this code block and I'll paste it in to place,
02:36and I'll prefix the next one with else.
02:39I'll change the numbers that I am evaluating to 4 and 6 and I'll change the
02:46Quarter output to Quarter 2.
02:47I'll Run the code again and I am in still Quarter 1, but then I'll change the
02:53month number at the top of the code to month number 5 and Run it again, and I am
02:58told you are in Quarter 2.
03:00Now again, you can have as many else- ifs as you want, and then optionally you
03:04can have an else, which is the catcher, the code that will execute if none of
03:07the previous conditions are true.
03:09The else looks like this, it doesn't take any parenthesis or conditions, but it
03:14does take its own code block, and here I'll output of string saying, "You are
03:18not in the first half of the year!"
03:19Now that code is getting a little wide, so let me maximize my code editor and we
03:24can see all three conditions.
03:26One for Quarter 1, one for Quarter 2, and finally, one for all of the other
03:31possible numeric values.
03:33I'll Save and Run the application and I am still in Quarter 2, but now I'll
03:38change the monthNumber variable to say number 8 for August and Run again and I
03:44get the output "You're not in the first half of the year!"
03:47So that's basically the structure of an if statement.
03:49Now when you are comparing values and you are working with primitive data types,
03:53you can use these mathematically quality operators >=, <= and so on.
04:00But as I previously described, if you are working with strings, you have to use
04:05methods of the String class to do comparisons.
04:08Let's create another class.
04:10I'll go to my package explorer to the default package, I'll right click and
04:15create a New class, and I'll name this CompareStrings.
04:19It's going to be its own little application, so I'll check the main method and click finish.
04:24I am going to get ride of all these extra comments that Eclipse puts in, and now
04:29within the Main method I'll declare a String variable named month and I'll give
04:34it an initial value of "February".
04:37Now I am going to compare that string value to another string.
04:41So, once again I'll put in an if clause typing the word if and pressing
04:45control space and pressing Enter or Return and then I'll look for the string
04:49February like this.
04:51if month.equals("February") then I say, System.out.println ("It's the second month!").
05:01I'll Save and Run this application and I get the output.
05:04The mechanism of comparing values will shift from one data type to another.
05:09For primitive values, you can use the mathematical equality operators.
05:14For Strings you have to use methods of the String class like equals or contains,
05:18but the structure of the if, else-if, and else statements will stay the same.
05:24Regardless of the data type that you are comparing, you can use the if, else-if,
05:28and else clauses to determine whether you would want to execute particular code,
05:32all depending on the current condition.
Collapse this transcript
Using the switch statement
00:00There are many times in applications where you have a variable and you want to
00:04check that variable against a set of finite values.
00:08You could model this code using an if statement, and a whole set of else-ifs or
00:12you could do it a little more elegantly with a switch.
00:15I'll show you how to use a switch in Java in this project, Switch, which you can
00:19find in Chapter 5 of the Exercise Files.
00:22The project has a few different classes, I'm working with the SwitchWithInts,
00:27this application already has the getInput method that I've used in a previous
00:30video, it accepts a value typed in at the command line and returns a String.
00:35I'll start in this application by receiving a value and converting it to an integer.
00:40I'll place the cursor inside the main method and declare a String named input,
00:45then I'll fill in its value by calling the getInput method, I'll pass a prompt
00:50into the getInput method of Enter a number between 1 and 12:
00:56Next I'll convert the String to an integer, I'll declare an int variable called
01:01month and I'll convert it using the Integer class's parseInt (input) method,
01:06I'll pass in the input, and now I should have an integer to work with.
01:12Now, I'm doing this because in Java up through version 6.0 you can use the
01:18switch statement only with integers, shorts, bytes, and a special class called Enums.
01:24In Java 7.0 you can actually use switches with strings, but I have my copy
01:28of Eclipse setup on Java 6.0 right now, so I'll stick with what works with that version.
01:34The next step is to create the structure of a switch statement, just as with if
01:39statement Eclipse will help you, type the word switch and press Ctrl+Space and
01:44then press Enter or Return to choose the first item in the list and that creates
01:48the basic structure.
01:49The switch syntax looks like this, after the keyword switch you put in a pair of
01:53parenthesis and then you pass in the variable that you're evaluating.
01:58I'm evaluating the variable month.
02:00Next you have one or more case statements, each case statement takes a value,
02:06the value must be an integer or an enumeration or Enum, I'll describe those
02:10later, but for now, I'm going to use the literal value of 1.
02:15Then after the case statement, but before the word break, you put in your
02:19executable code, this code will only execute if the value in the case statement
02:24matches the variable in the switch command.
02:27I'll output a bit of text System.out.println, and I will output ("The month is January");
02:35so I making an equivalence between the number 1 and the month January.
02:39Now, I'm going to copy and paste this case statement, including the three lines
02:43from case to break, I'll copy and then paste twice, close up the code a bit,
02:48I'll change the values I'm evaluating to 2 and 3, and I'll change their
02:53equivalent months to February and March.
02:57So my application is now at a point where it should work correctly.
03:01I'll run the application, in the console view I'll click in and then type the
03:06number 1, and I get the month as January.
03:08I'll run it again and type in 2 pressing Enter or Return and I get the month as February.
03:15And finally, I'll test a value that's not one of those numbers like 6, and press
03:21Enter or Return and nothing happens.
03:23Well, that's because I haven't filled in this bit of code, the default.
03:28The keyword default means execute this code if none of the previous cases return
03:34true, so here I'll put in System.out. println and then I'll output the String
03:40("You chose another month").
03:43I'll Run and once again I'll type in 6, and this time I get the default behavior.
03:50So that's the basic of a switch statement.
03:53Let's also talk about the break keyword.
03:55The break keyword is used to breakout of a code block in Java.
04:00Right now our code block is everything from this opening brace to this closing brace.
04:05When you say break, it means jump to the end of the code block.
04:08You need break statement in cases, because if you don't have them, the code will
04:13just keep executing throughout the rest of the switch statement.
04:16I'm going to comment out each of these break statements, so you can see the behavior.
04:20I'll place the cursor on the line and then press Ctrl+/ on Windows or Command+/
04:25on Mac, and that will add double slash comments to each of these lines.
04:29Now I'll Save my changes, Run the application, and I'll type the number 2 and I
04:35get not just the month as February, but I also get all of the other code
04:39executing for the rest of the switch statement.
04:42This code model works the same as it does in JavaScript, C++, and other C-Style languages.
04:48The rules are straight forward as soon as you get a match between the variable
04:53and the value in a case statement the code will start executing and it would
04:56keep executing for the rest of the code block.
04:59If you don't want that to happen, and you really never do, then you have to put
05:03those break statements into each case.
05:06So I'm going to get rid of those comments, all I need to do is move the
05:09cursor to each line and press Ctrl+/ or Command +/ and now the code is back in its working state.
05:16In Java, through version 6.0, you can use switch statement for integers or for a
05:22special class called Enums, and again, as I mentioned before, in Java 7.0 you
05:26can use switch statements on Strings, but I'm working in Java 6.0 here, so I'm
05:30going to stick to integers and Enums.
05:33Let's take a look at how Enums work.
05:35An Enum is short for Enumeration, it's a way of providing a set of possible
05:42values, in older version of the Java, previous to version 5.0, you had to create
05:47your own enumerations using a particular code model, but now they're native to
05:51language and have been for the last couple of versions.
05:54Here is how you create enumeration.
05:56I'll go to my default package in the project and choose New Enum.
06:00An Enum is a kind of a class, so you have a very similar wizard as for a new
06:07class, but without all the options.
06:10I'll give this Enum a type of Month, I won't use a package I'll just ignore
06:15that warning that the use of the default package is discouraged, and I'll click Finish.
06:20Now within the Enum I'm going to type in the names of the constants that I want
06:25to use, JANUARY, FEBRUARY, MARCH, notice that after I saved the file Eclipse
06:32automatically evaluates and recognizes that those are constants of the Enum
06:36class and it color codes them appropriately.
06:39Now I'll switch to the application SwitchWithEnums.java, this is a shortened
06:44version of that previous application;
06:46it has an integer variable with the value of 1.
06:49I'm going to copy out that version of the month declaration and I'm going
06:53to change it to an instance of the month class or a month Enum that looks like this.
06:58When I type in Month.Eclipse gives me a listing of the possible values and
07:04you'll see that the values that I put into the Enum class, JANUARY, FEBRUARY,
07:08and MARCH, are proposed.
07:10I'll choose FEBRUARY.
07:12Now I'm going to change my switch statement a bit, the switch statement itself
07:15stays the same, because I reused the variable name month, but now, instead of
07:20evaluating integers, I'm evaluating constants of the Enum, and it will look like
07:24this, case JANUARY, notice that within the switch statement I don't have to use
07:29the month dot prefix and I'll change the string from the month as JANUARY to
07:34("It's the first month").
07:35I'll change 2 to FEBRUARY and I'm just pressing Ctrl+Space to auto fill that
07:41value and I'll change this String to ( It's the second month) and I'll change 3
07:46to MARCH and the output String to ("It's the third month").
07:50The advantage of using an enumeration is that you can explicitly say these are
07:55the only possible values, when you say something as an integer, you're not
07:59limiting yourself to 1 through 12, you have literally millions of possibilities.
08:04The advantage of the Enum is that you're limiting the possibilities, and making
08:07it very clear what's possible in this situation.
08:09So now I'll Run the application and I get (It's the second month).
08:14I'll talk more about enumeration at a later point of the course, but you can see
08:18how useful they might be for various situations in your applications.
08:21Finally, I'll show you what the code would look like if Strings were supported
08:25in the switch statement.
08:27As I've mentioned, I can't do this right now, because I'm working in Java 6.0,
08:31but if you're working in Java 7.0, one of the improvements to the language is
08:35the ability to use Strings in switch statement, and this is what the code would look like.
08:39The purpose of switch statement is to make conditional logic a little more
08:43elegant and to prevent the need from multiple else-if statements that make the
08:48code harder to read.
Collapse this transcript
Repeating code blocks with loops
00:00The Java language includes a number of syntax styles that allow you to loop
00:04through the contents of arrays and other types of data collections.
00:09I'll demonstrate four approaches to looping in this project named Loops.
00:13The main class in this project has a set of code that's commented out currently,
00:17it declares a static variable, an array of strings called months.
00:22I'm going to loop through this data and output these strings a number of times
00:25using a different syntax style each time.
00:28I'll start by uncommenting this code.
00:31I'll select the commented code and then press Ctrl+/ on Windows or Command+/ on
00:36Mac and that removes the double slash comments at the beginnings of the lines.
00:40Then I'll place the cursor inside the main method.
00:43The first type of loop I'll show you uses a numeric counter variable.
00:48It's a conventional for loop and the syntax looks exactly the same as it would
00:52in JavaScript and other similar languages.
00:56I'll start by typing in the word for, and then pressing Ctrl+Space.
01:01Eclipse gives me a number of choices and I'll choose the first one, for
01:05iterate over array.
01:07This sort of loop uses a temporary variable, sometimes called a counter variable.
01:13When you generate the code using Eclipse, it will name the variable i for
01:17integer and it will datatype it as an int.
01:20Now if you're doing with a fairly small amount of data, you could change the
01:24data type to a short or even a byte, but typically ints are used in this case.
01:29When you're looping through an array, you should set the initial value of the
01:32counter variable i as 0.
01:34This is because in Java arrays are 0-based.
01:38The first item is item 0.
01:40The second is item 1 and so on.
01:42Then in order to make sure that you hit every item in the array, you add a comparison.
01:48You look at the counter variable I, and you compare it to the length of the
01:53array, as long as i is less than the length, you'll execute any code within the for-loop.
01:58But when i matches or exceeds the length, you'll stop, and again, that's because
02:03of the 0-based array.
02:06Say you have an array of 10 items, if the length is 10 and i starts at 0, then
02:11you can keep executing code as long as i is less than 10.
02:15When it actually is 10, it's exceeded the available items in the array.
02:19The third part of the for construct is the increment.
02:23Most commonly, you'll see this, i++, meaning, increment the value by 1, but you
02:28can put in any operation you want here.
02:30You could use i--, you could say i+ = 5 and then you would be stepping by 5, and so on.
02:37So now I'll place the cursor inside the for-loop, and put in System.out.println
02:43and I'm ready to output something.
02:45Now when Eclipse generated the code, it thought I might want to output the
02:49values from args, but instead I'm going to output the values for months and
02:54that's the array that I declared at the top.
02:56And in the print line command I'll output months, open bracket, i, closed bracket, and now I'm going to be
03:03outputting the string at that position of the array.
03:06I'll Save and Run the code and there is the result.
03:10Now to make this a little bit easier to see, I'm going to detach the console
03:13right-click and choose Detached, move it up onto the screen and expand it, and
03:17now I have a lot more room to see the output from my application.
03:21So that's a for loop with the counter variable.
03:23Here's another approach to using a for loop.
03:26This is called a for-each, but unlike some C Style languages, you don't
03:30actually use the word each.
03:32Here is how it actually looks.
03:34Once again I'll type in the word for, and press Ctrl+Space and I'll for-each
03:39from the list of choices and here's how Eclipse models it.
03:42Within the for-loop it declares a variable by default of type string, and
03:47it gives it a name.
03:48I'm going to change the name from string to month and then it asks what array or
03:53collection you want to loop through.
03:55I'm going to be looping through months.
03:57So in English this would be read as, for-each month in the month's array, but
04:03you declared in Java using a data type variable before the colon and the array
04:08or collection you are looping through after the colon.
04:11Now I can refer directly to the variable month.
04:14So I am going to go make a copy of this code, System.out.println, I'll paste
04:19it in, but now I don't need refer to the collection anymore, I'm already doing
04:23the iteration, I'll just refer to the variable that's created temporarily each
04:27time through the loop.
04:28I'll go up to my original for loop and comment it out and I'll Save and Run the
04:33application, and once again there is my output.
04:37In most cases with the arrays, you can use either of these two approaches.
04:41The only real advantage to using the counter variable, as opposed to the
04:45for-each syntax is that you're creating new counter variables, rather
04:49than complex objects.
04:51Whereas, with the for-each, particularly with the strings and other complex
04:54objects, you are creating a new object on each time through the loop.
04:57In most environments it really won't matter, and you should use the syntax that
05:01you're most comfortable with.
05:04I'll comment this version out, and now we'll move to the while loop.
05:08There are two forms of the while loop, the while loop where you put the
05:12condition at the front and the while loop where you put the condition at the back.
05:15Before you create a while loop, you should declare a variable and give it an
05:20initial value, unlike the for-construct, the while construct does not do the
05:25variable tracking for you.
05:26So I'll create a variable called counter, and set it to a value of 0.
05:31Now I'll type in the word of while and I'll press Ctrl+Space and I'll choose
05:36while loop with condition.
05:38The while loop with condition takes a look at a Boolean expression and asks
05:43should I keep on looping?
05:44I'm going to set my condition as counter <months.length, and then I'll move the
05:49cursor into the while loop, I'll paste in that code, and I'll change the name of
05:54the variable I'm looking at from I, to counter, because that's what I declared
05:58it as earlier, but again, the while loop isn't going to increment that value for
06:03me, I have to do it myself.
06:06So I'll place the cursor after the print line command and increment the
06:10value with counter++;
06:12I'll save and run the code.
06:14And once again it does exactly the same thing as the for-loops, but with a
06:18slightly different syntax.
06:20Finally, there is the do-while loop.
06:22For the do-while loop you place the condition at the end of the loop.
06:26I'm going to make a copy of this code and I'll paste it down at the bottom.
06:32I'll comment out the original and now let's create a do-loop.
06:36I'll take this while command and I'll move it after the code block.
06:40Then I'll the place the cursor at the beginning of the code block and put in the
06:44word do, and after the while command, I'll finish with a semicolon.
06:49So now I'm saying start by outputting the value and then increment the value and
06:55then do the evaluation rather than doing the evaluation at the beginning.
06:59Take a look at what happens.
07:01It still works exactly the same.
07:03So these are the four possible syntax styles that you can use for looping
07:07through arrays and other collections.
07:10You can use the counter for loops, you can use for-each syntax, you can use a
07:14simple while-loop or you can use a do-while loop.
07:19In many cases it's just a matter of program or preference, which syntax you
07:23like, or are most comfortable with.
07:25You will find that there are differences in what problems you can solve between
07:29say a while and do-while, but for the most part it's your choice.
Collapse this transcript
Creating reusable code with methods
00:00Nearly all programming languages support the concept of a function.
00:04A function is a set of code that's wrapped up and then given a name, so that it
00:08can be called easily from other parts of the application.
00:11In Java, we have special name for a function called a method.
00:15The term method comes from object- oriented vocabulary and refers to a function
00:20that's a member of a class.
00:22There are some programming languages in which you can create global functions.
00:26Functions that are available to the entire execution environment without having
00:29to say where they come from.
00:31That's not the case in Java.
00:33In Java, every function is a member of a class, and so we always use the term method.
00:39I have described the use of the main method in applications that run from the console.
00:44As you start up an application from the command line, the Java Virtual Machine
00:47looks for a method called main, which has these characteristics, public, static,
00:53and void, and accepts an argument that's an array of strings.
00:57You can create as many of your own custom methods as you want to, but again,
01:01every method must be defined within a class.
01:05I am going to define my own custom method and describe each part of the
01:08declaration as I go along.
01:09When you declare a method, the first thing you typically provide is called
01:13the access modifier.
01:15You can use one of three terms, public, private, or protected.
01:19Public means that the method is available to the entire application or at least
01:23to any part of the application that can see the class itself.
01:26So if the class is public and the method is public, then it can be called from anywhere.
01:30Private is the opposite.
01:32The method is only available to code within this class.
01:36Protected has to do with inheritance.
01:38A protected method is available to the current class and to any of its sub classes.
01:42And there is one other kind of access, which happens when you don't declare an
01:46access modifier at all.
01:47It is sometimes called protected package, and it means that a method is
01:52available to the current class and to any other classes in the same package
01:56or group of classes.
01:58I recommend always setting access modifiers though, because it makes your
02:01code easier to read.
02:03The next characteristic of a method is whether it's static or not.
02:07If you want the method to be static, you put in the word static.
02:10And if you don't, you don't.
02:11When do you want a method to be static?
02:13Well, the term static means that the method is something we call a class method,
02:17as opposed to an instance method.
02:19A class method is called directly from the class definition, whereas an instance
02:24method is called from an instance of the class or an object.
02:27If you are not sure whether to make a method static or not, try not putting in,
02:32and see if you can call the method.
02:33For example, in order to call a method from the main method, which is static,
02:37the called method must be static as well.
02:40Static methods can call static methods, instance methods can call instance
02:43methods, without having a say where they are coming from.
02:46But for a static method to call a non static method, it must create an
02:50instance of the object.
02:51I want to call this method every easily, so I'll make it static and then I'll be
02:55able to call it from the static main method.
02:57Next, you declare the return type.
03:00The term void means I am not returning anything.
03:03Unlike some languages, Java requires a declared return type.
03:08Now you type in the name of the method you want to create.
03:10I'll name my method doSomething, it's important to follow the right conventions
03:14when you name your methods and variables.
03:16You follow the same convention as for variables.
03:19The initial character must be lowercase or other java developers will think
03:23you don't know what you are doing, and it must be an alphabetical character, not numeric.
03:27You can also use underscores, but that's fairly in frequent.
03:30The rest of the method name can use camel case, such as I am doing here which
03:34means using uppercase characters to make the string more readable.
03:37At the end of the method name you always add opening and closing parenthesis.
03:41This is where you would declare arguments that can passed into the function or method.
03:46After the parenthesis, you add up pair of braces.
03:48In Eclipse, if you type in the opening brace and press Enter or Return, the
03:52closing brace will be created for you.
03:55Now I've declared this method as void, meaning I am not going to return
03:58anything, but I can do something within the method, and I'll output something to
04:02the console saying ("This method has been called.")
04:07Now I'll go to the main method and I'll call the new custom method.
04:10I'll type do and then press Ctrl+Space to see what's available and there is my new method.
04:16Eclipse is constantly scanning your code to determine what's available to the
04:20code and if it can't call a particular method, say because you are in a static
04:24context and the method you are trying to call isn't static, it won't show it in
04:27the list of choices.
04:29I'll press Enter or Return to choose the method and add the semicolon at the
04:32end of the statement, and I'll Save and Run the application, and there is the output.
04:37Now it's very common to create a bunch of code in a general context and then
04:42want to be able to wrap that up and turn it into its own method later on.
04:45We call this sort of changed to your code, refactoring, and it is something that
04:49Eclipse can help you with.
04:51I am going to create a little bit of code here.
04:53I'll create an int variable called top and give it a value of 10, and then I'll add for-loop.
04:58I'll type '-for, press Ctrl+Space and then Enter or Return to iterate over the array.
05:04I'll press tab and I'll change the value that I am iterating on from
05:08args.length to top and then within the for-loop output System.out.println, and
05:16then the value is, and then I'll append i. I'll Save and Run the application
05:22and there is my finished code.
05:24Okay, let's take this code and wrap it up in its own method.
05:28I am going to select the code that I want to put in to its own method, and then
05:31I'll go to the menu and choose Refractor>Extract Method.
05:36The Extract Method dialog asks me what I'd like to name this new method and
05:39I'll call it loopMe.
05:41It will propose what we call a method signature.
05:44The combination of the characteristics private, static and void, and the method name.
05:50I can change my access modifier up here or I can accept the proposal of private.
05:55I'll accept the proposal.
05:57I'll click OK and Eclipse takes all of that code and moves it off into its
06:01own separate method.
06:03It also adds a call to the method right here.
06:06So I'll Save the changes and Run the application again, and I'll see that the
06:10application is doing exactly the same thing as before, but now I have wrapped
06:15up all that custom code into its own method, so it can be called many times in the future.
06:20So that's a look at the basic of creating methods.
06:22Now in future videos I'll show you how to create methods that accept arguments
06:27or parameters and also methods that know how to return values.
Collapse this transcript
Declaring methods with arguments
00:00When you declare own custom methods in your Java code, you can declare them with
00:05arguments, parameters, or values that they can receive and these methods can
00:09return values as well.
00:11I am starting in a version of my calculator application that's in a project
00:15called MethodWithArgs.
00:17This application already has a custom method that I previously used in other exercises.
00:22The name of the method is getInput.
00:25It's designed to receive a single argument, a string with a name of prompt and
00:30it's designed to return a string as well.
00:32All of the complex code is encapsulated within the method.
00:36So, when I call the method, all I need to do is pass the name and a value that I
00:41want to display on the screen, the prompt.
00:43Now you can create your own custom methods incredibly easily in Eclipse.
00:47Let's say that you have some custom code and it's either 3 line or 10 lines or
00:51100 lines of code, and you want to take that code out of the main method and
00:55make it its own custom method.
00:57Eclipse calls this extracting a method and here is how you do it.
01:01I am going to take these three lines of code, I am declaring two double values
01:05that are being parsed from strings.
01:07And then I am adding the two values together.
01:10I would like to take this bit of code and make it its own method.
01:13So I'll select those three lines of code and then I'll right click in the selected area.
01:18I'll choose Refactor, Extract Method.
01:21Eclipse asks for the new Method name, I'll call it addTwoValues.
01:26Notice the parameters are set as Strings, that's correct, and also, Eclipse is
01:31smart enough to know that if my final statement is doing a calculation, then I'm
01:35probably going to want to return that value from the method.
01:39So it says, I'm going to return a double value, I'll click OK and Eclipse
01:44refactors the code for me.
01:45The new code is a single line that says create a double value named result,
01:50which is calculated by calling the new addTwoValues method and it's passing
01:54in the two strings.
01:56And here is the new method, it's declared as private, static, and double,
02:00because it's private and static, it can be called from within the Main method,
02:04and because it declares double as the return type, it knows that it's going to
02:07return that calculated value.
02:09Here is all the code that I extracted, and here is the code that returns the result.
02:14The keyword return means here is the value that I'm returning from this method
02:18and the data that you pass back must match the data type that you declare here.
02:23I'll Save my changes and Run the application, I'm asked for my values and I'll
02:27type in 5 and 10 and I get back 15.
02:31So I know that the code is working.
02:33It's also possible to declare methods that receive variable numbers of
02:37arguments, as long as all those arguments are of the same data type.
02:41Here is an example, I moved down to the bottom of the application and I'll
02:45create a new private static method and I'm going to set the return data type as
02:49double, just as before.
02:51I'm going to call this method though addMultipleValues.
02:55I'll start with no arguments, but then I'm going to place the cursor inside the
02:59parentheses and I'm going to tell Java, you can accept any number of arguments
03:04as long as they're all doubles, that is, as long as they are all numeric
03:08primitives they can be translated as double.
03:10Here is the syntax:
03:12double space dot, dot, dot space, and then the variable name.
03:16The data type works as it does for all arguments, but the dot, dot, dot means
03:21treat this value as an array.
03:23Right now, I'm seeing a little bit of error information and that's because I
03:27haven't returned a value yet.
03:29So now I just need to fill in the implementation of the method.
03:32I'll expand the editor so we can see more of the code, and within the method I'm
03:36going to start by declaring a double value of result and set it as 0d, meaning
03:42the double version of zero.
03:44Now I'm going to loop through those values, because of the dot, dot, dot in the
03:48middle of the declaration, values is passed in as an array, and I'll loop
03:52through using a for-loop, I'll type for press Ctrl+Space and I'll use a for-each loop.
03:58Eclipse tells me it's going to create a new double value named d, each
04:02time through the loop, and this is the collection or array it's looping through, values.
04:07Within the loop I'll add the value to the result using the += operator result +=
04:13d and finally after the loop I'll return the result.
04:19So, there is my completed method accepting variable numbers of double values.
04:23I'll go back to the top to the Main method, and I'm going to add a little bit
04:28of code down here, I'll say double resultOfMultiple = addMultiple and I'll pass in 1, 2, 3, 4, 5.
04:39And again, I can pass in as many values as I want, as long as they can all be
04:43easily converted into double values.
04:45Then I'll output the result saying (" The answer from multiple values is")
04:50and then the answer.
04:54I'll run the application I still have to go through the inputs for the original
04:58calculation, but then I get the answer from the multiple values also.
05:02Now it just so happens that I got back the same values, so let's try running
05:06the application again.
05:08This time I'll add 5 and 5 together and I get back 10 for the first answer, but
05:1315 for the second, because that's the result of 1+2+3+4+5.So this is how you
05:19declare your own methods with arguments.
05:22Java requires arguments to be declared if you haven't declared them you
05:26can't pass them in and if you do declare them you have to pass them in, it's very strict.
05:31But you do have the option of using the variable argument syntax to allow
05:36yourself 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:01The Java programming language allows you to create methods that share the same
00:05name, but have different signatures.
00:07A method signature is the unique combination of keywords and arguments that
00:13the method receives.
00:14For example, the standard main method receives an argument which is an array of strings.
00:19You can create your own custom methods in your class and where necessary, you
00:23can create multiple methods that share the same name as long as they have
00:27different signatures.
00:28The Java Virtual Machine determines at runtime which version of a method it
00:32should run, depending on what arguments are passed to it.
00:35Let's create a few very simple methods.
00:38I'm working in a beginning main class in the project MethodOverloading.
00:42I'll place the cursor after the static void main method and I'll create a new
00:47method using private static, I'll set the methods return value to int and I'll
00:53name the method addValues.
00:55For this first version of the method I'll receive two arguments, and they'll
00:59both be data typed as integers.
01:01I'll name the first one int1, and the second one int2.
01:06The body of the method will add up these two values and return the result.
01:10I'll do it on a single statement.
01:12return int1 + int2.
01:16In the main method I'll declare two starting variables;
01:18I'll declare them both as integers.
01:21I'll name the first one value1 and I'll set it to a value of 5.
01:25And I'll create the second one as value2 and set it to a value of 10.
01:29I'll declare an integer result variable and get its value from addValues and
01:35I'll pass in value1 and value2 and I'll output the result using
01:39System.out.println, (The result is" and then + result) I'll Save and Run the
01:49application and everything is fine. The result is 15.
01:53Now I'm going to add two more versions of this method, I'll copy the existing
01:58version and I'll paste it in, making sure I do this inside the body of the class
02:02and notice right now that I'm getting warnings that I have duplicate methods.
02:06The reason they are duplicate is not just because of the name, but also because
02:10they receive the same number and data types of arguments.
02:13So unlike other languages like JavaScript or ActionScript, I don't need to
02:17rename the second version of the method.
02:20I can just change the method signature.
02:21I have this method receive a third argument.
02:25The data type again will be int and the name will be int3, and I'll change the
02:29return statement to add that variable as well.
02:32As soon as I make the change, all the errors go away.
02:34I'm still left with a warning that I have a method that's not currently being called.
02:39But I'll fix that.
02:40I'll go back to my main method and create a third value and I'll set it to 15
02:45and then I'll change the way I'm calling the method and I'll pass in value3.
02:49I'll Save the change and Run the application and now I get the result as 30.
02:54Clearly I'm now running the second version of the method, so you can have
02:58more than one method of the same name as long as they have different numbers of arguments.
03:02But you can also distinguish methods from each other by the data types of the arguments.
03:07I'll create one more version of the add values method.
03:10My code is getting a little longer now, so I'll maximize my editor and move the
03:14cursor under all the other methods and I'll create another private, static and
03:19returns an int, and once again it will have the name addValues.
03:22This version of the method will have two arguments but they'll both be strings,
03:27and I'll call them val1 and val2.
03:30Now in order to add these values together I need to convert them to integers, so
03:34within the method I'll declare two integer variables.
03:37The first one will be called value1 and I'll set its value using
03:41integer.parseInt, and I'll pass in val1, and then I'll make a copy of that line,
03:47I'll change the second version to create a variable called value2, and it will
03:51get its value from val2, and then I'll do a return statement and I'll add
03:56together value1 and value2.
03:59So now I have three versions of the method, addValues with 2 integers, addValues
04:04with 3 integers and addValues with two strings.
04:07I'll go back up to the code and I'll create a couple of new variables, the first
04:11one will be a string and it will be named string1, and I'll give it a value of
04:1610, but because it's a string it has to wrapped in double quotes.
04:20I'll set string2 to a value of 25, then I'll create a variable called result2,
04:27and I'll get its values from the addValues method.
04:30And notice when I press Ctrl+Space Eclipse shows me all the different versions
04:34of the method that are available.
04:36The version with the two integers, the version with two strings and the version
04:40with the three ints, I'll choose the version with the two strings.
04:44and I'll pass in string1 and string2.
04:48I'll make a copy of my println command and paste it down here, and I'll output
04:54the value of result2.
04:56I'll run the application and the second version is clearly calling the version
05:00that receives the strings.
05:02So this sort of coding is called method overloading.
05:05When you overload a method, you are reusing the same method name, but you're
05:09creating alternative signatures.
05:11This is a good coding strategy in Java to handle situations where in one
05:15circumstance you have a certain set of variables, in another circumstance you
05:18got another set and where the data types can differ as well.
05:22By simply reusing the method names, but having distinct method signatures, it
05:27makes your coding much more flexible.
05:29And again, this is something that Java does that other languages in the C family might not.
05:34JavaScript and ActionScript for example, don't allow method overloading.
05:38In those languages each method name can only be used once, they have other
05:42strategies such as the ability to receive variable numbers of parameters in a
05:47method, but this capability of Java can be valuable to your application design.
Collapse this transcript
Passing arguments by reference or by value
00:00One of the questions you have to answer when you learn a new programming
00:03language is whether arguments passed into function are being passed by copy or by reference?
00:10Let's define these terms, when you pass arguments by copy that means that you're
00:15passing a variable in as an argument to the function or method.
00:19And within the function there is a new copy of that value, that is the value
00:23outside the function and the value inside the function are separated and any
00:27changes you make inside the function, won't be reflected in the original value.
00:32When you pass by reference, the variable outside the function and the variable
00:36inside the function are the same variable, and any changes that you make
00:40inside the function would be reflected in the original value, once the
00:44function is completed.
00:46In Java you always are passing arguments by copy;
00:49that is you're always creating a new instance of the value inside the function.
00:53But there are certain behaviors that can make you think you're passing by reference.
00:57I'm going to show you three scenarios and explain how each of them proves the
01:01point that arguments are passed by copy.
01:04Let's take the simplest scenario, passing primitive values.
01:07When you pass a primitive value into a function, a copy of the original value is
01:12made and any changes inside the function won't be reflected in the original.
01:16Here is a bit of code, a function named incrementValue, it receives an argument
01:21data typed as an int, within the function it increments the value by 1 and
01:25outputs the new value.
01:27Now when I call the function I am starting off with an original value, an int of
01:3110, and outputting that value and that will clearly output the value of 10.
01:36Then I call increment value and that will obviously output a value of 11, but
01:41what will be the final line of code output?
01:43Will it be 10 or 11?
01:45Well, because we are making a copy inside the function and not referencing the
01:48original, you'll see a value of 10 in the final output.
01:52That is to say the original value did not change.
01:56With primitives it's very easy to see that you're passing parameters by copy.
02:01Now you'll hear some Java developers say that when you pass primitives,
02:05you're making copies, but when you pass complex objects, you're actually
02:09passing by reference.
02:11That's not the case.
02:12You're still passing by copy, but references to values inside the complex object
02:17are parts of both versions of the variable, both the original and the version
02:21inside the function.
02:23Let's take look at an example using an array.
02:26In this version of the increment value function, I'm receiving an array of integer values.
02:31Within the function I'm incrementing the first item in the array by 1 and then
02:36I'm outputting that value.
02:37In the calling code I am starting off with an array of 3 values 10, 20 and
02:4130, then I am outputting the value of the first item in the array, once again outputting 10.
02:47I'm calling the function and then outputting the original after.
02:51This time the behavior will be different than in the first scenario with a
02:54simple primitive, the original value is 10, inside the function it's 11, but the
02:59original value after is 11.
03:02Well, if we were passing by copy, what's going on?
03:05Here is a good way to visualize it.
03:07The variables inside a complex object are references, but when you pass the
03:11complex object to a function, you're making a copy of the original object.
03:15But both the original object and the new object are pointing to the same values internally.
03:21A good way to say it is that a reference variable points to a location in memory
03:26and when you pass a variable to the function, a new reference is always created,
03:29but the original value is still in the same place.
03:32Let's once again take this integer array named original.
03:36It has three values of 10, 20 and 30.
03:38Let's visualize these values as locations in memory.
03:42In the original array, item 1 pointed to this location in memory, when we take
03:47that array and we pass it to a function, we're making a copy of the array, but
03:52the internal references are pointing to the same place.
03:55So our copy of the array inside the function is still pointing to those
03:59locations in memory, those values of 10, 20 and 30.
04:03So this is why it can look like complex objects are being passed by reference.
04:07The complex objects themselves are being copied, but the internal references
04:11are being retained.
04:13Finally, let's look at a scenario with strings.
04:16I've said many times that strings are complex objects, that they contain an
04:20array of char or character values.
04:23But I've also said that strings are immutable, once you create a string, you
04:28can't change its value.
04:30It may appear that you're changing its value, but you are actually creating a new string.
04:34Let's see what happens when you pass a string as a parameter.
04:38I've created a method named changeString, which accepts a string argument.
04:42Within the function I set its value to a string of new, and output that value.
04:47When I call the code, I start off with an original string, I output its value, I
04:51call the method and I output the original value again.
04:55With strings you'll see that you're always passing by copy, and the new copy
04:59can't reference the internal characters, because strings are immutable, they
05:03can't change once they're declared.
05:05And so you can't reach back and change that original value, the result with a
05:09string will look like a primitive.
05:11The original will say whatever it did, inside the function it will have that
05:15value, but the original value will remain untouched.
05:19As long as you remember that in Java you're always passing parameters by copy.
05:24But with complex objects other than strings, the internal references can be retained;
05:29you'll see that the behavior is completely consistent across the entire language.
Collapse this transcript
Creating a more complex calculator application
00:00If you've been following along through the entire course, you've just learned
00:03how to build your own methods, how to encapsulate functionality inside methods
00:08that are parts of classes.
00:10I'm going to use these tools to expand on the example of the calculator
00:14application that I showed you how to build in an earlier chapter.
00:18I've opened up a version of the calculator that currently only adds data together.
00:22It accepts two values from the command line through two calls to the getInput
00:26method, converts those values to double values, and then adds them together.
00:30We're going to add functionality to the calculator now, so that it can not only
00:34add but can also subtract, multiply and divide.
00:37The first step is to convert these three lines of code into their own method.
00:42I'll select those three lines and right click, then go to Refactor, Extract Method.
00:47I'm asked for the new Method name and I'll call it addValues.
00:52I've selected this option, Declare thrown runtime exceptions.
00:56I'll described runtime exceptions in more detail later in the course.
01:00But for now what you need to know is that when you convert a value using a
01:04parsing function, if the value can't be converted, an exception will be thrown.
01:08When an exception is thrown, you get an instance of a particular class, in this
01:12case a class named NumberFormatException.
01:15And it's good practice in Java to declare those exceptions, so that they can be
01:19easily handled later on in the code.
01:22I'll click OK and that result in extracting the code into the addValues method.
01:27I'll Save and Run the application to make sure it's still working the way I want to.
01:30I'll add together values of 5 and 10 and get 15, so all is good.
01:35Now it's time to ask the user what operation they want to do.
01:38Instead of just assuming they're going to add the values, we'll let them enter a
01:42numeric selector, one for addition, two for subtraction and so on.
01:47I'll get another input value, I'll declare a variable named String and I'll name
01:51it op for operation.
01:53I'll call getInput and I'll set the prompt like this, Enter 1=Add, 2=Subtract,
02:003=Multiply, and 4=Divide.
02:05Now the code is getting little wide, so I'll double click to expand my editor
02:09and we can see all the code on that line now.
02:12The next step will be to convert that op value to an integer so that I can
02:16process it in a switch statement.
02:18I'll declare an int named opInt for operation as an integer, and I'll convert it
02:24using this code, Integer.parseInt, I'll parse in op, and now I have an integer
02:30which indicates what the user wants to do.
02:32Now, I'm going to examine that integer value in a switch statement.
02:36I'll look for the values 1, 2, 3 and 4 and then execute the requested operation.
02:40I'll type in the word switch;
02:42I'll press Ctrl+Space and choose switch case statement.
02:45I'll set the key I'm examining to opInt and I'll set the first case
02:50statement value to 1.
02:52Then I'll take this command, which is adding the values together, and I'll cut
02:56and paste it into the case statement.
02:58So I'm saying if the user chose 1, I'm adding the values together.
03:02Now I'm going to select the entire case statement, I'll copy those to the
03:06clipboard and I'll paste them in three times.
03:09I'm just going to add and subtract a little bit of white space, so this is a
03:13little easier to read.
03:14Now I'll take the three new cases and I'll change what they do.
03:18I'll change the values I'm looking for to 2, 3 and 4.
03:23And I'll change the methods that I'm calling, so that instead of always calling
03:26addValues, I can also call subtractValues, multiplyValues and divideValues.
03:33I'll save my changes and show you that there are some errors showing up.
03:38I will move the cursor over the error marker and the one I'm looking for is the
03:42one that says Duplicate local variable result, this variable is being declared
03:47four times in the same code block, and that breaks the rule of Java.
03:51Each variable can be declared only once within a particular code block, a code
03:55block being delimited by the curly braces.
03:58When you have this kind of situation, the solution is to move the declaration of
04:02the variable outside of the code block and then simply address the variable
04:06within the code block.
04:07So I'm going to take this code, double result, and I'll copy it to the
04:11clipboard, I'll move the cursor above the switch statement and paste it in, and
04:16I'll finish the declaration with the semicolon.
04:18Then I'll move down to the switch statement and I'll remove the data type
04:22declarations from each of the four cases, because the variable has already been
04:26declared at this point, now all I need to do is address the variable.
04:30I'll save my changes and see that I still have some errors.
04:34The next error tells me that the subtractValues method is undefined and that's true.
04:39I've only created a method so far called addValues.
04:42Now I could go and explicitly type out a new method or I could let Eclipse do it for me.
04:47So to let Eclipse do the work, I'll move the cursor over one of the method
04:51names that's undefined and a little window pops-up and says, there's a quick
04:55fix available, do I want to create a method named subtractValues that accepts
04:59two string arguments?
05:00Well, that's exactly what I want to do.
05:02So I'll click the link, and then I'll scroll down a bit and I'll see that
05:05Eclipse has generated that method for me.
05:08I'll go back up to the case statements and do the same thing for multiply
05:12values and divide values.
05:14You can see how much time Eclipse is saving me by generating the method signatures.
05:18I'm going to close-up this code a little bit, and then I'll move down to my new
05:22methods, divide, multiply and subtract.
05:25The code within the addValues method is almost the same as I want in all four of
05:29these methods, so I'm going to select it and copy it, and then I'll paste it
05:34into place for each of the other methods.
05:36And all I need to do in each of these methods is change the operator.
05:39For subtract I'll use the dash for multiply, I'll paste in the code and change
05:44the operator to an asterisk, and for divide, I'll select that extra code, delete
05:49it paste in the other code and change the operator to a forward slash.
05:55I'm pretty close to being done, there's still one error there.
05:58The local variable result may not have been initialized, so I'll click the
06:02error and I'll get another set of quick fix proposals, one of them is the
06:06correct suggestion.
06:07When you declare a variable that's outside a code block, but you're only going
06:11to set its value inside a code block, the Java compiler wants you to initialize
06:15its value when you declare it, so I'll go back up to the line where I declared
06:19result and I'll set it 0.
06:21Now finally I have one more bit of code to take care of.
06:24I've asked the user to type values of 1, 2, 3, or 4, but what if they
06:27type another value?
06:29I'll move the cursor after the default case, but before the break statement and
06:33in this case I'll tell the user you selected a value I didn't understand.
06:37I use System.out.println, (" You entered an incorrect value");
06:42and then to terminate the application at that point, I'll use the Return keyword.
06:47I no longer need the break statement there, because if we got into the default
06:51block that means the application is done.
06:53I'll go ahead and run the application let's see how we do.
06:57I'll type in two numeric values 10 and 5, and instead of adding, this time
07:02I'm going to divide, by typing in the number 4, and I get the value 2, and that's correct.
07:06I'll run the application again, once again, I'll type in 10 and 5 and this time
07:12I'll multiply it by typing 3, and I get 50.
07:16So now my calculator is handling all four values.
07:19It's still possible to break the application, for example, what happens if I
07:23type values here, 5 and 10, but then instead of typing a numeric value I type a
07:28string value, I'll get an exception.
07:30I'll show you how to handle these exceptions and how to debug your application
07:34in a later chapter, but what's important to know at this point is that you now
07:38know how to accept values from the user, how to examine those values, how to
07:42process them conditionally, using if statements and switch statements, and how
07:47to execute simple math operations.
07:49This application, file trivial, is using many important parts of the Java
07:53programming language.
07:54And you're now ready to move on to other aspects of the language that can give
07:58your applications even more power.
Collapse this transcript
6. Working with Complex Objects
Using the String class
00:01The string class is one of the most commonly used complex types in Java.
00:06I call it a complex type, because when you create a string, you're creating an
00:09instance of a class.
00:10It's not a primitive variable, such as char, int, short and the others.
00:16I'm working in a project called strings that's part of the Chapter 6 Exercise Files.
00:20And the beginning class just has an empty main method.
00:23I'll start by declaring a string named s1 and I'll give it a value of
00:28"Welcome to California!"
00:29When you declare a literal string in Java, you must wrap the string in double quotes;
00:35single quotes are only used for character types.
00:38Double quotes are always used for strings.
00:40Now I'll output the value to the console using System.out.println(s1).
00:47I'll run the application and predictably I get the output "Welcome to California!"
00:52Now you can declare strings in one of two ways.
00:55This syntax where you assign a literal string directly to the equals assignment
00:59operator is actually a shortcut.
01:01Because the string class is a complex class, you are actually creating an
01:05instance of the class.
01:06And you can also use the more conventional instantiation syntax.
01:11It would look like this, I'll declare a second string named s2, I'll use the new
01:16keyword, I'll call the constructor method for the string class.
01:21A constructor method is a method of a class that has the same name as the
01:24class itself, and then I'm going to pass in exactly the same value to the
01:29constructor method.
01:31I'll select that text including the quotes and paste it between the parentheses
01:35and then add the semicolon at the end.
01:38And I'll change the variable that I'm outputting from s1 to s2, I'll Save and
01:42Run and the output is exactly the same.
01:46You can use either syntax style to create a string, they are
01:49functionally equivalent.
01:51Now I mentioned in an earlier video that if you want to compare two string
01:54values, you shouldn't use the double equals operator.
01:57It's unpredictable.
01:59There are some circumstances in which you can compare s1 and s2, and if they
02:03have the same value, you'll get a true value back and there are some
02:06situations where you won't.
02:07This is a situation where you won't.
02:09If you declare one string using the shorthand syntax with the equals assignment
02:13operator and just a literal string, and the second string using the constructor
02:17method, then you can't compare the values using double equals.
02:21It's a strange situation, but I want to show you the result.
02:23I'll place the cursor at the end of the existing code and I'll create
02:26a conditional block.
02:27I'll type if and press Ctrl+Space, choose the if statement, and then I'll set my
02:32condition as s1 has a value of s2, using the double equals operator.
02:38And then in the conditional block, I'll use System.out.println and I'll output
02:42the string, ("They match!").
02:44I'll add an else clause and I'll make a copy of this println command, paste it
02:50into the else clause and change that to ("They don't match!").
02:53I'll Run the application and I get back a negative result even though those two
02:58values look like they match pretty closely.
03:00So here's what's going on, the s1 and s2 objects are different objects.
03:05Even though they have the same string value, you can't reliably use the double
03:09equals operator this way.
03:11So instead, you should use a method called equals.
03:14The string class has a very deprogramming interface and the equals method is one
03:19of its most useful methods.
03:21Let's take a look at the documentation for the string class, I'll double-click
03:24the data type string, go to Dynamic Help on the Help menu, click the link for
03:29the class Java.lang.string and maximize the help view.
03:33I'll click the Method link and scroll down to the es, and show you that there
03:38are two versions of the equals method.
03:40The equals method is case sensitive.
03:42It compares the string to the string of another object.
03:45There is also equals ignore case, so you can do a non-case sensitive comparison.
03:50So I'll close the Help screen, and I'm going to change my syntax so that instead
03:54of using the double equals operator, I'll use the equals method.
03:58If (s1.equals(s2)).
04:01I'll save and run the application and now I get They Match!
04:06Now for non-case sensitive comparisons, use the equals no case method.
04:10I'll go to the second string and change the welcome word to uppercase.
04:15I'll run the application and I get They don't match!
04:18because the equals method is case- sensitive, but then I'll come down to the
04:22equals method and change it to equalsIgnoreCase I'll fix up the code so
04:26it's syntactically correct and I'll run the application again, and now I get They match!
04:31Finally, I'll show you one more method.
04:33I've shown previously that a string contains an array of characters and you
04:38can extract that array of characters and then loop through it one character at a time.
04:42I've moved the cursor below the conditional code, I'll declare variable with the
04:46data type of char, open bracket, closed bracket—- that's an array of the primitive data type char-- and I'll
04:53name it chars and then I'll call the method toCharArray.
04:57So it looks like this, s1.toCharArray();
05:00So now I have an array of characters, then I'll loop through the array and I'd
05:05put one character at a time.
05:07I'll type for and press Ctrl+Space and I'll chose the for-each iteration.
05:12For each variable which is going to be data typed as char with the name of c in
05:16the char's array, I'll use System.out. println and I'll output the value of c,
05:23the character in that position.
05:24I'll run the application and here is the result.
05:28Now I'm outputting the string one character at a time, one line at a time.
05:32Take a look at the rest of the documentation for the string class.
05:36You'll find all sorts of useful methods that allow you to compare, set, extract
05:40and otherwise manipulate string values.
Collapse this transcript
Building strings with StringBuilder
00:00The string class is one of the most common complex classes you'll use in Java.
00:05The string class has a special characteristic, it's immutable.
00:08This means that when you set a value of a string object that value cannot be changed.
00:14Now it might seem like you can change it.
00:16Let's take some very simple code, I have declared a string called s1 and
00:20given it a value of Welcome, I'll place the cursor on the next line and say
00:24s1 = s1+ "to California!";
00:29you could also write this code using the += operator, either way it looks
00:33like you're appending to an existing value and simply changing the value of
00:38an existing variable.
00:39Then I'll output the value of that variable to the screen using
00:42System.out.println, and I'll parse in s1 and I'll Run the application and
00:49everything looks like it's working just fine, but it's not so great in the background.
00:53What's really happening is that when you append a value or otherwise change the
00:57value of the string variable, you're actually creating a new instance of the
01:01string class, and you're abandoning the reference to the old object.
01:05That old object is still out there in memory;
01:07it becomes eligible for garbage collection.
01:10But in fact, you're using more memory than you need to or should.
01:13You won't see this behaviorally in your applications, the issue only becomes
01:17apparent when you're trying to tune your applications in a small memory
01:21environment, or you're working with very large scale applications.
01:24But because this is a universal issue in Java, it's good to know how to deal
01:29with it from the beginning.
01:30Java provides two utility classes called StringBuffer and StringBuilder, these
01:35two classes have the same API or programming interface, and they both implement
01:40the same methods named insert and append.
01:43The insert method can be used to insert text into a string at either the
01:46beginning or any other position in the string.
01:49And the append method can be used to append text to a string.
01:53You can use either the StringBuilder or the StringBuffer in most environments,
01:56but in general, the StringBuilder is more slender, it takes less memory and
02:00resources, but it's only good for single threaded environments.
02:04StringBuffer should be used where you need to synchronize the use of a string
02:08among multiple threads.
02:10If you're new to Java don't worry about it, just use StringBuilder until you
02:14find out you have to StringBuffer.
02:16So here is an example of how you might use StringBuilder.
02:18I'm going to take this little bit of code out and leave myself with the simple
02:23s1 variable and then after I've created the initial string, I'll create another
02:27variable named StringBuilder, notice that StringBuilder and StringBuffer are
02:31both members of the package java.lang, so they're always available to your code.
02:36So I'll declare the variable StringBuilder and I'll name sb and I'll
02:40instantiate it using new StringBuilder, I'll place the cursor inside the
02:45parentheses and press Ctrl+Space and show you the different ways that you can
02:49create a StringBuilder.
02:50You can either call the constructor method with no arguments or with some of
02:54these other settings, but the one I'm going to use is an initial string and I'll parse in s1.
03:00So now my StringBuilder class is being created and it's been populated with
03:03that initial value.
03:05Now to append a value, I'll call sb. append and I'll parse in that appended value
03:10that I used before, "to California!" and I'll change my print line command to
03:16output sb, the StringBuilder.
03:19I'll Run the application and I get the same result.
03:21Whenever you're working with strings that you need to manipulate, either adding
03:25text or inserting text, use the StringBuilder class instead of a simple string,
03:30you'll create fewer objects and you'll conserve memory.
Collapse this transcript
Parsing string values
00:00The string class has many methods that you can use to manipulate and parse its values;
00:05I'll show you some of these methods in this project, Parsing Strings.
00:09I'm starting in an empty main method and I'll declare a variable named s1 with a
00:14value of "Welcome to California!"
00:17First, I'll show you how to find out how long a string is.
00:20I use System.out.println and I'll output "Length of string:" and then to find
00:29out how long the string is, use the length method, s1.length.
00:33I'll run the application and there's the result.
00:37You can also parse strings using methods of the string class.
00:41Here, I'm going to show you how to find a string within a string, I'll declare
00:45an integer variable named pos for position, and I'll call the method s1.IndexOf.
00:52You'll see when I press Ctrl+Space that there are a number of versions of
00:55the IndexOf method;
00:56you can parse in a character or string starting from a particular location.
01:00I'm going to use the version that's looks for a particular strength, and I'll
01:03pass in a literal string of ("California ") and then I'll output the value of the
01:08position character using (" Position of California":)
01:13and then I'll append pos.
01:15I'll run the application and it tells me that California starts at position 11.
01:21Next, I'll show you how to extract a value from a particular position of the string.
01:26I'll declare a new string called sub, and I'll call s1.substring.
01:31The substring method has three different versions, the one that passes in a
01:34single integer, the one that takes a single integer and an ending integer, and
01:38one called subsequence, named differently, that returns a character sequence.
01:43I'm going to use the substring method and I'll ask for the value starting at
01:47position 11, then I'll use System.out .println again, and I'll output the
01:52substring that I extracted.
01:54I'll Run the application and there is a result, I get everything starting at
01:59the word California!
02:01including the exclamation mark at the end.
02:04Finally, I'll show you how to trim a string that might have spaces at the end.
02:09I'll create a new string called s2 and I'll give it a value of "Welcome!" and
02:13I'm going to add a whole bunch spaces at the end of the string.
02:16Then I'll declare an int variable named len1, and get its value from s2.length,
02:23and I'll output the value of len1.
02:28I'll Run the application and I get a value of 15.
02:31Then I'll declare another variable named s3, and I'll get its value from
02:36s2.trim, the trim method removes the extra white space.
02:41Then I'll make a copy of my print line command and this time I use a slightly
02:44more extended syntax, so I don't have to create another integer variable.
02:48It will look like this, s3.length.
02:51I'll Save my might changes and Run the application and after trimming, I'm down
02:56to just eight characters.
02:58In this exercise I've shown you some of what I think are the most useful
03:01members of the string class, but again, I encourage you to look at the
03:04documentation for the string class.
03:07You'll find in this list of methods many, many tools that you can use to
03:11extract, manipulate, convert and otherwise use the string class however you need
03:16to in your applications.
Collapse this transcript
Working with date values
00:00Java gives you a couple of different ways of representing dates just as with
00:04strings, the date is a complex object and not a primitive variable.
00:08I'm working in this empty main method in the Dates project and I'll start by
00:12declaring an instance of this simple date class.
00:15I'll type in the word Date.
00:17Now this is going to be the data type of my variable, but unlike all the other
00:20data types that I've have used previously, the date class is not a member of a
00:24packaged called Java.lang, which is always available to your code and to the
00:28runtime environment.
00:30Now we are stepping out into other libraries in the core Java class library,
00:34specifically the date class is a member of a package called java.util, it's a
00:39part of the core class library, it's always available to you.
00:42But if you want to use this class in your code you have to explicitly import it into your code.
00:47Eclipse will help you with the syntax, with the cursor right after the word
00:50Date press Ctrl+Space.
00:52You'll see four different date classes offered.
00:54The one we want is at the top java.util.
00:57There are other date classes for java.sql and others for sun.util.
01:02I'll press Enter or Return and that adds the import statement for that date
01:06class into my code at the top.
01:08I'll give the variable a name of d, and then I'll create the instance using the
01:12new keyword and then the constructor method, which like all constructor methods
01:16matches the name of the class and then with the parentheses in place.
01:20I'll press Ctrl+Space.
01:21You'll see that there are a number of versions of the constructor method for the date class.
01:25If you use what we call the no arguments constructor, that is the method that
01:29you don't pass any values into, you'll create an object that represents the
01:33current date and time on your computer.
01:35The next version takes a long integer, representing the number of milliseconds,
01:40since the epoch date.
01:41January 1, 1970 at midnight, you can also represent a date as a string, as three
01:47integer values representing the year, month and date, and you can get all the
01:51way precise down to seconds.
01:52I am going to choose the no arguments constructor.
01:55I'll finish that statement with a semicolon and then I'll output the value of
01:59the date object using System.out. println and I'll just pass the date object in.
02:05The date class has a two string method, when you pass in the object to println,
02:09just like all variables in Java, when you pass the object in, you'll get a
02:13string representation that's determined by that two string method.
02:17I'll run the application and I'll get the default formatting.
02:20The day and month represented as three character alpha values, the date, the
02:24time, the time zone and the year.
02:28Now the other class that you can use to represent a date in Java is
02:31called Gregorian calendar.
02:33The name of the class has calendar in it but it really represents a
02:36particular date and time.
02:38You use very similar syntax to instantiate a Gregorian calendar object.
02:43Because Gregorian calendar is a long name, I'll just type in the beginning,
02:47Greg, and I'll press Ctrl+Space and I'll let Eclipse fill in the rest of the
02:51class and add the required input statement at the top.
02:55I'll name this new variable gc for Gregorian calendar.
02:58For the constructor method, once again, I'll type the beginning of the class
03:01name and press Ctrl+Space.
03:03You'll see that there are constructor methods for this class, including some
03:07that match the style of the date class, there's no arguments constructor method,
03:11there is a version that takes a year, month and day, one that goes all way down
03:15to seconds and then there are particular versions of the calendar class that
03:19allow you to set the locale and time zone.
03:22I'm going to use this version that lets me set a particular year, month and day.
03:27When you set the year, you need to pass in a four digit numeric value.
03:31I'll type a value of 2009, set the month to a value from 0 to 11 just like a
03:36Java array, a month is represented using zero-based calculations.
03:40So 0 is January, 1 is February and so on.
03:44I'll type the number 1 for February and then I'll set the day of the month at
03:4728, the last day of February in that year.
03:50Now if I were to type in a value of 29, the Gregorian calendar class is smart
03:55enough to know that 2009 was not a leap year and it would reject that.
03:59One of the advantages of using a Gregorian calendar object is that you can do math with it.
04:04You can add, subtract and otherwise manipulate the date.
04:07I'm going to increment the value of the day in the Gregorian calendar by 1.
04:12So I should go from February 28 to March 1.
04:15Here is the code, gc.add.
04:18The add method takes two values, a field which represents which part of the
04:22calendar I want to manipulate, and the amount.
04:25For the field use a value that's a member of the Gregorian calendar class, like this.
04:31I'll type in GregorianCalendar and then dot and I'll see a listing of all of the
04:36available settings that represent parts of a date.
04:39And I am going choose this one, DATE which represents the day.
04:42And then I'll tab over and set the value as 1.
04:46So I am adding 1 day to the date.
04:48Now to output the value, I have to convert it back to a date object.
04:53The Gregorian calendar doesn't have formatting capability, it only has math,
04:57manipulation and the ability to breakdown the date into small parts.
05:01So in order to get it ready for formatting, I'll create another new date class.
05:05I'll call this one d2, and I'll get its value from gc.getTime.
05:10The getTime method returns an instance of the date class.
05:14Now for formatting, I'm going to use yet another class called DateFormat.
05:18I'll create an instance of the DateFormat class, just as with date in
05:22Gregorian calendar, I need an import, so I'll type in the name of the class
05:25and press Ctrl+Space and I'm going to choose the DateFormat class from the package java.txt.
05:32I'll call my DateFormat class df for date format.
05:36Now in order to construct an instance of this class, you don't use the new keyword;
05:41the DateFormat class has a number of methods that you can use to return
05:45instances of the DateFormat class.
05:47I'll use this syntax, DateFormat.getDateInstance.
05:51This is a particular design pattern called a factory method.
05:55A factory method of a class knows how to return an instance of that class, and
06:00you'll see in this list many different factory methods that behave differently.
06:04Again, for detailed information about what each of these methods does, look at the docs.
06:08I'll choose this very first factory method, getDateInstance.
06:12Next, I'll create a string and I'll call this one sd for a string of a date.
06:18And I'll get the value of sd from df. format, and I'll pass in the d2 variable,
06:24the date object I got from the calendar.
06:26And then finally, I'll output the value using System.out.println and pass in the value of sd.
06:33I'll run the code and there is the result.
06:36I started off with February 28th, I added a value of 1 to the date and I got March 1, 2009.
06:42Now this is the default formatting.
06:44You can easily manipulate or change how the formatter behaves.
06:48I'm going to change the way I called to getDateInstance method.
06:52I'm going to pass in a DateFormat.FULL.
06:55This is a field or a constant of the date format class that means use more
07:00extended formatting.
07:01I'll Save and Run the application again and now I get the full day, month, date and year.
07:08So that's a look at three useful classes that you can use to manage
07:11and manipulate dates.
07:13The date class which represents the date as the number of milliseconds, since
07:16January 1, 1970, through Gregorian calendar that lets you break down the date
07:21into parts and do math, and otherwise manipulate the values, and the date format
07:25class that allows you to format the date for presentation.
07:29All three of these classes require explicit imports in your code, because
07:33none of them are members of that package java.lang, these classes are always available.
07:37I'll talk more about import statements later on in the course, but just know, if
07:42you're not sure whether you need an import statement for a class, just place the
07:45cursor after the class name, press Ctrl+ Space and select it and if you need it,
07:50Eclipse will add it to the code for you.
Collapse this transcript
7. Exception Handling and Debugging
Understanding compile-time vs. runtime errors
00:00Errors in Java can be separated into two major types, compile time and runtime errors.
00:06A compile time error is either a syntax error or an error in the structure
00:11of the application.
00:13Syntax errors are pretty straightforward.
00:15Let's say for example that I declare a variable named s and I give it a value,
00:20but I don't put the semicolon at the end of the line.
00:23That breaks a fundamental rule of Java syntax.
00:26All statements must have a semicolon.
00:28And when I save and try to build the application, I get this error down at
00:32the bottom in the problems view, Syntax error, insert semicolon to complete BlockStatements.
00:42Other kinds of compile time errors can occur when you break fundamental workflow rules.
00:47For example let's say I declare a variable named s, I put in the semicolon at
00:52the end of the line and that line on its own is syntactically correct.
00:56But then I immediately try to output the value of s using System.out.println and
01:03I parse in the value.
01:05And so I have two syntactically correct statements, but when I save the
01:10application once again, I get an error in my problems view.
01:14If your errors are represented by this red circle with x, that means it's an
01:19error that is preventing the application from compiling.
01:23And if you try to run the application you'll get this error dialog.
01:27Errors exist, Proceed with launch.
01:30If you proceed at this point, your application might seem to run, but you'd be
01:35running an old version of the application, not the one for the code you have on
01:39the screen right now.
01:40If you have errors like this your application can't be compiled.
01:44In this case the rule that you are breaking is that you can't declare a variable
01:49without initialization code and then refer to that variable immediately.
01:54The most common fix to this is to add equals null and that would make it so that
01:59the compiler decided you knew what you were doing.
02:02Because I declared the variable and gave it an initial value, I can now compile and run.
02:08And when I run the application I just get the word null.
02:12So that's a compile time error.
02:14The other type of error is a runtime error.
02:17These are errors that occur because you break some rules that can't be caught by
02:21the compiler but when you run the application the error is so bad it just kills
02:26the application, it crashes it.
02:28Here is a very simple error that occurs a lot.
02:31I'm going to declare a new string array variable, I'll just name it strings.
02:36And I'll give it an initial value of one item, "Welcome!"
02:40This is one way of declaring an array in Java by wrapping comma delimited list
02:46inside a pair of braces.
02:48If I only declare one value inside the braces, then it's an array of one item.
02:53Now I'm going to try to output an item in the array using System.out.println and
03:00I'll refer to strings, open bracket, 1, closed bracket.
03:06This is clearly an error.
03:08Arrays in Java are zero-based.
03:11If I want to refer to the first item in the array, I need to refer to the
03:15index zero, not one.
03:17If I'm referring to one that means the second item in the array and it doesn't exist.
03:22When I save my changes, the compiler says looks good to me and I don't see any
03:28problems in the problems view.
03:30But when I run the application, I get a big odd error and my application
03:34just stops working.
03:36Exceptions in Java cause the application to quit unless you've handled them yourself.
03:42The particular error that's occurring is something called
03:45ArrayIndexOutOfBoundsException.
03:48In the next video I'll talk a little bit more about exception classes or
03:52exception objects, the kind of objects that are generated in Java when an
03:57exception occurs and how you can look at the exception object both in the Java
04:02debugger and in your own code.
Collapse this transcript
Handling exceptions with try/catch
00:00If you know in your application that you might generate a runtime exception, you
00:04can anticipate and handle it using a syntax called try and catch.
00:09The first thing you have to know is how exceptions behave.
00:13I'm working in a project named exceptions and it has a couple of lines of code
00:17that will generate a runtime error.
00:20I've declared a strings variable which is an array of string objects and I've
00:24initialized it with one item, a string named welcome.
00:27And then in the next line, I try to output the second item in the array,
00:31which doesn't exist.
00:32When I run the application, I get an exception.
00:36When these kinds of exceptions happen in Java it stops your application cold, it
00:41crashes the application.
00:43I can show you that in fact this application is crashing and is not
00:47continuing with its execution.
00:49I'll add another line of code down here System.out.println and I'll output, "The
00:55application is still running1" I'll save and run the application, I'll see my
01:03error and I don't see anything after it.
01:07So how do you handle a potential runtime error?
01:10The first thing you need to know is that when an exception occurs, a variable is
01:15generated, an exception object.
01:17The exception object will be an instance of a class named exception or of
01:23another class that's a subclass of exception.
01:26If you want to wrap your code and deal with a possible exception, the first
01:30thing to do is put the code into a try block.
01:33The try block will be followed by a catch block or more than one catch block and
01:38the code in the catch block will deal with the exception in some way.
01:42Here is a very simple way to add a try catch block around some code that might
01:46generate a run-time error.
01:48I'm going to select that code and then I'll right click on it and I'll choose
01:53Surround With, Try/catch block.
01:56The syntax of the Try/catch block is that you start off with the word try and
02:02then you put the code that might generate the exception inside the first set
02:05of braces, then you follow that with a catch block starting with the keyword
02:11catch and then a variable declaration which is of data type exception or one of its subclasses.
02:18Then within the catch block, you can handle the exception in some fashion.
02:23If your code execution gets into the catch block that will clear the error and
02:28your application will continue running.
02:30I'm just going to get rid of the TODO comment and save my changes and then I'll
02:34run the application again.
02:37And I still see that there is an error but then I get this extra little bit of code.
02:42The application is still running.
02:44And so I know that my try catch block has handled the exception.
02:48Within the catch block right now, I'm executing a method of the exception
02:52class called printStackTrace and that's why in the console block, you're
02:57seeing this output.
02:58java.lang.ArrayIndexOutOfBoundsException:
02:591.I could take that little bit of code out, I am just going to comment it and
03:08I'll put in a little bit of my own custom code, System.out.println, there was an error.
03:14So I'm telling the user that something went wrong, but I'm being a little more vague.
03:18Stack traces tend to scare users, because they don't know what's going on inside
03:23the program and they shouldn't have to.
03:24I'll run the application again and now I get clean output.
03:29There was an error, but the application is still running.
03:33In this situation, the particular type of exception that was thrown was not just
03:38an instance of the exception class but of one of its subclasses.
03:42You can be more specific in your catch block by knowing exactly which type of
03:46exception you are anticipating.
03:49To find out what that class is, I'm going to remove the comments and run the
03:53application again and I see that the exception object is an instance of this
03:58one, ArrayIndexOutOfBoundsException.
04:02To be more specific about this, I'll go into the console and I'll copy the name
04:07of that exception class to the clipboard, then I'll go back to my code and I'll
04:12change the data type of the exception object.
04:14I'm declaring from exception to a rate index out of bounds exception, just
04:19by pasting that in.
04:20Then I once again comment out the printStackTrace method and run the application.
04:25And I'll see that everything is working the way I wanted it to.
04:28But now I set up a situation where as long as they get this particular
04:32exception, I'll be able to keep running the application but if any other
04:36exception happens the application will stop.
04:39The compiler will tell me what went wrong and I'll be able to figure out what
04:42that exception was about and fix it.
04:45So that's a look at how to use the try catch structure, to anticipate
04:49errors that you know might happen in your application and then elegantly deal with them.
Collapse this transcript
Throwing exceptions in methods
00:00As I showed in a previous video, a runtime exception generates an instance of a
00:04class called an exception class, either the exception class itself or one of its subclasses.
00:10I've shown how to deal with this with a try catch block around the
00:13possibly offending code.
00:15But I'd also like to show you how to explicitly declare some code that might
00:19throw an exception and wrap it in a method that has a keyword called throws,
00:24that tells the rest of the application what might happen.
00:27Here is the same starting code as in a previous video, instead of wrapping
00:31this directly inside try catch, I'm going to take this code and put it into its own method.
00:37I'll select these two lines of code right click on the selected code and choose
00:42Refactor, Extract Method.
00:44I'll give the method a name of getArrayItem, and right here I'm going to select
00:50an option of Declare thrown runtime exceptions.
00:54This sort of refactoring, taking code that might generate a runtime exception
00:58and putting it into its own separate method is such a common practice that
01:03Eclipse has a special option for it.
01:06I'll click OK and that creates the new method.
01:09Now notice, it didn't add any additional code and the reason is because in this
01:13situation none of the code that I executed already told Eclipse what kind of
01:18runtime exception might happen.
01:21So I'm going to put in the code myself, I'll place the cursor after the name of
01:25the method, now at this point, the code is going to get a little bit wide.
01:29So I'm going to go to a new line here and I'll put in the keyword throws and
01:35then add Array press control space and choose the exception class
01:40ArrayIndexOutOfBoundsException.
01:43This now tells the rest of the application that when this particular code is
01:47running, that is the code within the getArrayItem method, that it could throw
01:51this specific kind of exception object.
01:53Now, I'll go to the method getArrayItem, I'll select that, I'll right click and
01:59I'll select Surround With, Try/catch Block and now Eclipse is smart enough to
02:03know that because I'm calling a method that could throw this object, that's the
02:08one it's looking for.
02:09I'll get rid of the TODO comment, I'll replace e.printStraceTrace with my own
02:15custom message, System.out.println " Array item was out of bounds" and I'll
02:25run the application.
02:26And now I'm elegantly catching the error, handling it myself, and the rest of
02:31the application can keep on running.
02:34So again, the common practice is when you have a bit of code that might generate
02:39an exception, put it in its own special method and mark the method with the
02:44keyword throws and the particular kind of exception class that might be thrown.
Collapse this transcript
Using the debugger
00:00All good Java development environments including Eclipse provide good debuggers
00:04that allow you to inspect data at runtime, set breakpoints, and otherwise figure
00:09out what's going on in your code.
00:12I'm going to show you how to use the debugger and along the way, I'll show you
00:15how to work with parts of the Java class library that commonly throw exceptions,
00:20how you can find out what those exceptions might be and anticipate them.
00:25I'm working in an empty main method in the current project debugger.
00:29I'm going to declare a variable of a special type URI.
00:33URI stands for Uniform Resource Identifier.
00:37This class is a part of the package java.net and is part of a collection of
00:41classes that are used for network communications in Java.
00:45After you have typed URI, press Ctrl+ Spacebar and choose the URI class from java.net.
00:51That will add an import statement at the top of the code.
00:54Then give it a variable name uri, all lower case, and set its initial value with
01:00the constructor method new URI and pass in a well formed domain string such as
01:06"http://somecompany.com."
01:12It doesn't matter what the name of the domain is or even whether it's real
01:15website, what matters is that it's well formed with http://at the beginning and
01:21then a well formed domain at the end.
01:24When you save your changes and build the project, you'll see an error has
01:28occurred, Unhandled exception type URISyntaxException.
01:33The Java compiler seems to think that when I call this URI constructor method,
01:37it might throw an exception and that it's up to me as the programmer to make
01:41sure that I've handled that exception.
01:43Well, how would I know that as the programmer unless I have to wait for the
01:47compiler to tell me?
01:48And the answer as is so frequently the case in Java is that it's there in the documentation.
01:54I'll go to the URI documentation, I'll double click URI, the data type and
02:00then I'll go to my Dynamic Help and click javadoc for java.net.uri and I'll
02:07maximize the Help screen.
02:10In the documentation, I'll click on Constructor, here is the method that I just
02:14called URI receiving a string argument.
02:18I'll click that method and it tells me and the documentation very explicitly,
02:23this method could throw an the instance of URI syntax exception.
02:28So when you're working with a method that's part of the Java class library
02:33and that method has been defined as throwing an exception, it'll be there in the docs.
02:38So what do I have to do as a developer to deal with that?
02:41If a bit of code is going to throw an exception I have to handle it with a
02:46Try/catch method or by putting an appropriate throws declaration in the method
02:52signature where I'm actually calling the code.
02:55I'm going to wrap up this code with a Try /catch block, I'll select the code then
03:00right-click it and choose Surround With, Try/catch block.
03:06Eclipse is smart enough to look at the syntax of the class or the method and say
03:11hey that method might throw URI syntax exception and so that's the class that
03:16puts into the catch block that it generates.
03:19Now, I'll delete the TODO comment and I will add a little bit more code down at
03:24the bottom, so I can see clearly that the application is still running
03:27System.out.println and I'll put the message "I'm alive!"
03:35I'll save the change and run the application.
03:40And the first time everything works fine because the string that I passed into
03:44the URI method was a well formed domain.
03:48But now let's create an intentional error.
03:50I'll change those forward slashes to Backslashes.
03:54That will create a malformed URI.
03:57I'll save and run the application and now I get the stack dump.
04:02I still see I'm alive!
04:03at the end of the output.
04:05And by the way, you might not see this at the end of the output it might be
04:08mixed into the middle don't worry about that.
04:11But if you see that message that means that the Trycatch block is working but in
04:15fact, this error message is being thrown as part of that complex exception
04:20object and this takes us to the debugger.
04:24Let's say, that I wanted to interrogate that exception object while I'm
04:27programming, I wanted to look at its structure.
04:31I can put a breakpoint on the line where the printStackTrace command is being executed.
04:36And I can freeze the execution of the application, suspend it, while it's
04:41suspended, I can use Eclipse to inspect that exception object and see what
04:46information is available.
04:47To do this place a breakpoint on the line where the exception object is in
04:52scope, in this case it's on this line where I'm calling printStackTrace.
04:57To set a breakpoint, go to the left trough over on the left side of the editor
05:02and either double-click or you can right click and choose Toggle Breakpoint.
05:08Either way, you should see this little icon showing that there is now a
05:11breakpoint at this particular line.
05:13Now it's time to run the application in debug mode.
05:17Go to the toolbar and click debug, it's the little button that looks like it has
05:22a cockroach or a bug on it. Click the button.
05:26If you see a message from your firewall application, let it know that everything
05:30is okay, and then you should see this message Confirm Perspective Switch.
05:35This is telling you that Eclipse wants to switch to something called the Debug perspective.
05:40The debug perspective is a collection of views that will allow you to more
05:44quickly inspect and fix your application. Click Yes.
05:49And this is the debug perspective.
05:52There is a Debug view in the upper left that shows your current call stack, a
05:56Variables view that shows all the currently in scope variables the Editor, the
06:01Outline and down at the bottom, the Console.
06:05Go to the Variables view because you suspended the application at the point
06:09where the exception object became available, you should see the exception object
06:14named e listed there, double-click the tab for variables to expand it and then
06:20expands the e object.
06:22You'll see that there's all sorts of interesting information the cause, the
06:27detail message, the index, the input and the stack trace.
06:32Now some of these values occur on all exception objects like the detail message,
06:37but the values that they have may or may not be useful.
06:41In this case, there's a pretty interesting error here, Illegal character in opaque part.
06:47But you'll also find that you can call methods of the exception object to get
06:51the information more elegantly.
06:54Once you've finished inspecting the exception object, double-click the Variables
06:58tab to return it to its original size, then go up to the toolbar and click the
07:02Terminate button, it's the red square button on the toolbar.
07:07And then return to your CustomForJava perspective.
07:11You can choose the perspective from the upper right or you can go to the Menu
07:15and choose Window, Open Perspective, Other and choose the perspective you want,
07:21I've been using this one CustomForJava.
07:24Once you know what the structure of the exception object is, you can do some
07:27interesting stuff with it.
07:29So for example, instead of printing the stack trace, I'm going to do a little
07:33print line here System.out.println.
07:37And I'm going to output a value from e.getMessage.
07:41This is a method that's available on all exception objects.
07:45I'll save my changes and run the application again.
07:49And I get that message Illegal character in opaque part at index 5, and it's
07:55talking about index 5 of the string.
07:57If you start counting at 0, the letter h is 0, ttp is 1, 2, 3, the : is 4 and
08:05the / is 5, that \\ was interpreted as a \ by Java and it's telling me exactly
08:13where the problem is in that string.
08:16So now, I can come back to the code and go oh gosh, I put in \\ instead of //
08:21and I can fix it, save and run, and everything is okay.
08:27So whenever you are working with a method that might throw an exception, you
08:31should wrap it inside a Try/catch block and then within the catch block to can
08:35set a breakpoint and inspect that exception object.
08:39Once you know how to use the debugger for that, you know how to use it for everything.
08:44Whenever you have some information in your Java programming environment and
08:48you're not sure what the value of a variable is, set a breakpoint and use the debugger.
Collapse this transcript
8. Using Data Collections
Using simple arrays
00:00Java gives you a couple of ways of managing ordered collections of data in memory.
00:05The simplest approach syntactically is to use simple arrays.
00:08Simple arrays are very easy to code, but they're not particularly flexible.
00:12There are couple things to know about simple arrays.
00:15First all of the items in an array must be of the same type, so you can create
00:19an array of integers or create an array of strings, but you can't create an
00:23array that contains both.
00:25Also, when you declare an array it's always of a fixed size.
00:29You set the size when you declare it and you can't change the size at runtime.
00:34If you want to use resizable arrays you want to take a look at the class array
00:37list which I'll describe in a separate video.
00:41There are few different syntax styles that you can use to declare and
00:44initialize an array.
00:45I'm working in an empty main method in a project named simple arrays.
00:50Here is one style of syntax.
00:52Start with the data type of the array, followed by a pair of brackets, then
00:56assign, the array name, put in an equals operator, and then initialize the
01:01array using the new keyword, the data type again and the brackets again but
01:06this time the size.
01:08So this is an array of three integers.
01:11Now, I'll add up a little bit of looping code.
01:14I'll type in for and press Ctrl+ Spacebar and I'll choose iterate over array,
01:19I'm iterating over the a1 array, Eclipse figured that out for me.
01:24And within the for loop I'll output System.out.println and I'll output the value
01:29of a1, bracket, i, bracket) meaning the item at position i. I'll save and run the application and
01:37the output is three zeros.
01:41Now, there is a variation on this syntax that's possible and it's completely a
01:44matter of preference which one you use.
01:46I am going to select and copy this block of code and then paste it in.
01:51I'll change the name of the second array to a2.
01:54I'll make the change in three places, here, here and here.
01:59And then I'm going to take the brackets and move them from after the data type
02:04and paste them after the array name.
02:07This variation does exactly the same thing as the first version.
02:10It creates an array of three items and the items will have their default value.
02:15Integer is just like all other primitive numeric types, have the default value of zero.
02:21And so when I print these out once again I should get three zeros, and when
02:25I run the application, I get the three items in array a1 and the three items in array a2.
02:33The third style syntax for simple arrays is to initialize the values in the
02:38declaration statement.
02:39I've used this version of the syntax previously in the course.
02:43Start off with your data type, once again you can place the brackets either
02:47after the data type or after the array name and then put in a pair of curly
02:52braces and then declare your list of items as a comma delimited list.
02:57So I'll add in a list of 3, 6, 9.
03:01The number of items in the array and their values are determined by that list.
03:06As with the previous declarations, once the array is set to have a particular
03:10number of items it will always have that number of items, you can't change it at runtime.
03:16I'll make a copy of one of these for loops, and I'll copy and paste it down here.
03:21I'll change the references here from a2 to a3.
03:26I'll run the application and there is the result.
03:30The last array has values of 3, 6 and 9.
03:32Once you've declared an array, you can address the items in the array using
03:39array syntax, where you referred to the index of an item using zero-based
03:44numbering wrapped inside brackets.
03:47So for example, I could say System.out. println, "The value of the first item is"
03:58and then I can address a3, open bracket, 0.
04:03I'll save and run the application, and I see that the value of the first item is three.
04:08And as I've shown in previous videos, if I try to address an array item and I
04:13get it wrong, if I put in an index to an item that does not exist I'll generate
04:18an exception a runtime error.
04:21So that's the basics of simple arrays, once again the syntax can vary a little
04:25bit, you can place these initial brackets either after the data type or after
04:29the array name and you can either use the new keyword and an explicit number of
04:34items in the array, or you can use a comma delimited list wrapped in braces.
04:39Either way the array must contain items all of the same data type and it is not
04:45resizable at runtime.
Collapse this transcript
Using two-dimensional arrays
00:00Java supports the use of multidimensional arrays.
00:03Just as with simple arrays a multidimensional array contains items all of
00:08the same data type.
00:09And once the sizes of the dimensions of the array have been set you can't
00:13change them at runtime.
00:14I'll show you how to use a multidimensional array in this empty project 2DArrays.
00:21I'll start by declaring the array.
00:23This is going to be a multidimensional array of strings, so I'll start with the
00:28data type followed by brackets, but because this is going to be a
00:32two-dimensional array, I add another pair of brackets.
00:36Next, I assign the array name, I'll call it states.
00:40Then after the equals assignment operator, you put in the new keyword, once
00:45again you put in the data type.
00:47And now just as with simple arrays you declare the array size, but now you're
00:51declaring both the top-level dimension and the child dimension.
00:55I'll set the size of my top-level dimension at three and my child dimension at 2.
01:00Now my goal is to create a primary array of three items each one representing a state.
01:06And then within the secondary array or child array there'll be two items, one
01:11for the name of the state and one for its capitol.
01:14Now I'll set the values.
01:16Use similar syntax to set values.
01:18I'll start with states, bracket, 0, bracket, 0.
01:22The first item in the first primary array. And I'll set that to a value of California.
01:29Next I'll create the second item in the first primary array using the
01:34syntax states, bracket, 0, bracket, 1, and I'll set that to the name of the capitol of
01:41California, Sacramento.
01:44Now I'm going to copy and paste those two lines of code a couple of times.
01:49I'll create two new copies.
01:53And for the second pair, I'll change the primary array item to one.
01:57And for the third pair I'll set the primary array item to two.
02:02Now I'll set the values, the second state will be Oregon, and its capitol is Salem.
02:09And for the third pair I'll use Washington and Olympia.
02:15Now to output these values, I am going to use a loop inside a loop.
02:20I'll use two for loops and I'll manage my output by using a StringBuilder object
02:25to build strings for each combination of state name and capitol.
02:29I'll start by typing the word for and pressing control space and I'll choose
02:34for, iterate over array.
02:37In the primary for loop the integer counter variable will be named i. And
02:42I'll be looping through the primary array, this syntax is the same as for a simple array.
02:47I'm iterating through the primary dimension, the one that has three items.
02:53Then I'll click into the primary for loop and I'll add a secondary for loop.
02:57I'll once again type for and choose iterate over array.
03:02And this time, Eclipse knows that I've already used the variable i, so it uses
03:06the variable j for the secondary counter.
03:10Now to make sure that I'm iterating over the secondary array, I'll place the
03:14cursor after name of the array, states, and I'll add bracket, i, bracket.
03:20So now I have an outer loop and an inner loop.
03:24Now my goal is each time through the loop, I'm going to output the state name
03:28and its capitol all in a single line.
03:32To put it together I'll declare a StringBuilder.
03:33I'll put the declaration and initialization of the StringBuilder in the outer
03:39loop, so then I can manipulate and append to it in the inner loop.
03:43So I'll set the data type to StringBuilder and its variable name to sb and
03:47I'll initialize it.
03:53Within the for loop, I'm simply going to add the values to the StringBuilder
03:58using sb.append and I'll output states, open bracket, i, open bracket, j.
04:07And then after the for loop I'll use a println command to output the
04:11StringBuilder to the console System.out.println.
04:16And I'll just refer directly to the StringBuilder object.
04:18I'm not quite done yet but let's see the results so far.
04:22I'll save and run the application and I'm seeing that I am successfully getting
04:27both the state name and its capitol output to the same line.
04:31So now I need to add a little bit of conditional logic so I can separate those values.
04:38I'll go to the inner loop and I'll add some conditional code.
04:42I'll type if and press control space and choose the if statement and I'll set
04:46the condition to if J has a value of zero.
04:50So if I'm working on the state name then j will have a value of zero.
04:54And before I append the state name, I want to append a little bit of text.
04:59So I'll say sb.append, I'm appending a string to the existing StringBuilder, and
05:04so now the text should say the capitol of and then the name of the state. Let's check that.
05:09The capitol of California, so now, all I have to do is separate those two values
05:15and I'll use an 'else' clause for that.
05:24If I'm just about to append the capitol name to the string builder, I'll put in
05:29a space the word is and another space and let's see how I'm doing.
05:34And now I have sensible output, the capitol California is Sacramento, the
05:39capitol of Oregon is Salem and so on.
05:41So I have successfully organized my data into a multidimensional array.
05:47Now the strength of this approach is that if you know exactly how much data
05:51you're going to be working with, it's a pretty straightforward process to store
05:55it in memory and then access it at runtime.
05:58If on the other hand you have to be able to expand the array or shrink it at
06:02runtime, because you don't know how much data you're going to be dealing with
06:06and you can't just declare the array, and then deal with a fixed size, then you
06:10should start looking at the array list class instead.
06:14And I'll talk about that in another video.
Collapse this transcript
Managing resizable arrays with ArrayList
00:00There are many situations in applications where you need to manage ordered
00:04collections of data.
00:05That means that once you add data to the collection, it stays in the same order
00:10and you can reference the items in the data collection by their index position.
00:13This simple array in Java is useful but it has a downside, it's not resizable at runtime.
00:20And so Java provides a special class for resizable arrays, it's named array list.
00:26You declare an array list as an instance of a class, so it's a complex object.
00:31I'll start in the empty main method of this project ArrayList.
00:34And I'll begin by typing the name of the class ArrayList.
00:38Remembering that Java is case- sensitive, ArrayList is spelled with an
00:42uppercase A and an uppercase L. The ArrayList class is not a member of the java.lang package.
00:48So you must provide an import for it at the top of your code.
00:52After typing in the name of the class, press Ctrl+ Spacebar and Eclipse will
00:56add the import for you.
00:58Eclipse also adds a little bit of additional notation after the class name.
01:02The less than and greater than characters are sometimes known as the diamond operator.
01:07And in Java the diamond operator is used to declare something called a generic.
01:11A generic is a special data type, and in this context it means this array list
01:17will contain items only of a particular data type.
01:20It is possible to create an array list of mixed data, but most of the time we
01:25don't use it for that purpose.
01:26Most of the time array lists and other collections contain items all of the same data type.
01:32You declare which data type by simply setting the data type between the less
01:36than and greater than characters, so this array list could contain integers or
01:41can contain shorts or, as I'm going to do here, it could contain strings or any
01:47other complex object.
01:49So that's the complete data type including the generic declaration.
01:53This will be an array list of strings.
01:56Next as with all declarations I'll provide the variable name I'll call it list,
02:00and then I'll initialize it using the constructor method.
02:03I'll once again type in the name of the class, this will be a constructor method
02:07call, and then I'll press control space again and I'll choose the version of the
02:12array list constructor method that doesn't receive any arguments.
02:16Eclipse looks at the original declaration, and says you said this was going to
02:20be an array list of strings, so when I call the constructor method, I'm going to
02:25use that same string generic declaration and that's correct, I'll complete the
02:30declaration and initialization with the semicolon.
02:34Now I can add items to the list.
02:36I said it was going to contain strings, so anything I pass in must either be a
02:41string or be translatable to a string.
02:44To add items to the array list call the add method.
02:47There are two versions of the add method, you can either pass in a value and it
02:52will be appended to the end of the list or you can pass in an integer, an
02:56index, and the value and then the item will be added in the position that you determine.
03:01I am just going to use the simple add version that accepts the string and I am
03:06going to add three items to the list, California, Oregon and Washington.
03:19I'm going to output the list to the console.
03:22I'll use System.out.printline, and I am just going to add the list object.
03:29The list object will be serialized into a string for me because its two string
03:33method handles that operation automatically.
03:37I'll save and run the application, and I see my items displayed in a comma
03:41delimited list wrapped in square brackets and that's how an array list is
03:46translated automatically.
03:49Now I'm going to add another item.
03:51I'll call list.add and I'll just keep on moving north, I'll add Alaska, and then
03:57I'll copy and paste my print line command and run the application again.
04:02And I see that I've successfully added an item at runtime, something I wouldn't
04:07have been able to do if this were a simple array.
04:11You can add items to an array list at runtime and you can also remove items.
04:15In order to remove items, you can provide either the index position or an object
04:20reference that matches.
04:22In the case of strings, you can remove items simply by providing a matching string.
04:26I am going to remove the first item in the list when I type .remove and press
04:31Ctrl+ Spacebar, I see that there are these two versions of the remove method. It's overloaded.
04:37And I'll use the first version.
04:38I'll provide an index value of zero meaning remove the first item.
04:44I once again copy and paste my print line command and I'll output the list.
04:50And I'll see that after removing the first item California I'm left with a list
04:55of three items starting with Oregon.
04:59Next I'm going to get an item in a particular position in the list.
05:03I'll declare a string variable named state.
05:05In order to get an item from the list, you use the method list.get.
05:10You provide an integer value.
05:13So I'm going to provide a value of one remembering that an array list just like
05:17a simple array starts its numbering at
05:19Zero, this would mean get the second item in the list.
05:22I once again paste in my print line command and I'll change it.
05:27I'll start with the literal "The second state is" and then I'll append state.
05:35I'll save and run, and I get the second state as Washington and that's correct.
05:41You can also find an item in the list.
05:43That is, get its index position by passing an object reference or in the case of
05:48strings by passing in the string value.
05:51So I am going to declare an integer variable named pos, and I'll get its value
05:56by list.indexOf an I'll pass in Alaska.
06:01And then I'll once again use a print line command and l'll output Alaska is at
06:09position and I'll append pos.
06:12I'll run the application and I see Alaska is at position 2, which taking into
06:21consideration the zero-based numbering is at position 2, Oregon position zero,
06:27Washington position one, Alaska position 2.
06:31Take a look at the documentation of the array list for more information about
06:35how you can use this powerful class.
06:38I'll double click the name of the class in my code and go to Dynamic Help and
06:43click the link for its javadocs, expand the help view and then go to the method list.
06:50You'll see that there are methods in they are not just for adding removing
06:53and searching, but also for getting the size of the array list and managing
06:57how it uses its memory.
06:59Use array list to manage ordered collections of data, or you need to resize the
07:04collection at runtime, and where you need to be able to add remove and search
07:08for items, it's an incredibly powerful class that does much more than the simple array.
Collapse this transcript
Managing unordered data with HashMap
00:00Most programming languages have the ability to store unordered collections of
00:04data where you can randomly access items in the collection by their keys.
00:09In some languages these are known as associative arrays, in others structures.
00:14But they always serve the same purpose, an unordered collection of data where
00:18you can get to one item at a time.
00:21In Java, we do this with a class called the HashMap, just like the array list it's a class.
00:27And when you declare it you have to import it.
00:29I'll start in this empty main method in the project HashMap and I'll declare an
00:34instance of the HashMap class.
00:37I'll type in the name of the class and press control space.
00:40Eclipse recognizes that this class must be imported and it adds the import at
00:45the top of the code.
00:47Just as with the array list the HashMap is designed to store data all of the
00:51same type but where the array list means one data type, the HashMap needs two.
00:57Each item in a HashMap will have a key and a value.
01:01Notice that these are represented in the Diamond Operator that is where the
01:04generic is declared using the letters K and V.
01:08In some languages the key always has to be a string, but in Java you can
01:13really use any object.
01:15For simplicity though in this exercise I'll declare both my keys and my
01:19values to be strings.
01:20So I'll type in String, press tab and type String again and then I'll declare
01:27the variable name, map.
01:29Next, I'll instantiate the class.
01:31I'll type in the code = new then once again I'll type the name of the class and
01:36press control space.
01:38There are four different versions of the constructor method for HashMap.
01:42There is one with no arguments, there is one with an initial capacity, and there
01:47are a couple that let you initialize the object in other ways.
01:50I'm going to choose the simplest the one with no arguments.
01:53Eclipse looks at my original declaration and matches my constructor method call.
01:58Now the codes get in little wide so I'll maximize my editor.
02:02I'll add the semicolon at the end of the line and now I've created my first HashMap.
02:08In order to add items to the HashMap use the method named put.
02:14I'll call map.put and I'll see that there's only one version of the put method.
02:19It requires two values, in this case two strings.
02:23And once again using the names of states, I am going to use the name of the
02:27state as the key and its capital as the value.
02:31So I'll type in California then tab over and type in Sacramento.
02:40I'll add another item to the map this will have a state name of Oregon and a
02:46capital of Salem and finally I'll add Washington and Olympia.
02:56Now I'd like to output the contents of the map to the command line.
03:00Just as with the array list, the HashMap has a two string method that will
03:04serialize its contents so it's easy to read.
03:06So I'll use System.out.println and just pass in the map object.
03:12I'll save and run my application and there is the results.
03:17Each item contains a key and a value separated by the equals operator and the
03:23entire list is wrapped in curly braces.
03:27Just as with array lists, HashMaps are resizable at runtime.
03:31So I'll add in yet another State Alaska and its capital Juneau and I'll copy and
03:40paste my printline command.
03:43I'll organize my codes, so that it's all grouped together correctly, and I'll
03:49run the application and there you see that I am successfully adding an item.
03:54You can find an item in a map by referring to the key.
03:58So for example, let's say that I wanted to find the capital of Oregon.
04:03I'll declare a string variable, I'll call it cap and I'll call map.get and I
04:09will pass in the key Oregon.
04:14And then I'll use of printline command and I'll say the capitol of Oregon is and
04:23I'll output the value of cap.
04:26And I'll run the code and I get the capitol of Oregon is Salem, that's correct.
04:31Now once again as I mentioned this second item in the HashMap does not have to
04:35be a string, it could be any kind of complex object.
04:39And as you get into creating your own custom classes that represent data,
04:43you'll find that HashMaps are very useful for storing large collections of data in memory.
04:49Next, I am going to remove an item.
04:52With the array list you removed an item by its index position, but remember a
04:56HashMap isn't in any particular order.
04:58So if you want to remove an item, you refer to its key.
05:02So I'll call map.remove and I'll pass in California and I'll print out the map,
05:10and I've removed California and I'm left with the three remaining states.
05:15Take a look at the documentation for the HashMap class to learn more about it.
05:20I'll select the name of the class and go to Dynamic Help, click for the javadoc
05:24and maximize and go to the method list.
05:27You'll see that there are methods to determine whether a particular item is
05:30available in the list.
05:32Those methods are name contains key and contains value.
05:35There is a method for determining whether the HashMap is empty, it's called
05:39isEmpty and returns a Boolean.
05:41There's put methods, a putAll method, size methods and values methods.
05:47I'll show you how to use a couple of these other methods in a later video when
05:51I show you how to loop through the HashMap using something called an iterator object.
05:56But this should give you enough information to get started with HashMaps storing
06:01unordered data collections in your Java applications.
Collapse this transcript
Looping through collections with iterators
00:00When you loop through a simple array in Java, you typically use a for loop and a
00:04counter variable or a foreach loop.
00:07If you're using the counter variable approach, you increment that variable once
00:11each time through the loop and then use that as an index value.
00:15You could do that with an array list, but the array list and the HashMap
00:19both have more elegant approaches available for iterating or looping through their contents.
00:24There's a pattern called an iterator, an iterator is a special Java class
00:29that's designed to allow you to loop without having to keep track of internal
00:33numbering yourself.
00:34I'll show you how to use iterators on both the array list and the HashMap.
00:39I'm working in a project called iterators, which is a part of this
00:42chapter's exercise files.
00:44The beginning code for this application declares an array list named list and
00:49a HashMap named Map.
00:51Items are added to each of the objects, and then the objects are output to the Console.
00:55I'll run the application and show the results.
01:00Now because these classes are not members of java.lang, at the top of the class
01:04you'll see these import statements, these are critical.
01:08Now, I'll show you how to create an iterator from an array list.
01:12The first step is that you need to know what kind of class you're going to be getting.
01:16For an array list, the iterator is called a list iterator and there was a
01:21special class for it.
01:23I'll declare a class named ListIterator, notice that there are two available,
01:27I'll choose the one from java.util.
01:30And when I declare the data type, just like the array list, I need to declare
01:34the data type of its values.
01:36In this case, it will be string.
01:41I'll give this variable a name of listIterator with a lowercase initial character.
01:47Now to populate its value, I'll call the array list objects listIterator method,
01:53this returns the iterator that references the list values.
01:57I now have an object that I can use to easily loop through the values.
02:01Next I'll use a while loop, I'll type in the keyword while and press control
02:06space and I'll choose this version while loop with condition.
02:11It's up to me to determine what that condition is.
02:15The listIterator object has a method called hasNext.
02:18As long as there is an available next item in the collection, it will return true.
02:23When I have dealt with the last item in the collection, it will return false.
02:27So my condition will be listIterator.hasNext.
02:33Within the code block for the while loop, I'll now create a string variable and
02:38I'll give it a variable name, value.
02:41And in order to get the next item from the iterator, I use this
02:44code listIterator.next.
02:48When you call the next method, it moves internally to the next item within the
02:53iterator and the collection and it returns a reference to the value.
02:57If it's complex object, it's a reference to the object.
03:00Now I can output the value.
03:03I'll use System.out.println and just value.
03:08So that's how use the listIterator when you're working with an array list object.
03:12I'll run the application and show that it's outputting in turn California,
03:16Oregon and Washington.
03:19Because I started from an array list which is an ordered collection, it's
03:23guaranteed that I'll be looping through in the order in which the items were
03:26placed into the list.
03:28So now I'll show you how to do something fairly similar with a HashMap.
03:32Remember that this HashMap has two sets of strings, the keys and the values.
03:38You can iterate through either.
03:40But I'm going to focus on iterating through the keys because once you have a
03:43key, you can get to the value.
03:46With an array list, it's a single step to get to the iterator you need.
03:49But with a HashMap it's two steps.
03:52The first step is to get the collection of strings that you want to loop through
03:56and the second step is to get the iterator.
03:59With the HashMap class you can either get the values using the method values or
04:04you can get a set of values called a key set and that would be the set of keys
04:09California, Oregon and Washington.
04:11When you get the keys, they'll end up in an object called a Set.
04:15Type in the word Set and press Ctrl+ Spacebar and choose the set class from java.util.
04:21And as with all classes in the collections framework set the data type, I'll set it to string.
04:27Now to populate that set of values called map.keySet.
04:31Now as I've been typing, I should've been getting import statements at the top of the code.
04:37If you aren't getting your import statements for any reason, you can easily fix
04:41that by pressing Ctrl + Shift + O on Windows or Command + shift + O on Mac, and
04:47Eclipse will fix up your imports making sure you have the ones you need and
04:51putting them in the right order.
04:53Now let's go back to the code.
04:55I'm missing my variable name here and I'll just call it keys.
04:59Okay now I'm ready to create my iterator.
05:02When you're working with a set, and you want to iterate through its values,
05:06instead of getting a list iterator you'll get a class simply named iterator.
05:10At this point, you might be asking how do I know this?
05:14And the answer is it's in the documentation.
05:17Remember that because Java is so strongly typed, every bit of documentation will
05:21tell you exactly what you're getting.
05:23So I'm going to create a class which is data type as an iterator.
05:28Again make sure you choose the right version, this one should be from java.util,
05:33set the data type, and set the variable name, I'll call it iterator.
05:38And then get the value of the iterator from keys.iterator the method.
05:43Now I'm ready to loop.
05:45I'll go to the next line and type while and press Ctrl+ Spacebar once again I'll
05:51choose while loop with condition.
05:53And the programming interfaces of the iterator and the list iterator are exactly the same.
05:59So I'll be able to use while iterator.hasNext.
06:06And within the while loop, I'll once again declare a string, I'll set its
06:10name to a value, I'll get its value from iterator.next, again following
06:15exactly the same syntax that I did with the listIterator and then I'll output
06:20the value System.out.println.
06:26I'll run the application and I get California, Oregon and Washington.
06:31But remember, those key values came from a HashMap, but remember those strings
06:37are keys in a HashMap and each key has an associated value, so I'm going to do
06:43this with a little bit more complexity.
06:45I'll expand my editor, so I have a little bit more width to work with, and I'll
06:50add before the value the capital of, and then the value, and then after that I
06:59add another plus operator and a space is, and then after another space and
07:05another quote, another plus operator and then map.get(value).
07:13So the whole purpose of this was to loop through the keys, so that I could then
07:17address the keys and their associated values, here is the result the capitol of
07:22California is Sacramento and so on.
07:26Iterators always work on collections of single values.
07:30When you're working with a HashMap you're working with a collection of keys
07:33and associated values.
07:35So the first step is to extract the keys and the next step is to get the
07:39iterator so you can loop through the contents.
07:42Iterators are a valuable part of what's known as the collections framework in Java.
07:47They're designed to make it very easy to loop through the contents of your data
07:51in memory without having to keep track of your own numeric counter variables or
07:56use your own handcrafted strategies.
Collapse this transcript
9. Creating Custom Classes
Understanding encapsulation
00:00The principles of object-oriented programming depend on a few basic concepts and
00:05one of the most important concepts is encapsulation.
00:08Encapsulation means that you're packaging complex functionality to make it easy to use.
00:14When you first create Java applications, most new programmers will put all of
00:18their code into the main method, and I've been doing that so far in this course.
00:23But you quickly find out as your applications get larger and gain features that
00:27putting all the code into one place makes that code very tough to manage.
00:32So instead, you want to break the code out into individual classes, grouping the
00:37functionality, however, the logic dictates for your application.
00:41When you do this, you have some big advantages.
00:44One advantage is that you can restrict access, one part of the application
00:48might be able to use a particular function or another part of the application
00:51wouldn't be allowed.
00:53If you put all the code in one place, that's tough to restrict.
00:56When you break it apart, it's easier.
00:59Similarly, when you store data in a Java class, if you wrap it up as
01:04encapsulated data, you have the option of hiding how it's being stored.
01:09You don't have to tell the user of the data, that is a programmer who's calling
01:13a particular class, whether that data is being stored as an array, a collection
01:18of some kind, or any other object.
01:21You simply provide methods that the user of that class can call and all the
01:25complexity is hidden.
01:26One way to think about encapsulation is to look at an analogy of the 3D world.
01:32Let's take an example of an industrial machine, in this case, an olive press.
01:37In order to use an olive press, if you were asked to know everything about how
01:41the press worked, it would be very difficult to get started.
01:45If you had to know which direction each gear was going to turn, which order each
01:49of the pressing arms is going to come down, and how much oil might come out of
01:53each individual olive, it would be very difficult to get any work done at all.
01:57So most real industrial machines are encapsulated and that means that they wrap
02:03up their complexity in a big box and then you can simply add the olives in the
02:08case of an olive press, perhaps press a button and out comes the olive oil.
02:13It's much easier for a new user to understand how to use the olive press.
02:18There is still complexity, there are still gears, there are still pressing arms,
02:22there are still calculations to be done, but the whole process of getting
02:26started with the machine is greatly simplified.
02:28Code-encapsulation works the same way.
02:32Let's take an example of non-encapsulated code.
02:35Again, if you're a new Java developer, you might be tempted to put all the code
02:39for the application in the main method of your primary class.
02:43In this example, I'm creating an array and then I'm creating instances of two
02:48other classes, and then I'm looping through the array and doing something with it.
02:53This little bit of code might not look too daunting but imagine if the code
02:57had expanded so you had literally hundreds or thousands of lines of code all in one place.
03:04Then somebody comes along and says would you add a new feature to the
03:07application or I found a bug and it needs to be fixed.
03:11This sort of monolithic code is very, very difficult to manage.
03:15So in Java applications, you're encouraged from the beginning to break your
03:19applications down into small pieces.
03:22So for example, I may take some of that code and move it off into its own custom class.
03:28I might create a class called OlivePress.
03:31Within the OlivePress class, I might declare a private field or a private variable.
03:37In this case, it's an array of olive objects named olives, and then I might
03:42have a constructor method that allows me to pass that data in as I create an
03:46instance of the class.
03:48Then I might have a method called getOil that can be called from anywhere in the application.
03:53This method would encapsulate the complexity of how you have to loop through the
03:57list of olives, crush them and add them to the olive oil.
04:01The developer of this class needs to understand and deal with the complexity,
04:06but the user of the class only has to call the getOil method and so the primary
04:11code of the application can now be very brief and very easy to read.
04:15I would create an instance of the OlivePress, I'd pass in my olives, I'd call
04:20the getOil method and I get back the oil.
04:23All of the mechanics and the complexity of how the operation happened would be hidden from me.
04:29All I need to know is call the method, get the result.
04:33So that's how encapsulation works.
04:35The benefits of encapsulation include that you can break your functionality down
04:40into small maintainable units.
04:42It's much easier to fix bugs when you're looking at a small amount of code and
04:47much more difficult when you're looking at a massive amount of code.
04:51So encapsulation helps you maintain the application over the long-term.
04:55You can also use encapsulation to group functionality and data together.
04:59In Java, as with most object-oriented languages, you can define classes that
05:04group the data and the functionality that manages that data together or you can
05:09create individual classes;
05:11one for the data, one for the functionality, and bind them together using a
05:15process called loose coupling.
05:18And finally, all of this together means that you can test your software and
05:23maintain it over the long- term at a granular level.
05:26Rather than looking at your application as one huge block of code, you're
05:31breaking it down into small manageable pieces.
05:34So in the rest of this chapter, I'm going to talk about the mechanics of this in Java.
05:39How do you create your own custom classes?
05:42How do you move code from a monolithic application and break it down
05:45into smaller pieces?
05:47And how do you declare classes that serve as utility libraries or that are
05:52their 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:00Complete applications in Java typically consist of more than one class.
00:05You'll have a starting class that has the main method for a console application,
00:09but then you have all sorts of supporting classes that either encapsulates data
00:13or functionality or both.
00:15For this exercise, I'll show you a simple strategy for taking an application
00:20where all the code is in a single class or a single file and extracting it out
00:25to multiple files, so it's easier to keep track of and maintain.
00:29I'll start with this beginning Calculator application.
00:32This is a version of the Calculator application that I worked on in a previous
00:35chapter of the course.
00:37It accepts two numeric values and then asks the user what operation they want to do;
00:42addition, subtraction, and so on.
00:44Right now, all of the code for the application is in a single file.
00:48There is code to get the input and to figure out what to do, but then all of the
00:53supporting methods are also in the primary class.
00:56In a well-structured Java application, you would extract a lot of this code out
01:00to separate classes.
01:02It's up to you as the developer and the application architect to figure out
01:06where the code goes and how to group it together.
01:09I'll show you a strategy for this application, where I take all of the
01:12mathematical operations and group them together into one class and then I'll
01:16take the functionality that's accepting input from the command line and put
01:20it into another class.
01:21The goal will be to create classes that are reusable.
01:25I'll start in the CustomClasses project and I'm going to create two new classes.
01:30I'll right-click on the default package and choose New>Class.
01:35The first class will be SimpleMath.
01:38You could name the class anything you want, but make sure you use an uppercase
01:42initial character and that you don't put in any spaces or special characters.
01:47This will not be the starting class so don't check the option to create a main method.
01:52You'll only be able to call this class from other classes of the application.
01:57Click Finish, and you end up with a very simple class structure.
02:02The class is public and the name is SimpleMath.
02:06When you declare your own classes, the name of the public class must match the
02:11name of the Java file and you can only have one public class in each Java file.
02:16It is possible to declare multiple classes in a single Java file, but any other
02:21classes can't be public and will only be accessible from within the code in this file.
02:25I am going to have just one class in this file and I'm going to put all of my
02:29mathematical operation methods into it.
02:32So I'll go back to the application, I'll scroll down, and I'll locate my divide,
02:37multiply, subtract, and add methods.
02:40I'll select all four of them and I'll cut them to the clipboard.
02:44Then I'll go to SimpleMath.java, I'll place the cursor inside the class
02:49declaration, and paste in the methods.
02:55Now because I'm going to be calling these methods from another class, I can no
02:58longer have them marked as private.
03:01They must be marked public or I can just remove the access modifier entirely.
03:06I like to be explicit in my access modifiers though, so I am going to change
03:09private to public on all four methods.
03:12I'll save my changes to this file and go back to the application, and now I'll
03:24go to the switch statement where I'm calling those methods.
03:27I now have errors telling me that these methods are undefined.
03:31I'll fix this by adding the name of the class SimpleMath as a prefix to the
03:37call to the method.
03:39I'll type Simp and press Ctrl+Space and there is my new class, SimpleMath.
03:44I'll separate the name of the class and the method name with a dot.
03:48Notice when I type in the dot, the four available methods are shown
03:52automatically and I can easily call them where needed.
03:55Now I am going to copy SimpleMath and the dot to the clipboard, and I'll paste
04:00that string in to each of the other three method calls.
04:03I'll save my changes and I'll run the application, I'll enter a value, I'll
04:10enter another value, I'll choose subtraction this time, and everything still works.
04:17So now I've successfully refactored my application.
04:21I've extracted the code that's not a part of the main operation and put it in
04:24its own separate class.
04:26Let's do the same thing with the input function.
04:29Once again, I'm going to create a new class, I'll right click and choose
04:33New>Class, and I'll call this InputHelper.
04:38Once again making sure I don't have the main method selected, I'll click Finish.
04:42I'll go back to the main application, I'll scroll down to the bottom and I'll
04:47grab this getInput method, make sure you get all of the method including the
04:51opening and closing braces, I'll cut that code to the clipboard, I'll go to my
04:57new class, place the cursor inside the class declaration, and paste.
05:02Notice that when I paste the code into the new class, Eclipse automatically
05:06adds import statements for the BufferedReader and InputStreamReader classes that I need.
05:12Just as I did with the methods in the SimpleMath class, I'll change this access
05:16modifier from private to public.
05:18I'll save my changes to this file and go back to the main application, and I'll
05:23go up to the calls to the getInput method.
05:25I'll type in input and press Ctrl+ Space and I'll choose my new class,
05:31InputHelper and add the dot.
05:34I'll select and copy the InputHelper .string and paste that in twice and
05:42I'll save my changes.
05:44Down to the bottom, I get a warning, The import java.io is never used.
05:49That import statement was handling the classes that deal with input, but because
05:54I've moved the usage of those classes into my own separate custom class, I no
05:58longer need the import statement.
06:00I can either delete it explicitly or I can let Eclipse do it for me.
06:04To do it in Eclipse, hold down the Ctrl and Shift keys on Windows or the
06:09Command and Shift keys on Mac and press the letter O, and that is something
06:13called organizing imports.
06:16That's a great trick, because it will not only get rid of the imports that you
06:20don't need, but it will also add or propose the imports that you do need and
06:25alphabetize and otherwise organize them for you.
06:27I'll save my changes and run the application again and I'll test it again with
06:32values of 10, 3 and this time I'll multiply and everything still works.
06:41By organizing your application in smaller classes, it makes it easier to
06:45maintain your work over time, and you'll be tempted to tune and refactor your
06:50application as you go along.
06:52Eclipse will help you with this in many ways.
06:55Let's say, for example, that you end up not liking the name of this class
06:59SimpleMath, and you think well, I'd like to change the name of that class so
07:03that it matches InputHelper, I'd like it really to be named MathHelper.
07:07But it would be a real pain to go through and try to search and replace for
07:10every occurrence of this class name.
07:12I have it here and I have it four times in the main method.
07:15Well, this kind of class renaming is called refactoring and it's
07:19incredibly simple in Eclipse.
07:22Go to the class in your package Explorer, right click, choose Refactor and then Rename.
07:30Assign the new name of the class and I'm going to call it MathHelper.
07:35Then click Finish and you'll see that the name of the class is updated in all
07:39the calls in the main application, the name of the file is changed, and the name
07:45of the class in the class declaration is changed as well.
07:48At the minimum, you can use your custom classes to organize the code, bringing
07:53together methods that execute similar operations and moving them out of the main
07:57application file that has your main method.
08:00How you design the application and how you separate the code is completely up to
08:05you, but Java gives you all the tools to do it.
Collapse this transcript
Organizing classes with packages
00:00So far in this course, I've been creating applications where every class
00:04was placed in the root folder of its project, but Java developers very
00:08seldom actually do that.
00:10Most classes in a Java application are placed in packages or subfolders of the project.
00:16Because of the way Java application is structured it could have dozens, hundreds
00:20or even thousands of classes, and as an application gets larger it's very
00:25important to organize these classes into groups.
00:27We call these groups packages but they represent actual physical folders on disk.
00:33I'm going to start by creating a sub package to store my helper classes.
00:37I'm working in a version of the Calculator application where all of the classes
00:41are stored in the root folder or default package and I'm first going to create a
00:45custom package and then move my helper classes into it.
00:49I'll go to the default package in the package Explorer view, right-click
00:54and choose New>Package.
00:56Initially, I'm going to use a shallow package structure meaning that each
01:00package will be just a subfolder of the root.
01:03So I'm going to call this package, helpers.
01:07Now, when I create a package in Eclipse, I am actually creating a physical
01:11folder on disk as well.
01:13Next, I'm going to move my helper classes into the helpers package.
01:17I'll do this one at a time.
01:19I'll start with InputHelper.java, I'll right-click on the file and I'll
01:24choose Refactor>Move.
01:27I'll select my new helpers package and click OK.
01:31The file is moved into the package and a couple of changes are made to the code.
01:36First of all, in the InputHelper.java file, a new package declaration is added
01:41to the top of the file.
01:43This is a requirement in Java.
01:45When a class is anywhere but the default package, it has to be declared that way in the code.
01:51The syntax is the keyword package and then the name of the package ending with a semicolon.
01:57Also, in the main application, where I am using that class, a new import
02:01statement has been added to the top of that code.
02:04Once again, this is a requirement.
02:06If the class isn't a member of the same package as the one that's calling it,
02:09then it has to be imported.
02:12In this case, I am referring not just to the package but also the class name,
02:16helpers.InputHelper.
02:18Now I'll move my second helper class.
02:21I'll go to MathHelper.java in the package Explorer, right-click and choose
02:25Refactor>Move and once again, I'll choose the helpers package and click OK.
02:32My main application now has imports for both helper classes and both InputHelper
02:37and MathHelper have the package declaration.
02:41I'll run the application, I'll click the Run button and if prompted, I'll
02:45choose Java Application.
02:48I'll enter some values and an operation and everything is working just fine.
02:53So organizing your classes into packages doesn't do anything to change the
02:56functionality for application;
02:59it just gives you a way of organizing the code so you can find it more easily later on.
03:03In large scale Java development environments package names typically are
03:07structured using a prefix of the company's domain in reverse domain order.
03:12So for example, if a company is named lynda.com then you would start off with a
03:17package prefix of com.lynda.
03:20The reason to do this is so that you can eliminate any possible conflicts with
03:24other classes in the Java environment.
03:27Remember that Java compilation doesn't create a single monolithic file.
03:32Instead your runtime application consists of a whole bunch of compiled classes
03:37and it's up to the JVM to figure out which classes needed at runtime.
03:41By using reverse domain notation in your classes, you guarantee
03:44universal uniqueness.
03:46So I'm going to do a little bit more refactoring.
03:49I'll go to my default package and once again I'll add a new package, and I'll
03:53name this package com.lynda.calc.
03:56So I start off with the domain name first and then something to say which
04:01application I'm working on.
04:02You can add more levels to your packages, it's up to you.
04:05I'll click Finish, then I'll go to my Calculator class, I'll right click and
04:12choose Refactor>Move and I'll choose com.lynda.calc.
04:17Notice that because I have dot notation, each of these is seen as its
04:21own individual package.
04:23I won't be placing anything in com or com.lynda;
04:27those are just prefixes for the way I am organizing my code.
04:30But my main class will go in this calc package.
04:34I'll click OK and my source code file is moved and I'll look at my code and I'll
04:39see that the package declaration has been added at the top of the code.
04:44Next, I'll rename my helpers package, I'll right-click, I'll choose
04:49Refactor>Rename and I'll change the package name to com.lynda.calc.helpers.
04:56I am still distinguishing this package from the package that contains my main
05:01application and keeping all my helper classes in their own unique package.
05:05But they're all deeply buried now in my uniquely named primary package.
05:11This time I'll choose Preview and show you that Eclipse can show you what your
05:15code will look like before and after refactoring.
05:19I'll click OK and the change is made.
05:23My main application still has the imports for the two classes, InputHelper and MathHelper.
05:28If I prefer, I can change these and just put in an asterisk and take out the
05:33second import, and this now means import everything in that package.
05:39If you have classes in the package that you're not using that's okay;
05:43it won't affect performance.
05:45But note that if you use the Organize Imports tool in Eclipse that's the tool
05:49that kicks in when you press Ctrl+Shift+ O on Windows or Command+Shift+O on Mac,
05:54Eclipse will convert from an asterisk , a wildcard import to explicit imports
05:59for each class that you're using.
06:01That's the preferred approach for Java development because it helps you know
06:05by looking at the top of your code exactly which classes are actually in use
06:09in your application.
06:11I'll go take look at the InputHelper and MathHelper classes and I'll see that
06:16the package declarations have been modified there.
06:19And finally, I'll save everything and run the application again and make sure I
06:22haven't broken anything.
06:24I'll enter the numeric value and another numeric value and this time, I'll
06:29multiply and I get back a correct answer.
06:33So, organizing your coding packages is a good thing to do.
06:37As your applications become larger and more complex and you have more and
06:41more classes, you'll find organization of your classes through packages to be invaluable.
Collapse this transcript
Creating and using instance methods
00:00When you declare a method in a Java application, you can declare it either as a
00:05class method or an instance method.
00:07A class method is a method like the ones I've been using so far, it's called
00:11from the definition of the class.
00:13An instance method in contrast is called from an instance of the class or an object.
00:18Typically, you can use class methods when you're building up a library, say, of
00:22utility functions and you are going to pass in all the values that the method is
00:26going to operate on as arguments passed into the method when it's called.
00:30But when you start working with more complex objects, objects that have
00:33persistent data in them, you are going to want to learn how to use instance methods.
00:38For this exercise, I'm working a project named InstanceMethods that has three classes.
00:43All three classes are starting off pretty empty.
00:46The Main class has a main method that doesn't do anything yet and there's
00:49an OlivePress class and an Olive class, and again, they don't have any functionality yet.
00:55I'm going to design this Olive class so that it can be instantiated and then its
01:00methods can be called.
01:01I'll place the cursor inside the class declaration.
01:04To define in the instance method, you use the same sort of signature as you do
01:08with a class method, but you don't put in the static keyword.
01:12Remember, the Main method has this word, static, and all of the methods
01:15that I've defined throughout this course up to this point have also used the word static.
01:20The word static means this is a class method that can be called from the class definition.
01:25If you drop out the word, static, it's an instance method.
01:28Just as with class method you start with an access modifier;
01:31public if you want to method to be called from anywhere in the application;
01:35private if it's only available within the class;
01:37and protected if it's available within this class or any of its subclasses.
01:42I'll declare this method as public.
01:44Next you need a return type.
01:46Initially, this method will return void or nothing and then the method name
01:50which I'll call crush.
01:52Add in the parentheses at the end of the method name and a pair of braces and
01:56now you can add code to implement the method.
01:58When an Olive is crushed, we'll say it hurts, so the Olive says ouch.
02:02So I'll output using system.out.println the word ouch and I'll save my changes
02:09and that's my first instance method.
02:11Now I'll go back to the main application.
02:14Within the main application, in order to call that method, I need to create an
02:18instance of the Olive class.
02:20So I'll declare a variable.
02:22I'll assign a data type of Olive, the name of the class.
02:25Notice that as I type the name of the class, I get the little squiggly line
02:28underneath the class name and that tells me that the class currently is
02:32being seen as undefined.
02:33The compiler doesn't know where it is.
02:36So I'll press Ctrl+Space, I'll see a listing of all the classes that start with
02:40the word Olive and I'll choose Olive.
02:42An Eclipse adds a required import statement at the top of the code.
02:45Even though this is my own class and my own application, the rules for imports
02:50are the same as with the Java class library.
02:52If the class that I'm using is in a package other than the one that contains the
02:56current class, I must import it.
02:58Next, I'll declare the variable name which I'll set as olive, all lowercase, and
03:03I'll instantiate using new Olive.
03:06Now you may be thinking where is that method.
03:09If I go back to Olive.java notice that there is no definition of a constructor
03:14method or any other method that matches the class name.
03:17The answer is that the Java compiler always adds a no arguments constructor
03:22method, a method that can be used to create an instance of the class.
03:25If you don't define one, one is defined for you and that's what I'm calling here.
03:30So I have created an instance of the Olive class and now I'll call its method
03:34using olive., and when I type the dot, Eclipse shows me the list of methods
03:38that are available.
03:39The crush method is at the top of the list.
03:42All of the other methods that you see here are defined as a part of the class object.
03:47I'll talk later in the course about inheritance, but basically all these methods
03:51are coming from a class name object.
03:53That is the super class of other classes in Java.
03:56I'll call the crush method, I'll save my changes and run the application and
04:01there is the output.
04:02I call the objects instance method and it was responsible for outputting that
04:06string to the console.
04:08Now I'll create one more instance method.
04:10So far my application knows how to crush a single olive, but clearly that's not
04:14enough to get enough olive oil.
04:16So now, I'm going to create an OlivePress class and once again, just like the
04:21olive, it will be designed to be instantiated.
04:23I'll go to OlivePress.java and I'll create a public method named getOil.
04:29Once again, it will return void.
04:30The getOil method will receive an array of olive objects and it will loop
04:35through the olives and crush them one at a time.
04:38So I'll go to my method getOil and I'll design it to receive an array of olives.
04:43I'll type in the word, olive, I'll press Ctrl+Space and choose olive, that will
04:46add the required import statement.
04:48I'll add the opening and closing brackets to indicate that I'm receiving an
04:52array of olives and I'll name the array, Olives.
04:56Now within the method, I'll loop through the array.
04:58I'll type for and press Ctrl+Space.
05:01I'll choose the for each syntax and I'm saying for each olive in the
05:05olives array do something.
05:07And once again just like I'm doing in the main application right now, I'll call olive.crush.
05:12I'll save those changes;
05:13I'll go back to the main application class and change it so that it's now going
05:17to crush a whole bunch of olives.
05:19I'll go back to main.java and I'm going to take out this code.
05:23I don't need that anymore and I'm going to declare an array of olives.
05:27Once again, I'll press Ctrl+Space and choose olive, I already have my import
05:31statement at the top so I don't need re-declare it.
05:34I'll declare this as an array and name it olives, and then I'll use the syntax
05:39to initialize the array with values.
05:41I'll start with a brace and then newOlive(), newOlive(), and newOlive().
05:47So I am creating three anonymous objects.
05:52I am not assigning variable names to them;
05:54I'm just creating them and passing them into the array, and then immediately
05:58assigning the entire array to the olives array.
06:01Next, I'll create an instance of the OlivePress.
06:05I'll type in OlivePress, I'll press Ctrl+ Space that adds an import statement for
06:09that class, I'll name it press and I'll instantiate it, once again using the
06:15constructor method that the Java compiler adds for me, and finally, I'll call
06:19press.getOil and I'll pass in the olives array.
06:23I'll make sure to add the semicolon at the end of the line and I'll run the
06:26application and because I created three olives in the array, I get the
06:31word, ouch, three times.
06:33So this is how instance methods work.
06:35Don't put in the static keyword and it becomes an instance method that's called
06:39from an instance of the class rather than from the class definition.
06:43Once you know how to create and use instance methods, you are on your way to
06:46creating full-blown objects that incorporate both methods that is
06:50functionality and data.
Collapse this transcript
Storing data in instance variables
00:01When you declare your own custom classes you can assign them instance variables.
00:07Instance variables in Java are known as fields and they are variables that are
00:10assigned at the class level and are available to the entire class and optionally
00:14to the rest of the application.
00:16I'm working in a version of the application named InstanceVariables that's in
00:20this chapter's exercise files.
00:22It starts within Olive class that has a public method named crush.
00:26Right now it's just outputting a simple string, but I'm going to define a set of
00:30instance variables in this class that can be used later on.
00:33To declare an instance variable or a field you place the cursor inside the
00:37class definition and within the class definition, you declare each variable
00:41with an access modifier, a data type, and a name and optionally, you can set an initial value.
00:47So for example, I'll start with public string, meaning I am declaring a
00:51variable or a field that can be accessed from anywhere in the application and
00:56that will contain a string.
00:57I'll give the field a name of name, and I'll set it initially to a value of Kalamata.
01:03So that's the type of olive that I'm working with.
01:05I'll let another string variable, this one will be named flavor and it will be
01:10a flavor of grassy.
01:11According to Wikipedia, Kalamata olives have a grassy flavor.
01:15Next, I'll also declare a variable named color.
01:18Now rather than setting this as a string, I'll use long integer.
01:22Colors can be translated into long integers using the same hexadecimal values
01:27that you might use in HTML for cascading style sheets.
01:30So I'll call this public, long, color and I'll set it to a value of 0x000000 or
01:39Black, and finally, I'll create a variable called oil.
01:44I'll set this as an integer and I'll give it a value of 3.
01:48This is random, what I'm saying is that when I crush a Kalamata olive, I'm
01:53getting 3 ml of oil, that's almost certainly incorrect in the real world, but it
01:58will work for this example.
01:59So now these variables or fields are available to the entire application.
02:04Eventually, I'm going to hide the actual data within the application, but
02:08for now this will work.
02:09I'll save my changes and go to the main application where I'm creating an array of olives.
02:15Now I'm going to re-factor or change the structure of the application so that
02:20instead of creating an array of Olives that's fixed at runtime I'm going to
02:24instead use an array list and this will allow me to resize the array as needed.
02:29I'll go into the Main method and add some extra whitespace.
02:33I'll create an ArrayList after typing ArrayList, I'll press Ctrl+Space and that
02:37will add the required import, and I'll set the array list as containing
02:41instances of the Olive class, and I'll name it olives.
02:45There'll be a conflict because I'm already using that name further down, but
02:49that's okay, I'll take care of that in a moment.
02:52Next, I'll instantiate the array list.
02:54Now, I'm going to create three instances of the Olive class.
02:58I'll start by declaring a single variable, Olive olive.
03:03I'm not instantiating it yet;
03:05I'm declaring it once so that I can reuse that reference three times.
03:09Next, I'll say olive = new Olive and I'll output the name of the olive that I
03:15just created using system.out.println( olive.name) and then I'll add the olive to
03:22the array list using olives.add(olive).
03:26I'm done with this array, I'll get rid of it and then I'll copy these three
03:30lines of code and paste them in twice.
03:32Now I'm obviously making this code more verbose than it really needs to be, but
03:36my goal here is to show you that because I declared a public field in the olive
03:40class, I can reference it from within the main application.
03:44I'll save my changes and run the application and I see some errors.
03:49I'll go down to my errors list and double-click and it tells me that the getOil
03:52method is expecting an array, but I'm trying to pass in array list.
03:56So I'll jump to that method and here's a great little Eclipse shortcut.
04:00Now that my methods are being scattered across multiple classes, I need to be
04:04able to move among them more easily.
04:05Eclipse lets you click on a method name and jump to the reference and here's the shortcut.
04:11Hold down the Ctrl key on Windows or the Command key on Mac, move the
04:15cursor over the method, and choose Open Declaration and that will take you
04:19to the method itself.
04:20Now change the method declaration so that it's receiving an array list of Olives.
04:26Save and run the application and you'll see that you're looping through the
04:30array list using the same syntax as you did with the array earlier.
04:34You don't need to create an iterator for this;
04:36if all you need to do is look through, you can simply use it for each command.
04:40So as I create the Kalamata olives, I am outputting the names of the olives and
04:45as I crush them, I'm still getting ouch.
04:48Now let's go ahead and fix that.
04:49We need to be more specific.
04:51I'll go to the Olive class and I'm going to change how the crush method behaves.
04:55I'm going to change it to return the amount of oil that just got crushed.
05:00I'll change the data type from void to int and I'll add return oil.
05:05I'll save the changes there and go to OlivePress.
05:08Within the OlivePress class and within its getOil method, I'll declare an
05:12integer variable named oil and I'll set it a value of 0.
05:16Within the for loop, I'll increment the amount of oil that I've received
05:20using oil += Olive.crush.
05:23I'll jump to the crush method.
05:25Remember that I'm returning the total amount of oil which is this integer value.
05:30I'll come back to the OlivePress and after the for loop, I'll output the amount
05:35of oil that I just received.
05:37The string will be, You got, and then the amount of oil and then units of oil.
05:42I'll save and run the application and it tells me, I got 9 units of oil three times three.
05:48Finally I'll go back to Olive.
05:51You might have noticed that at no point was I actually accessing the oil field
05:55from the main application.
05:56So I don't need to make this field public and this is the first time I'm going
06:00to talk about hiding data within a Java application.
06:04In a Java application, you should only make data accessible that must be
06:08accessible to the rest of the application.
06:09If you can hide the data within a class, you should do it.
06:13So the only method that's actually accessing this value at this point is a
06:17method within the class and I can make this field private.
06:20I'll save and run the application again and it still works.
06:24So that's a look at how to declare instance variables or fields in a Java class.
06:29These are persistent data values.
06:31When you create the instance of the class, the object, these data values will
06:35persist as long as the object persists in memory.
06:38I've shown you how to make those variables either public or private.
06:41If you make them public, if you need to be able to access those values from the
06:45rest of the application or private, if they're only used within the class, and
06:49there is also the access modifier protected, but we won't need that until we
06:54start dealing with inheritance.
Collapse this transcript
Using constructor methods
00:00Whenever you define your own custom class it has a constructor method.
00:04A constructor method is a special kind of method that's called when you create
00:08an instance of the class, and as I showed earlier if you create a class that
00:12doesn't have an explicit constructor method, such as this Olive class, the Java
00:16compiler adds a no arguments constructor method for you.
00:20You can create your own custom constructor method though if you prefer.
00:23I'm working in a version of the project called constructors that in this
00:27Chapter's Exercise Files.
00:29Now, place the cursor after the field declarations and before the custom method crush.
00:34A constructor method looks like this.
00:36You start with the keyword public and then the name of the Method is always the
00:40same as the name of the class.
00:42Constructor methods can be designed to receive arguments, but if you're going to
00:45have any constructor methods and you want to be able to call the constructor
00:49method with no arguments then you need to define it explicitly.
00:52So I am going to create a constructor method and within the constructor method
00:57I'll just output a message to show when the method is being called.
01:00I'll output constructor of and then I'll append the value of the object name field.
01:06When you refer to the name field prefix it with the word this, this in Java
01:12means the current instance of the current class.
01:16So I'll type in this and I'll see a listing of all the custom fields that I've
01:19defined and I'll choose name.
01:22I'll Save my changes and Run the application, if prompted with the Run As dialog
01:27I'll click Java application and click OK and I see constructor of Kalamata each
01:32time I create an instance of the class.
01:36Now, notice with constructor methods, you don't do any return type.
01:40You don't put in the keyword void, because constructor methods never return a
01:44value, so you put in the accessor method which should always be public, and the
01:48name of the class, and you're done.
01:50Now as with other kinds of methods you can overload a constructor method, that
01:54is, you can have more than one version of it, as long as you distinguish them by
01:58the numbers or data type of the arguments.
02:01I'll move the cursor down below the no arguments constructor method, and this
02:05time I'm going to ask Eclipse to generate a constructor method for me that
02:09accepts values into the constructor method and passes those values to the fields
02:14that I've already defined.
02:14I'll right click in the empty space, then I'll go to the Source menu and I'll
02:20select Generate Constructor using fields.
02:24Eclipse shows me all the fields that are a part of this class name,
02:28flavor, color, and oil.
02:31I'm going to create a constructor method that just receives the value of oil
02:35and they'll click OK. Here's the result.
02:39The constructor method that's been generated receives an argument named oil data
02:43type as an integer the same as the field that matches.
02:46Skipping over the next line, the call to the super method, which I'll explain
02:49in a moment, the method takes the argument that's been passed in and passes it to the field.
02:55this.oil means the field or instance variable and oil by itself means the argument.
03:01If you don't put in the keyword this, prefixing the variable name, you're
03:05talking about the argument.
03:07Now the super method isn't really needed in this situation.
03:11Super opening closing parentheses means call the constructor method of the superclass.
03:17We haven't talked about inheritance yet, and I'll described as more closely when
03:20we talk about inheritance later on, but this basically means call the
03:24constructor method of the class that this class is inherited from.
03:28I don't need that bit of code, I'm going to delete it, and I'll close ups
03:31some of this whitespace.
03:33Now I'll Save the changes to this file and go back to the main application
03:37and I'll go to the constructor methods that I'm already calling when I
03:40construct each of the olives.
03:42The default value for the oilfield in the Olive class is 3, so when I run the
03:47application right now, I end up with 9 units of oil, 3 times 3, but because I've
03:53created a constructor method for the class, I can now pass in the number of
03:57units of oil when I construct the class, when I instantiate it.
04:01So I'll set these values now to 2, 1 and 2.
04:05I'll Save the changes and notice that Eclipse says that's fine.
04:09There's a constructor method that's looking for integer argument and that's
04:13what you've passed in.
04:14I'll run the application and this time, I don't see the output telling me that
04:18I've constructed the class, but I get 5 units of oil.
04:222+1+2, let's go back again and look at the class code.
04:27So now I have more than one constructor method, one that accepts no arguments
04:32and one that accepts an integer, and this is a very common pattern when you're
04:36creating your own custom classes.
04:38You can overload your constructor methods can have multiple versions as long as
04:42you distinguish them by the number or data types of the arguments, and then it's
04:46up to the Java Virtual Machine and the Compiler to figure out which of the
04:50constructor methods will be called.
04:52I recommend when you're creating your own custom classes that you always create
04:55a no arguments constructor, even if it's not going to do anything.
04:59That will make it very clear in your code that a no arguments constructor is
05:03executing the default action that is nothing.
05:06So I'll go back to olivePress.java and I will place the cursor inside the class
05:10declaration, make a little bit of whitespace, and I'll create a constructor
05:15method for this class as well.
05:17I'll close up the braces to show very clearly that it's an empty, no
05:21arguments constructor method.
05:23Again, this is not required, but it is recommended, so that when other
05:27developers look at your code they can clearly see the no arguments constructor,
05:30and see that it's not going to do anything.
05:33That's last change I will make to this application, so I'll run the application
05:37again, and show that it still works fine.
Collapse this transcript
Managing instance data with getter and setter methods
00:00When you're working with object- oriented development patterns a lot of
00:04developers feel that fields should always be private and their data should only
00:09be accessed through what we call getter and setter methods.
00:12In some languages there is a port for implicit setters and getters.
00:16For example, in both C# and in ActionScript 3, you can use the words set and
00:22get before method names as separate words and then you can refer to those
00:26methods as properties.
00:28In the Java language, in the absence of some other framework, you can only
00:32use explicit setters and getters, that is methods that start with the word
00:37get as part of the method name, but these are so common that there is support
00:41for generating these kinds of methods in the development environment such as Eclipse.
00:45I'm working in the class Olive which is a member of the project getters and setters.
00:49This is class has 4 fields, 2 strings, one long in one end, and 3 of the fields
00:56are public and one private.
00:58To generate getter and setter methods, place the cursor anywhere in the class.
01:03You don't have to select the code as I've shown here, and then you can right
01:07click and choose Source or you can go to the main Menu and choose Source.
01:12From there choose Generate Getters and Setters.
01:17In this dialog box choose the field for which you want to Generate Getter
01:21and Setter methods.
01:22For this first example, I'll only choose the oilfield.
01:27Next, determined the insertion point, where do you want to put the new code.
01:31If you choose first member, the code will go right after the class declaration,
01:35and last member will put it at the end.
01:38I typically like to put my getters and setters after the field declarations.
01:42So I'll choose after oil;
01:45that's the last field declaration and before the methods.
01:48Next, indicate how you want to Sort.
01:50Do you want to put the Fields in alphabetical order or do you want to do all the
01:54getters first and then all the setters.
01:57I'm generating only getter and setter for one field initially, so it doesn't
02:01matter which I choose, but typically, I like the first option, Fields in
02:05getter/setter pairs.
02:07Next, set the Access modifier, are your getters and setters going to be public,
02:12protected, default, or private?
02:14I'm going to set them as public, so that they can be called from anywhere in the application.
02:18I'll click OK, and that generates two methods named getOil and setOil.
02:25Here is the syntax of an explicit getter method, it always has a return data
02:31type, which matches the original fields' data type, the name of the method
02:35matches the name of the field with a prefix of get, and the name of the field is
02:40changed to have an uppercase initial character.
02:43So oil, all lowercase, becomes oil with an uppercase O, and then within the
02:47getter method, there is a return statement that returns the value of the field.
02:52A setter method always has a void return type, and it has a prefix of set before
02:57the field name, it receives a value that matches the data type of the field, and
03:02then it sets the field using this, to distinguish the field from the argument.
03:07Once you've created these methods, you can we refactor the rest of the
03:10application to always set the fields through the methods.
03:14So for example in my public constructor down here the one who receives an int
03:19value, instead of saying this.oil=oil, I'll call the method setOil and pass
03:25in oil, the argument.
03:27Following this pattern results in centralizing the processing of the argument,
03:32later on if you want to validate, modify, or otherwise secure the data;
03:37it makes it very easy to do.
03:39Now let's do something similar in the olivepress class.
03:43Currently this getOil method in this class loops through an array list of olive
03:48objects, crushes each of them, then calculates the amount of olive oil, but it
03:53doesn't actually return the olive oil to the application.
03:57You could change this method so that it have a return type say of int, and
04:01then add a return statement, or another approach, would be to create a field
04:06of the class, so that once the getOil method was done, it would set the amount
04:11of oil as a member of the class and then the rest of the application could access that oil.
04:16So I'm going to place the cursor right after the class declaration and before
04:19the constructor method.
04:21I'll declare a private integer variable and I'll name it totalOil and I'll
04:27initialize it to a value of 0.
04:29When the class is instantiated, this private field will have a value of 0, but
04:35then I can add values to it each time the getOil method is called.
04:40Next, I'll add a getter and a setter for this field.
04:44I'll right click and choose Source>Generate getters and setters.
04:49I'll check the only field, I'll place the insertion point after totalOil, and
04:55I'll set the access modifier to public and click okay.
05:00So there's my getter and setter.
05:01The rule that I want to follow is the only code within the class is allowed to
05:06set the totalOil, but code anywhere in the application can access it.
05:11So I am going to change the access modifier for setTotalOil to private.
05:16So now from the point of view of the rest of the application, it's a read-only value.
05:22Within the getOil method I'll move the cursor down here, and I'll call the
05:25method setTotalOil and pass in the value that was calculated.
05:30I'll take this line of code that's outputting the total amount of oil and I'm
05:34going to place it in the main application.
05:35I'll go to main.java and place the cursor after the call to the OlivePresses get
05:41oil method, I'll paste in that line of code and now instead of outputting the
05:47value of an oil variable, which is no longer in the scope of this class, I'll
05:52get that value from press.getTotalOil, because it's a public accessor method, a
05:58public getter method, I can call it from anywhere in the application.
06:03It's up to the olivepress to set the oil, but my main application code can get to it.
06:08I'll run the application as a Java application and there is the result.
06:14Everything still works exactly the same as before.
06:18Finally, let's say that in this application I wanted to reuse the press
06:22object, so that I could add olives at one point in the application and then at another point.
06:28As long as I create a single instance of the olivepress class and keep it in
06:32memory for the duration of the application session, I should be able to do
06:36that, but right now my setTotalOil method is rewriting the value of total oil
06:42every time it's called.
06:44Let's say that instead, I wanted to incrementally add to it.
06:48I could go to the setTotalOil method and change the operator from equals to plus
06:53equals, and now I'm adding to the total.
06:56I'll Save my changes.
06:59I'll go back to main.java and I'm going to copy these lines of code
07:04starting with press.getOil.
07:06I'll paste those at the end and so now I am going to crush those olives once,
07:11and then I am going to crush them again, because I'm now incrementally adding
07:15a value, I should be multiplying the amount of olive oil each time I go through the loop.
07:21I'll Save and Run, and the first time through I got the 5 units and after the
07:26second time through I have 10, and so on.
07:30This illustrates the value of getters and setters, when you wrap the access of
07:35the data in a setter;
07:37it lets you change the rules very, very easily.
07:40So before every time the method was called, I was just assigning the value, but
07:45then with one little change, now I'm incrementally adding to the value, and you
07:50can design and code any other sort of business rule you like once you have the
07:54getters and setters in place.
07:56So this is a major part of what we talked about when we were
07:59discussing encapsulation.
08:01Hiding data refers to the practice of setting fields as private and then only
08:06allowing access to those fields through getter and setter methods.
08:11Again in Java, in the pure programming language, you don't have implicit
08:15setters and getters, like you do in some other languages, but there is a very
08:19strong convention for how you design setters and getters and then call them
08:23from within your application.
Collapse this transcript
Using class variables and Enum classes
00:00In this video course so far, I've shown you how to create two types of methods,
00:05class methods that are called from a definition of a class and instance methods
00:09that are called from an instance of the class or an object.
00:13The same distinction occurs with fields or variables.
00:17When you declare a variable as a member of a class using access modifiers such
00:21as public and a data type such as string, it's automatically an instance
00:26variable or an instance field.
00:28You can also create class fields by incorporating the additional keyword static.
00:34The most common reason to do this is to represent a constant value.
00:39Java doesn't support an explicit const or constant keyword, so instead, you
00:44typically set constant values using a combination of static and the keyword
00:49final, which means that a value can't be changed once its been set.
00:53I'll demonstrate this in the Olive class in this version of the project class
00:58variables, and I'll define a few possible values for the color.
01:03Right now my color field has a value of 000000 which has equivalent value of
01:09black, but I want to make my code a little bit more readable.
01:13So I'll place my cursor inside the class declaration and I'll declare a field
01:18using these keywords, public, static, final.
01:22Public means that the field would be accessible from the entire application.
01:26Static means that it's a class field, it will be accessed from the class
01:30definition, not from an instance of a class, and final means its value can't be changed.
01:36Next, I'll set the data type long, to match the field data type of color, and
01:41then the name of the constant will be set.
01:43The convention for constant values is to set their names in all uppercase.
01:49So I'll set the name of this one as BLACK, then I'll put in the equal assignment
01:53operator and I'll copy the value from the color field.
01:56I'll finish the declaration with a semicolon and now I have a constant value to work with.
02:05Next, I'll go down to the color field where I've used the literal value.
02:09I'll get rid of that and I'll replace it with Olive.;
02:13and I'll see the value BLACK appear.
02:16I'll Save the changes and Run the application and you should see that it runs
02:20exactly the same way it did before.
02:23Now I'll add one more field, I'll copy the one for BLACK and paste it in, I'll
02:29change the second one from BLACK to GREEN, and I'll change the hexadecimal color
02:34value to 00FF00 and you can keep on doing this, adding as many different Olive
02:41colors as you need it.
02:43I'll Save the change and Run it again and even though I'm not using that GREEN
02:47value the application still runs just fine.
02:51So this is a look at how to declare constants or class variable.
02:55Again, there's no constant keyword in Java, instead, you declare values using
03:00the keywords static and final.
03:03You can make these fields public, private, or protected, whatever you need, and
03:07you set their names to all uppercase, and that's just a very strong convention
03:12that all Java developers follow.
Collapse this transcript
10. Working with Inheritance and Polymorphism
Understanding inheritance and polymorphism
00:00In a previous video, I described the concept of encapsulation, one of the major
00:05concepts of object-oriented programming.
00:07There are two other concepts that you need to master to be a great
00:10object-oriented programmer, and they are named Inheritance and Polymorphism.
00:15I'll describe them here.
00:17Inheritance means that there's a relationship between classes in your application.
00:22An inheritance relationship lets you inherit or extend functionality from
00:26one class to another.
00:28In the world of C++ there is multiple inheritance.
00:32A single class can inherit functionality from multiple other classes but in
00:36Java, there is only single inheritance, each new class can extend or inherit
00:41functionality from only one other class.
00:44This actually makes it a lot easier to manage your code because if you've
00:48created an inheritance relationship and you run into a bug that bug can either
00:52be in the class you are working with or in the class that you inherited from,
00:56but the issue has to be somewhere in that very linear path.
01:00There are a number of ways to describe an inheritance relationship and they are
01:04just different vocabularies.
01:06You'll hear some developers describe the relationship as a
01:08parent-child relationship, where the parent has the functionality and
01:12the child is inheriting.
01:13You will also hear the terms base and derived, where a base class has the
01:18functionality and the derived class is extending it.
01:22In the world of Java, the terms that are most commonly used are Superclass and Subclass.
01:27The Superclass has the functionality and the Subclass is extending the Superclass.
01:33And again, each subclass in Java can only have one Superclass, in fact even if
01:39you don't explicitly extend a class all of your classes are extending another
01:44class, a Superclass.
01:45There is a special class named object with an uppercase O and this is at the top
01:51of the Java inheritance tree.
01:53If you don't explicitly inherit from some class, you're inheriting from object
01:58automatically, so that's Inheritance.
02:02Polymorphism is the last important term to understand.
02:05Polymorphism means that when there is an inheritance relationship between a
02:09Superclass and a Subclass you can deal with an object that's instantiated from
02:14the subclass either as its native type, the subclass or as it's inherited or to
02:19extend a type the Superclass.
02:22To do this, you declare the object and instead of declaring the native data type
02:27you declare the Superclass type.
02:29If it's a class that you're instantiating by calling a constructor method,
02:33you call the constructor method from the subclass but you use the data type of the Superclass.
02:38When you've done that it becomes possible to take that object which you
02:42declared as the Superclass and pass it to any method that's expecting an
02:47instance of the Superclass.
02:49When you have an inheritance relationship this can give you enormous flexibility
02:53in designing your code.
02:55Let's visualize an inheritance relationship.
02:58Let's imagine a class named Olive.
03:00Well there are many kinds of olives in the world and so you might declare a
03:05Superclass named Olive that has functionality that's common to all olives but
03:10then you might create multiple subclasses, each representing one particular kind of Olive.
03:16This is how we would diagram the relationship with an arrow pointing to the Superclass.
03:21That arrow means that the subclasses are extending the functionality of the Superclass.
03:27The Superclass is olive and all the others are the subclasses.
03:32We call this single inheritance because each subclass can only have a single
03:36superclass, but as you can see, a superclass can have many subclasses.
03:42superclasses don't need any special code, any class can be a superclass.
03:47And all of the fields and methods of that class can be inherited, unless
03:51they're marked as private.
03:53You'll see that it's very common to set fields or data values as private in a
03:58class and methods of a superclass as protected or public.
04:02Private means that only the superclass can deal with the field directly,
04:06protected means that a method can be called either by the superclass or by its
04:11subclasses, and public means that those methods can be called by anybody.
04:16Let's take a look at code of a sample superclass.
04:19This might be the class Olive, the class Olive might have a couple of fields or data values.
04:25I've declared a double value called volume and a Boolean value called crushed
04:29which is initially set to false.
04:32I have a method called getVolume and the logic of that method says if the value
04:37crush is true then return the volume and otherwise return zero.
04:42This is using the ternary operator, a shortened conditional syntax.
04:47There is a protected method named setVolume, it's protected so that it can only
04:52be called by the class itself or its subclasses.
04:55And there is a public method named crush which basically says this Olive has been crushed.
05:01The fields or data values are marked as private only the superclass can
05:05deal with them directly.
05:07To get volume method which is a getter accessor method can be called by
05:10anybody in the application.
05:12This setVolume method, the setter can only be called by the class itself and the
05:17subclass and the crushed method is declared as public.
05:20Now again this is just one way of designing the code, it follows some standard
05:25recommendations in Java by keeping private data private, but you could choose
05:29to do it differently.
05:31Now the subclasses that extend the superclass.
05:34In order to extend the superclass you declare the class in your Java file and
05:39you use the extends keyword and reference the superclass.
05:43It might look like this, I'm placing my class into a package named olives and
05:49then I create the class named Kalamata and I use the extends keyword and then
05:54the superclass named Olive.
05:56The subclass implementation might have a lot of details but here's one small example.
06:01As the subclass is constructed, and its constructor method is called it would
06:06be responsible for setting its own volume or the amount of oil it's capable of producing.
06:11So within the constructor method Kalamata which matches the name of the class
06:15itself it calls this.setVolume(2).
06:19SetVolume is a protected method, so the subclass can call it, but the actual
06:24data it's affecting is stored in the superclass, it's hidden from the rest
06:29of the application.
06:30Another subclass of the same superclass would call the setVolume method also but
06:35it would set its numeric volume differently.
06:37So now Liguria is saying, I can get five units of oil and Kalamata is saying, I
06:44can get two units of oil.
06:46They're both calling the same method, they're both using that same hidden data
06:50that's in the superclass, but they are determining what the actual value is.
06:54When you go to the main class code, you can now say I'm going to declare
06:58an array of Olives.
07:00Olive, bracket, bracket, means multiple Olives.
07:03But then when you actually declare the instances of the object, you use the
07:07constructor methods of the individual subclasses.
07:11I have an array with two Kalamatas and one Liguria, but they're all olives
07:17because of the inheritance relationship.
07:19I could then create an instance in the OlivePress call to getOil method and
07:24within that method it would then go and call the appropriate methods of the
07:29olive object and for Kalamata's, it would get two units, for Liguria's it would
07:33get five units and so on.
07:35The rest of the application does not need to know the mechanics of how the
07:39volume is being calculated.
07:41All the top-level application has to do is say, I've got these three olives and
07:45they're of these types, go ahead and crush them.
07:48The actual mechanics are hidden within the class implementations.
07:53This idea that you can create an instance of a class by referring to it uniquely
07:58named constructor method but then take the object and fit it into a data type of
08:03its superclass is polymorphism at work.
08:06You're taking an object that has a native type in your saying I'm going to use
08:10it as though its supertype, that's polymorphic and it allows you to build really
08:15elegant applications
08:17Within the implementation of the OlivePress, it would simply loop through the
08:21olives and call the methods, it would get the oil, it would add that to the
08:26olive oil, and the end result would be a correct calculation.
08:30The OlivePress doesn't need to know how much oil you get out of each olive
08:34and it doesn't even need to know that they're all these different kinds of olives out there.
08:38From the point of view of the OlivePress, there is only one kind of olive an
08:42Olive, and you can crush it and you can add it to the oil.
08:46The details are hidden within the implementation.
08:50So that's the idea of inheritance and polymorphism.
08:53In the rest of the videos of this chapter I'll show you how to implement
08:56inheritance and put it to work polymorphically in your applications, and then in
09:01a later chapter we'll go on to more advanced concepts using constructs called
09:06interfaces and abstract classes that also adds to the inheritance model of Java.
Collapse this transcript
Extending custom classes
00:00The goal of creating an inheritance relationship between classes is to extend or
00:05inherit functionality in the subclass.
00:08I am going to demonstrate this in my OlivePress application, working in a
00:12version of the project named extending custom
00:15In this application I've defined a custom class named Olive, it has two public
00:20class fields BLACK and GREEN.
00:22It has three public instance fields, two strings in a long, and it has a private
00:27instance field for oil, an integer.
00:30It has a getter and a setter for the oil value and a couple of constructor
00:34methods and one custom crush method.
00:37Now, I'm going to create subclasses for the Olive class.
00:41My goal is to create classes that inherit most of the functionality of the
00:45superclass, but then set particular values that are unique to those classes.
00:51I'll place my subclasses in the same package as the superclass olive.
00:55I'll go to the package Explorer, I'll right click on the package and I'll select New> Class.
01:02I'll name my first subclass, Kalamata, I'll set the superclass to my olive class.
01:09When you set the superclass you have to use the entire package and class name.
01:13You can't just name the class by its name.
01:16And this would be tough to type without making mistakes.
01:19So I'm going to click the browse button and let Eclipse do some of the work for me.
01:23In the superclass selection dialog I'll type Olive and I'll choose Olive and
01:28click okay and then click finish.
01:32And here is my subclass Kalamata.
01:34Now I'll repeat that operation and create a second subclass, I'll right-click
01:38on the package, choose New > Class and I'll name this one, Ligurian another olive variety.
01:46Once again I'll browse for the superclass selecting Olive and I'll click Finish.
01:53I now have two subclasses of the Olive class.
01:56Now when I create my olives in the main application, I'd like to be specific
02:02about what kind of olives I'm creating.
02:04Right now, I'm calling the Olive constructor method three times and passing in
02:09values for the amount of oil that that Olive will generate.
02:13Instead I'd like to say I want to create two Kalamata's and one Ligurian.
02:19All I need to do is use the appropriate constructor methods for these classes,
02:24but I can't do it quite yet.
02:26Even though the superclass has constructor methods.
02:29Constructor methods are not literally speaking members of the class.
02:33There are special kind of syntax and so they're not inherited by subclasses,
02:39each subclass needs its own explicit constructor that matches its name.
02:44So I will go to the Kalamata class and fix the problem there first.
02:48I'll place the cursor inside the class declaration and right-click and I'll
02:52choose Source and then I'll let Eclipse do some of the work for me by choosing
02:57this option, Generates Constructors From Superclass.
03:01I'm asked which constructors I want to implement, the one with no arguments or
03:06the one with the integer argument or both.
03:09Because of the way I am designing this application I only want my subclasses to
03:13have no arguments constructors.
03:16So I'll deselect the version that would receive an integer argument and click OK.
03:21So here's my new constructor method.
03:23There is a single line of code here named super.
03:26The super method is a way of calling the superclass's constructor method.
03:31I'll leave that in place for the moment and I'll just remove the TODO comment.
03:35I'll save those changes and go to the Ligurian class and repeat the process.
03:39Once again I'll right-click inside the Class Declaration and choose Source
03:44generate constructors from superclass, I'll deselect the constructor that
03:48receives an integer argument and click OK, and I'll remove the TODO comment.
03:54Now I'm ready to use the subclasses in my main application.
03:58I'll go to main.java in the main application file I'm calling the constructor
04:03method for the superclass three times.
04:06Notice that I declared a variable typed as the superclass, but when I actually
04:11construct the objects I don't have to use the superclass constructor.
04:15I can instead use the subclass constructor, the native type of the object will
04:20then be the subclass, but it can masquerade as the superclass.
04:25This is polymorphism at work.
04:28By declaring as the superclass, I can then say I've got a whole bunch of olives,
04:32but I don't have to be specific about what types of olives, but when I construct
04:37them I can be specific and affect the behavior.
04:40So I'll go to the first constructor method call and I'll change that to
04:44Kalamata, I'll type Kal and press Ctrl+ Spacebar and the rest of the class name
04:49is filled in for me by Eclipse.
04:51Now, I'll do something similar but the second one will be an instance of
04:55the Ligurian class.
04:56I'll type Lig and press Ctrl + Spacebar, and Eclipse finds two classes that
05:02start with that string, I'll choose Ligurian and then finally, I'll change the
05:06third one and I once again use Kalamata, typing Kal and Ctrl + Spacebar.
05:13When you type Ctrl + Spacebar, you should get new import statements up at the
05:16top of your code for the new classes.
05:19Now, I've still got problems here right now my subclasses only have no arguments
05:24constructor methods.
05:25They don't have versions of the constructor method that can receive values.
05:29When I move the cursor over the first constructor method call, I get a list of
05:33available quick fixes.
05:36What do you want to do Eclipse is asking me to match the constructor.
05:40I'll choose the first one, remove the argument and now that constructor method
05:45call matches what I have in the class.
05:47I'll do the same thing for Ligurian, removing the argument and then for the
05:52second version of Kalamata.
05:54I'll save my changes, and it will now appear as though everything is in good shape.
05:59I'll run the application, and you'll see that after running the first series of
06:03olives I get nine units of oil, and after the second 18.
06:06Well, why is this happening?
06:10The reason is because in the superclass, in the oil declaration there is a
06:15default value of three and I am no longer doing anything to override that value.
06:21My goal is to have each of the subclasses decide for itself.
06:24How much oil do I generate, what's my color, what's my name and so on.
06:29So I'll go over to kalamata. java and I'll make those changes.
06:33First of all, going back to the superclass these three fields are public and so
06:38I can change them from directly within the subclass, I'll say this.name =
06:43Kalamata and this.flavor equals Grassy and this.
06:52color == Olive.BLACK.
06:56Now to set the oil value once again I'll go back to the superclass, and show you
07:01that we provided a way of setting the oil value using this version of the
07:05constructor method which is public.
07:07So go back to Kalamata, and I'll pass in a value of two.
07:11So now all Kalamata olives will have the same oil value.
07:16When I save my changes, notice the error at the bottom.
07:19It tells me that if I'm going to call the superclass's constructor, that has to
07:23go at the top before any other statements.
07:26So I am going to move that code up holding down Alt on Windows or Option on Mac
07:31and pressing the up arrow a few times, then I'll save my changes.
07:35Now I'll copy those lines of code to the clipboard, and go over to Ligurian and
07:40I'll paste that in getting rid of the super method call with no arguments.
07:45I'll change the oil value for Ligurian to five.
07:48We'll say that that's a very big olive, I'll change the name to Ligurian, I'll
07:52change the flavor to Yummy and I'll change the color to green.
08:00So now each of the subclasses is responsible for setting its own field values,
08:05when I run the application, all I need to know is that I am creating these
08:09instances of these subclasses, all the specifics are determined by the
08:14subclasses themselves and when I run the application, it looks like I got the
08:17same values, nine units and 18 units but it turns out that that's because of the
08:23values and the particular combination of olives that I just selected.
08:27So I'll go back to Ligurian and I'm going to change the Ligurian so that it's a
08:31really tiny olive, it only gives me one unit of oil, I'll run the application
08:36again and this time the numbers change.
08:38So you can see how creating an inheritance relationship allows you to inherit
08:43functionality from a superclass but then set specific values in the subclass
08:49that are respected by the rest of the application.
08:52From the main application's point of view, all it needs to know is these are the
08:56types of olives, all of the details are handled in the subclass code.
Collapse this transcript
Overriding superclass methods
00:00When a subclass extends a superclass, it inherits the methods of that superclass.
00:05But it can override them replacing the version in the superclass;
00:09I'll show you how to do this with the Olive superclass and Kalamata subclass in
00:14this version of my application overriding methods.
00:17The olive superclass has a method called crush, it outputs a simple string
00:22and returns a value.
00:23Now, the particular example I'm going to show is very simple, but my goal is to
00:28show you the basic syntax and then as you find reasons to extend superclasses
00:33and override their methods you'll know how to do it.
00:36Go to the subclass Kalamata and place the cursor after the constructor method.
00:41Now you could type all the code yourself, but Eclipse will help you, press
00:44Ctrl+Space and you'll see a list of all the methods of the superclass, choose
00:50the one you want to override crush, a new version of the crush method is
00:54added to your code.
00:55This annotation the @ character and the word Override with an uppercase O is not
01:00required, but it is recommended it makes your code more readable, it makes it
01:05clear that you're overriding the superclasses version of the method.
01:09When you override the superclass version the data type must match.
01:13So if I go back to the superclass method it returns an int value and here's the
01:19subclass version, this arrow pointing upward over and the trough indicates that
01:24this is an overriding method and when you click it, it will take you to the
01:27superclass version, I'll go back to the subclass, I'll get rid of this TODO
01:32comment, we don't need that, the version of the class that Eclipse generates
01:36includes a statement return super. crush, this means called the superclasses
01:42version of the method and return whatever value it returns.
01:46So, even though you're overriding, you still can take advantage of the
01:50functionality that's apart the superclass implementation.
01:54Now, I'll place the cursor inside the new method and I'll use System.out.println
02:01and I'll output the message "crush from subclass", then I'll go back to the
02:09superclass version of the method and I'll output "crush from superclass", I'll
02:15save all my changes and run the application and you'll see where ever the
02:19subclass version is being called that first to get the message from the subclass
02:23and then from the superclass.
02:26And this is because of the order of the code first I'm getting this print
02:29command, then I'm calling the return statement and calling the super crush
02:34method, the super crush method is outputting its message returning the value
02:40and then finally the subclass method takes over and returns the value to the main application.
02:45So to review the rules for overriding methods the data type of the method that
02:49you're overriding must be repeated in the subclass, the at override annotation
02:54is not required but it is recommended, it makes your code more readable.
02:59And once you know how to override methods from the superclass you can customize
03:03the behavior of your subclasses however your application requires.
Collapse this transcript
Casting subclass objects
00:00Earlier in this video course when I was describing the use of primitive
00:03variables, I described the process of conversion as either upward or downward.
00:09I described the conversion of an integer say to a float or double as an upward
00:14conversion and said that this sort of conversion is implicit, automatic, and
00:19safe, but if you try to go in the other direction converting downward where
00:23you take a very specific value and try to squeeze it into a less specific
00:28value that's where the conversion can lose data, and so you have to be
00:32explicit in your syntax.
00:34This same thing is true of complex objects that have an inheritance
00:37relationship, when you use an object that's a subclass and you treat it as its
00:42superclass, we don't call that converting we call it casting, but we still use
00:47the same directions, the specific version being used as the more general version
00:51is called upward casting and taking an object that's been seen as the superclass
00:57and casting it downward to the specific object is called down casting.
01:02And just as with primitive variables you have to be specific.
01:05Let's take an example, I'm working in a version of my application that's
01:09called casting objects.
01:12In this version of the application I removed a little bit of code, but I still
01:16have a declaration of an olive variable and then I'm instantiating that variable
01:21three times, twice as a Kalamata and once as a Liguirian, I'm then adding those
01:26objects to an array list that explicitly is declared as only containing
01:31instances of the olive class.
01:34I'm allowed to pass in the subclass, because that's an upward conversion and
01:39it's implicit and it's safe.
01:41But now I'll show you what happens when you try to recast downward.
01:45I'll go down to the bottom of the code and I'm going to get a reference to the
01:49first item in that array list.
01:52I know that it's an instance of Kalamata class, because that's how I declared it up here.
01:58So I'll start off below all the other code and put in a data type of Kalamata
02:04and I'll name the variable olive1.
02:07And then I'll get a reference to that object using the syntax olives.get and
02:12I'll pass in a value of 0 for the first item in the array list.
02:17Now when I save my changes and build the project I get this, type mismatch
02:22cannot convert from Olive to Kalamata, it's a downward casting that I'm trying to do.
02:28Even though I know it's a Kalamata olive, I created it as a Kalamata olive, the
02:34compiler and the JVM at this point will think it's simply an olive.
02:39So I have to tell the compiler its okay, it's a Kalamata olive.
02:43Here is how you do it, place the cursor before the code that's returning the
02:48reference and then declare the native type of the object wrapped in parentheses.
02:58I'm telling the compiler and getting the reference to this object, but I want
03:02you to treat it as the subclass, I'll save the changes, the error goes away
03:08and all I have left now is a warning saying the value of that variable isn't yet used.
03:13So let's go ahead and add a little bit specific functionality to Kalamata,
03:18that's not available in all other olives.
03:20I hold down the Ctrl key on Windows or Command on Mac and click the name of the
03:25class Kalamata and that takes me to the declaration of the class.
03:30I'll add a new public method into the class after the override of the crush method.
03:35It'll be a public method that returns a String and it will be named
03:39getOrigin and I'll return a value simply of "Greece" because that where
03:45Kalamata's come from.
03:46I'll save my changes and go back to the main class and then I'll output the
03:52return value from that method using a System.out.println command and the
04:00output will look like this "Olive1 is from" and then I'll append to that the
04:07value of olive1.getOrigin.
04:09I'll run the application and there is the result Olive 1 is from Greece.
04:19Now if I didn't have this casting syntax I wouldn't even be able to compile the
04:24application, but if I could I wouldn't be able to call that get origin method,
04:29the compiler would say, well you said that was an olive not a Kalamata and if
04:33it's not a Kalamata then it doesn't have to get origin method.
04:37So this is how you cast objects downward from the general type to their specific type.
04:43As you continue using the inheritance model in Java you'll find that this
04:48casting becomes more and more important.
04:51The ability to cast upward and downward so that you can either use objects in
04:56their general form that is as their superclass or in their specific form their subclass.
Collapse this transcript
Understanding interfaces and implementing classes
00:00In previous videos, I've describe how to create an inheritance relationship
00:04between Java classes, superclasses that contain functionality, and subclasses
00:09that inherit that functionality.
00:11There is another way of creating inheritance relationship using an interface.
00:16An interface in Java lets you define the structure of a class including the
00:21names and signatures of the classes methods and any final fields that is class
00:26or instance variables that will always have the same values.
00:30You can then implement that interface with a class that you can
00:33actually instantiate.
00:34The Java class library uses interfaces extensively.
00:38Here is an example of an interface you probably will use in your own
00:41applications, the collection interface.
00:44The collection interface is the high- level definition of objects that are a part
00:49of the Java collections framework and we've only used a number of classes in
00:53this framework including the array list.
00:55The collection interface defines the names and signatures of methods that are a
01:00part of all the classes in the list of implementing classes.
01:04I'll go down to the method list and you'll see that they look familiar.
01:08These are the same methods that are a part of the array list class.
01:12The idea of an interface is that you're defining a contract.
01:16If you say that a class implements an interface, it must implement all of these
01:21classes and it must use the exact method names and the same number and data
01:26types of arguments and the same return data type.
01:29This then allows you to use the concept of polymorphism in your code.
01:33An array list can be seen either as an array list or as the interface that it
01:37implements, collection.
01:39Let's see how you might use this in an actual application.
01:42I am in a project named UsingInterfaces that's a part of his chapter's exercise files.
01:47In this version of the application I have a call to a method named getOil that's
01:52defined in the class OlivePress.
01:54I am passing in an object as an array and this object is declared as an array
01:59list containing instances of the Olive class.
02:02In the OlivePress class, where I've defined that method, I'm using exactly the
02:07same data type array list.
02:09Now because array list implements the collection interface I can actually make
02:13this method a lot more flexible.
02:16Instead of requiring an instance of the array list class, I can instead require
02:20an instance of the collection interface.
02:23So I'll change the data type in the method signature from array list to collection.
02:28After typing the name of the interface, I'll press Ctrl+Space and choose the
02:32collection interface and that causes the required import statement to be added
02:36to the top of the code.
02:38I'll then clean up my imports by going to Source>Organize Imports and that
02:43removes the import for the array list, which is no longer referred to in this class.
02:47I'll save my changes and that rebuilds the project and you'll see that there are
02:52no programming problems as a result.
02:54I am up casting from array list to collection, from the more specific type to
02:59the more general type.
03:01And now this method can accept any instance of any class that implements the
03:06collection interface.
03:07In the Main class, I'm going to still keep the array list declaration here.
03:13I'm not going to change its collection and the reason is because the array list
03:16class has other methods that are not part of the contract that are not described
03:22in the collection interface.
03:24One of the most important of these is the get method.
03:27This method is a specific part of array list and is not part of the contract
03:32and if I data typed this object as collection the compiler would not accept my call to get.
03:38But with that change I'll save and run the application and show you that it
03:42still works exactly as it did before.
03:45But now my getOil method is more flexible.
03:47I can pass in any instance of any class that implements the
03:51collection interface.
03:53Now you can create your own custom interfaces in your applications and your own
03:57implementing classes and I'll show you how to do that in another video.
Collapse this transcript
Creating your own interfaces
00:00You can use interfaces in your own applications to model
00:03inheritance relationships.
00:05You create your own interfaces just like you do classes and in the interface
00:09definition, you add your method definitions, the method names and signatures,
00:14and you can also add final fields that is values that don't change at runtime.
00:20Interfaces can't have constructor methods or other elements of classes though.
00:25So interfaces should only be used in situations where you're modeling behavior
00:30and not dynamic management of data.
00:32I'll give you a very brief example of this.
00:35I'll be working in a version of the application named creating interfaces.
00:39Let's say, for example, that I wanted to create an inheritance relationship
00:43between an interface called press and a specific class called OlivePress.
00:48I'll be creating an actual class named OlivePress2.
00:52Now I'll right click on press and choose New>Interface and I'll give it a name
00:57of Press and I'll click Finish.
01:00The first thing you'll see that syntactically different from a class is this keyword.
01:04Instead of public class I'm saying public interface.
01:09Now within the class definition, I can define as many methods as I want.
01:13I'll go back to my existing OlivePress class and I am going to take some code from there.
01:18Let's say, for example, that I want all classes that implement my press
01:22interface to implement a getOil method.
01:24I am going to select and copy the method's signature, but not
01:29the implementation.
01:30Then I'll go back to press, I'll paste that in and I'll add semicolon at the
01:35end of declaration.
01:36Notice that when I paste it in the code, Eclipse automatically added import
01:40statements for the collection and the Olive class.
01:43Those are required, but also notice that I'm not implementing the code here.
01:48I'm just saying what the name of the method is, what its arguments are, and what
01:52its return data type is.
01:54I'll go back to OlivePress and I'll take a couple more methods.
01:58I'll take to getTotalOil method, copy and paste it in, add the semicolon,
02:04I'll go back to OlivePress again, and I'll take setTotalOil, I'll copy and I'll paste.
02:12Now when I save, I get an error.
02:15It tells me that methods defined in an interface can only be marked as public or
02:20something called abstract.
02:22Don't worry about abstract;
02:23I'll describe that later.
02:24What's important here is that when you declare method signatures in an
02:28interface, they must be public.
02:31You can't make them private because you can't implement the code here.
02:35So I'll change private to public and save my changes and the error goes away.
02:40Next I'll show you how to create a class that implements the Press interface.
02:45I'll create a new class and I'll name this OlivePress2.
02:51Now you can actually implement multiple interfaces in Java.
02:55So you can add as many interfaces here as you want, but I am only going to implement one.
03:00I'll type in press and choose the Press interface that I just created, I'll
03:06click OK and Finish.
03:08When the class is generated by Eclipse, all of the methods that were defined in
03:13the interface are added automatically to the new class, just as in a superclass
03:18subclass relationship, you use the override annotation above all the method
03:23signatures that you are overriding.
03:25It is an inheritance relationship and just like a superclass and a subclass, you
03:31can say that an OlivePress2 is a Press.
03:34To complete the coding process, I would add the implementing code in each of these methods.
03:40This would be enough to get you started though.
03:42Now, I will say that using interfaces in your own code is completely optional.
03:48If you like the idea of interfaces, use them;
03:51if you don't like them, ignore them.
03:53But it is important to understand how interfaces work because of the number of
03:57times you are going to encounter them in the core Java class library, such as
04:01with the collection an array list class that I described in a previous video.
04:06If you want to create your own interfaces for your own applications though, this
04:10is the syntax and the process in Eclipse.
Collapse this transcript
Using abstract classes and methods
00:00In previous videos, I showed examples of creating inheritance patterns with
00:04concrete superclasses and with interfaces.
00:08There is another option in Java called an abstract class.
00:11Abstract classes combine the best of the other two options.
00:15Like concrete superclasses, they can have fully implemented methods that they
00:19can share with their subclasses, but like interfaces, they typically aren't
00:23instantiated directly, so they can create a better programming contract.
00:27I'm starting in a version of the Olive Press application that has a concrete
00:31superclass named Olive.
00:33To change it to an abstract class I'll add the keyword abstract after the public
00:37access modifier, but before the keyword class.
00:41Nothing has changed so far in the functionality of this application.
00:44I'll save and run the application, and show that it still runs.
00:48But the reason there are no functional changes yet is because I'm not trying to
00:52instantiate the Olive class directly.
00:54Going back to the Main class, I'll show that I am instantiating the subclasses:
00:59Kalamata, Ligurian, and Kalamata again.
01:02Watch what happens when I try to instantiate Olive directly.
01:05I will move the cursor down to the end of the Main method, and I will add a line
01:09of code that declares a new variable.
01:11I will set the data type as Olive, and I will name it olive2, and I will
01:15instantiate it with new Olive, the constructor method.
01:20When I save my changes, I get the error message, Cannot instantiate the type Olive.
01:25So when you declare a class as abstract, you can't instantiate it directly,
01:30except under certain conditions.
01:32I am just going to comment-out this code for the moment, I will come back to it later.
01:36The point of using an abstract class as a superclass is that you can create a
01:41contract that says all of this abstract classes' subclasses promise to implement
01:46some sort of functionality.
01:47Here is an example, I will go back to the Olive class and show that it has a
01:52method called getOrigin(), which returns a string of Greece.
01:56Now because this class is abstract, it can have this concrete implementation,
02:01but the reality is that not all olives come from Greece.
02:05Some have an origin of Greece, some of Italy, and some of other countries.
02:09So I might make the decision that I'm going to implement this method in each of the subclasses;
02:14not in the superclass.
02:16But I want to make sure that all of the subclass is implemented.
02:19So I will change this method to an abstract method.
02:23The syntax is just like the class itself, you place the word abstract after the
02:28access modifier, and in this case, before the return type.
02:31And then, you use the same kind of syntax you would in an interface.
02:36I will delete the implementation and add the semicolon at the end of the declaration.
02:41I'm now saying that this method must be implemented in all classes that extend this class.
02:47Watch what happens when I save my changes. I get errors.
02:50The classes Kalamata and Ligurian are extending the abstract class and they must
02:56implement all abstract methods.
02:58So let's go to each of these classes and fix the problem.
03:01I will go to Kalamata, I will place the cursor below all of the other methods
03:05but within the class declaration.
03:07I will right-click, and choose Source > Override/Implement Methods.
03:12This is a trick that most good Java editors will be able to do for you.
03:15It will look at the superclass and say, here are the methods that you have
03:19not implemented yet.
03:20And then it will generate the stub for the method for you.
03:23I'll click OK, and I get the new method getOrigin().
03:27The Override directive above the method can be retained if you like.
03:31It is optional, but it is a good way of noting that you are implementing a
03:34method that was declared in the superclass.
03:36I will delete the TODO comment and I will replace the value null with a string of Greece.
03:43I will save those changes and now I will go to Ligurian, and I will do the same thing.
03:49I will once again make a little bit of space, right-click in the open space,
03:53and choose Source > Override/ Implement Methods, once again getOrigin() is
03:58checked, and I will click OK.
03:59Then I will delete the TODO comment and replace null with Italy, again as a string.
04:05I'll save my changes, and all of the errors go away.
04:09Now to prove this works correctly, I will go back to Main.java.
04:12At the bottom of this code I'm already declaring a variable named olive1,
04:16data-typed as Kalamata.
04:18I am going to change that so that the data type is the superclass of Olive,
04:22and because Olives is a collection of olive objects, I can remove the casting syntax.
04:28Then I will copy and paste that code, both the declaration and the output of
04:32the getOrigin() method.
04:33And I will change the second set to olive2, the name of the variable is olive2.
04:39I will change index that I am looking for from 0 to 1, and I will change the string.
04:44I will save the changes and run the application, and now I am told that Olive 1
04:49is from Greece, and Olive 2 is from Italy.
04:51The magic of this inheritance architecture is that at the top level, I am only
04:56designating the type once, when I instantiate each object.
05:00But later when I call the method getOrigin(), I know that that method will be
05:04there because of the contract created by the abstract class, and I called the
05:09correct method because it is implemented as a concrete method in the
05:13appropriate subclass.
05:14Finally, let's go back to the declaration where I tried to instantiate the
05:18superclass directly.
05:20I mentioned that you typically don't instantiate abstract classes directly, it
05:24is possible to do it though, as long as you satisfy the contract.
05:28I will remove this comment, and I am going to recode this.
05:31I will backspace over the semicolon and the parenthesis, and then press
05:35Control+Space, and I will choose Olive as the constructor method.
05:39Notice the notation Anonymous Inner Type.
05:42I will double-click to select, and take a look at what Eclipse generates.
05:47It allows me to instantiate the Olive class directly, but only if I implement
05:51the abstract method getOrigin().
05:53So I am satisfying the contract again, but in a different way.
05:57Instead of an explicit subclass, in its own class file, now I am creating a
06:02subclass inline as something called an anonymous inner type.
06:06I am not actually going to do this in the application, so I will select that
06:10code, and then comment it out, save my changes, and run the application one last time.
06:16So that is a look at how you can use abstract classes in your
06:19inheritance architecture.
06:21Again, they combine the best features of interfaces and of
06:25concrete superclasses.
06:26They support a better programming contract then the concrete superclasses, but
06:31have a lot more flexibility and power than interfaces.
Collapse this transcript
11. Working with Files
Managing files with the core class library
00:00Once you've learned the core principles of Java, you'll find that expanding
00:04your knowledge of the language is a matter of learning about more classes and
00:07their functionality.
00:09One of the most common tasks that all programmers need to know how to do in any
00:12programming language is how to work with files.
00:16So in this chapter, I'll go through a number of different programming tasks
00:20including copying files, deleting them, writing them from scratch, and so on.
00:25And I'll start with how to copy an existing file.
00:28I'm going to be using a number of classes from the core class library called the
00:33input stream, file, and output stream.
00:36My project, FileManagement, has a single text file and it just has some
00:40nonsense text in it.
00:42My goal is to write some code that copies this file and create a new file
00:46with the same contents.
00:48I'll do all the work in the Main method of this class, CopyFile.
00:52The first step is to create objects that represent your existing file and the
00:56file you want to create and for this purpose, we use a class named file.
01:01I'll type in the name of the class and press Ctrl+Space and choose the version
01:05of file from java.io and I'll name it f1.
01:10I'll instantiate class and I'll pass in the name of the existing
01:13file, loremipsum.txt.
01:17When you're working with a console application, you can assume that the file
01:21is in the project directory that is the root directory where the whole project is stored.
01:26If you are working in another programming environment such as Java Enterprise
01:30Applications that is web applications, the rules for where the current
01:34directory is may differ;
01:36check the documentation for that environment.
01:38Next I'll create a second file variable and I'll have this file object refer to
01:43the file I want to create, I will call it target.txt.
01:48So a file object can refer either to an existing file or when you want to create.
01:54Next, I'll create classes called input and output streams.
01:57An input stream can read the contents of a file and an output stream can write
02:02the contents of a file.
02:04I'll declare a variable data typed as InputStream, I'll press Ctrl+Space and
02:09choose InputStream from java.io.
02:11I'll name it in and I'll instantiate it using a specific class
02:16called FileInputStream.
02:18The Java.io package has many versions of the input stream class.
02:23This one is specifically for files and when I instantiate the file input stream,
02:28I'll pass in the file reference.
02:31Next, I'll create an output stream.
02:34I'll follow the same pattern, I'll type the name of the class and press
02:37Ctrl+Space and be very specific hear;
02:40there's more than one version of the output stream class available to you, you
02:44want the version in java.io.
02:47Name the output stream out and instantiate it using FileOutputStream.
02:55Once again I'm making sure I select the class from the list so I get my import
02:59statement, and I'm referencing file number 2.
03:03You'll see that there are errors over on the side, don't worry about them from now;
03:07we'll take care of them at the end of all the programming.
03:10The next step is to create objects that we can use to read the contents of the file.
03:15In Java, in order to copy a text file, you copy a byte by byte.
03:21There is no single method in the core Java class library to say copy a file
03:26and you have a choice of reading one byte at a time or using a chunk of bytes at a time.
03:32It's more efficient to use a chunk of bytes, but you don't want to use too many
03:36bytes because you don't want to chew up memory.
03:38So in the next step, I'm going to create an array of bytes and give it a
03:43specific size, large enough but not too large.
03:48I'll declare a variable as a byte array, I'll give it a name of buf for buffer,
03:52and I'll instantiate it using new byte [1024].
03:59That's a nice little number.
04:00It means that I'm going to read 1024 bytes at a time.
04:04Next, I'll declare a variable named len for length, data type as in int.
04:09I'll use that to determine how many bytes I get back each time I read
04:14something from the file.
04:15If I'm just starting to read the file, the byte array will contain 1024 bytes.
04:21When I get to the end of the file, len will return the total number of bytes
04:25remaining and this will make sure that I don't try to write bytes to the target
04:29file that I don't have.
04:31Now I'll create a loop with the while keyword.
04:34I'll use off while loop with condition and here's the condition.
04:39I'll start with an open parenthesis then len = in.read(buf), and then I'll
04:49compare the return value to 0, and close the whole condition with a
04:54closing parenthesis.
04:56So this part of the expression means reading of information from the source file
05:01to fill the byte array that will be 1024 bytes maximum and then return the total
05:07number of bytes that you actually got to the integer variable, len.
05:12If the value that's returned is greater than 0 then that means we got something.
05:17If the value returned is 0 that means we're done, we're at the end of the file.
05:22Once again, you'll see an error;
05:23again, don't worry about it.
05:24We'll deal with that at the end.
05:26So now I have an array of bytes that I can use to write content to the target
05:31file and I'll use this syntax, out. write, I'll pass in the buffer byte array,
05:39a beginning point of 0 of the byte array and len, the number of bytes that I want to output.
05:46And that's it;
05:47I'm done copying the file over.
05:50Before I can really be finished though, I need to close my streams.
05:55Input and output streams can use resources.
05:58Not all output streams and input streams actually use resources, but it's a good
06:02practice to call a method on each of them called close.
06:06So I'll use in.close and out.close and finally, I'll output a message saying
06:16that the file was copied.
06:23Now let's get to all these errors;
06:25if you move the cursor over all the error indicators, you'll see that they're
06:29all saying that they are unhandled exceptions.
06:32Some of them indicate IOException and some of them indicate
06:35FileNotFoundException.
06:38You can handle all these exceptions with a single try catch, I'm going to select
06:43all the code, right click, and then choose Surround With>Try Catch Block.
06:49And you'll see that there are catch blocks added for both possible exceptions;
06:54FileNotFound and IOException.
06:57So now my code should be ready to run and we'll see what happens.
07:00I'll run the application, I get the message, file copied.
07:06I'll go over to the Package Explorer, right-click, and choose Refresh and I see
07:11my new target file has been successfully created.
07:14Now, you might be thinking that's an incredibly complex way to copy a file.
07:20But this is how you do it using the core Java class library.
07:24The good news is that there are libraries out there in the world from the Apache
07:29Commons project that make this kind of process a whole lot easier.
07:33I'll show you how to download and use that particular library later in the
07:36course, but it's important to know how to do this in the raw form in Java so
07:42that if you have to write your own specific code, you'll know how.
Collapse this transcript
Managing files with Apache Commons FileUtils
00:00In our previous video, I described how to copy the contents of the text file to
00:05a new text file, using tools that are available from the Java class library.
00:10I'm working in a copy of that project now called ApacheFileUtils that's a part
00:14of the exercise files for this course.
00:17In this application, I had to create a whole bunch of different objects two file
00:23object representing the existing file and the target file, an input stream and
00:28an output stream, a byte array, an integer, and then I had to loop through and
00:34read the file one set of bytes at a time and write out the new file.
00:37To all new Java developers, this seems a bit cumbersome and almost everybody
00:42asks the question isn't there an easier way.
00:45The reality of the Java class library is that it tends to give you tools in very
00:50small pieces, and it's up to you the developer to figure out how to plug those
00:54tools together to get your work done, but the good news is that the Java
00:59programming language has been around a long time and the Java developer
01:03community has done a great job figuring out what were the most common tasks that
01:07everybody needs to do and those tasks tend to be encapsulated and delivered in a
01:13project called the Apache Commons.
01:16You can get to the Apache Commons website at http://commons.apache.org.
01:23This project contains fully tested reusable Java components that are completely
01:28free and licensed for use on either Open Source or commercial applications, most
01:34of the components in the Apache Commons can be used in any Java development
01:38environment including console applications like the ones I've been showing here,
01:43but also including Java Enterprise Edition applications that is web applications
01:48and Android mobile applications.
01:50To get to the Commons project we need, go to the Commons Proper from the
01:55homepage, you'll see that there are a whole bunch of different projects you can
01:58work with and we're going to work with this collection IO.
02:03On the IO page, you can click into utility classes and then scroll down in the
02:08list of classes, and you'll see a class listed there called File Utils.
02:13This is the class, that I'll be working with.
02:15The first step to using the class is to download the Commons IO package, I'll go
02:21back a couple steps in my browser, back to the IO page and in the Commons IO
02:26menu on the left, you'll click the download link.
02:29There are two binary versions of the download a tar.gz version and zipped version.
02:35The zipped version should work fine for either Windows or Mac.
02:38Now, I've already downloaded and extracted the file to my desktop, I'll open the
02:43extracted folder and drill down, until I see these files.
02:48The zip file contains three jar files, I don't need the Java docs and I don't
02:53need the source files, what I need are the binaries, they will have a file
02:57extension of dot jar and the name commons-io and the version number.
03:03I'm using version 2.1 but any later version should work pretty much the same.
03:08Now, to use this file in your project copy it to the clipboard then go to the
03:14folder that contains your project, I'm using Windows so I'll use Windows
03:18Explorer and I'll go to the 11 files folder and from there to ApacheFileUtils,
03:22now you can place this file anywhere on your disk you want to, but most Java
03:28developers place existing libraries into a folder named Lib, L-I-B.
03:34So I'll create a new folder and I'll name it Lib or Lib or L-I-B, I'll drill
03:40down into that folder and paste the jar file, then I'll switch back to Eclipse.
03:45I'll go to the Package Explorer and refresh the view and show that the Lib
03:50folder and the jar file are now there.
03:53Now here's how you incorporate the jar file into your application, you have to
03:58add the jar file to something called the build path.
04:01A new Java project always includes these jar files that are a part of the
04:06Java runtime environment system library something I sometimes refer to as the
04:10Java class library.
04:12You're adding your own jar file to the build path and here is the easiest way to do it.
04:17Right click on the jar file, choose Build Path, Add to Build Path and now, all
04:23the classes that are in that jar file are available to your project.
04:27Now we're going to replace some of the existing code, I'll double-click the
04:31editor to expand it to full screen and then I'm going to select starting at the
04:36input stream declaration and ending at the close calls.
04:40You're still going to need to create references to your files, the source file
04:45and the target file, but all this other more complex code won't be needed
04:49anymore you can just delete it.
04:52Next, I'll call a method of the file utils class that's a member of the Apache
04:57Commons Library that I added to my project's build path.
05:01The particular method I need is a class method or a static method.
05:05So I'm going to call it directly from the class library, it'll be FileUtils.
05:12and here is a whole list of everything you're able to do with the class library,
05:16including copying files, getting directory information, moving files, reading
05:22files, and writing files.
05:24And I'm going to use a method called copy file.
05:27There are a few different versions of it, it's an overloaded method but I'm
05:31going to use this version that accept two file references.
05:34There are two required methods, the source and destination.
05:38I'll set the first to f1 and the second to f2 and that's it, that's all the code I need.
05:45I remove these TODO commons because I really don't need to do anything else,
05:48I'll save and run the application and I get the message file copied.
05:55I'll go back to my Package Explorer and I'll Refresh and I see my new target
06:02file has been successfully created.
06:04Now the magic of the Apache Commons approach is that you eliminate a whole
06:08bunch of complexity from your application, you'll notice that my application is
06:13showing these warnings about all the import statements my file still has but I'm not using.
06:19These are all the classes that were required when I was using the Java class
06:23library approach, that is, I was limiting myself to using only the tools that
06:28are available in the JRE.
06:30But when you expand your world to include the Apache Commons, life gets a whole
06:35lot easier, I'm going to organize my imports by choosing Source > Organize
06:40Imports, and now I see that the only classes I'm using are the File class and
06:46the Exception classes.
06:47The code within the Commons class still might throw those exceptions, so I still
06:52need to refer to them but everything else is greatly simplified.
06:56I strongly encourage you to take a look through the documentation for the Apache
07:00Commons Libraries, for example, in the IO page, there's a link for the Java doc
07:06for version 2.1 and the class that we are using FileUtils has a listing of all
07:11the methods that are available, but you'll also see that there are dozens and
07:15dozens of other classes available.
07:17And this is just one of the projects in Apache Commons, using the Apache Commons
07:22project can make your coding much simpler and your process of learning Java and
07:27making it useful for your applications a lot faster.
Collapse this transcript
Reading a text file from a networked resource
00:00The class library that's a part of the JDK includes a rich set of classes
00:05designed for network communications.
00:07Among the tasks that they support, they give you the ability to easily retrieve
00:12and read files over the web.
00:14I'll show you one approach to doing this, using the classes of the Java class library.
00:18I'll mention before I get started, that there are easier ways that require less
00:22code if you use the Apache Commons Library, but it's good to know what's
00:27available in the core class library first.
00:29I'm working in a project called NetworkFiles and a class called Read network
00:33file and I'm working with an empty main method.
00:38The first step in getting a network file is knowing its location.
00:42You should wrap the location in the file in an instance of a class named URL for
00:46Uniform Resource Locator.
00:48I'll type in the name of the class which is all uppercase and I'll press Ctrl +
00:52Spacebar, and choose the version in the package java.net.
00:57I'll name that variable url, all lowercase and then instantiate it, using the
01:02URL constructor method, I'll start with a pair of quotes.
01:07Now the purpose of the URL class is to wrap a string that indicates the location
01:11of the file, so now I need the file.
01:14I'll go to Internet Explorer, I'm going to be retrieving a dynamic XML feed from the web.
01:19Here is the URL http://services. explorecalifornia.org/RSS/tours.php.
01:31When you view this file in a browser, its format will differ from one browser to the next.
01:36In the Internet Explorer, it might be formatted the way you see here on the
01:39screen or if you're working in Chrome or Firefox, it might have a
01:43hierarchical presentation.
01:45But regardless of how it's presented visually the actual format is XML.
01:50You can see this in any browser by right clicking and choosing view source or
01:55some similar menu choice.
01:57That will open the raw format of the retrieved content and you'll see that it's
02:02an XML file and you also see that it's in RSS format.
02:06RSS is the format that's used for syndicated content.
02:10For example, if somebody has a site that's based on WordPress, typically you'll
02:15be able to get an RSS feed of their content from that site.
02:19So now that I've confirmed that this URL provides a valid XML feed, I'll copy
02:24the URL to the clipboard and return to Eclipse.
02:27I'll place the cursor inside double quotes that I use to pass in the value to
02:32the URL and I'll paste in the URL string.
02:35I'll maximize my editor so we can see all the code.
02:38You'll see an error occur over on the left, it's telling you about a potential
02:42unhandled exception, we'll deal with that later.
02:45The next step is to create an instance of a class named InputStream.
02:50I worked with this class in an earlier video, when I opened a file from
02:53the local file system.
02:55It's the same data type but this time I am going to create the reference to the
02:59object by calling a method of the URL class using URL.openStream.
03:06So now I have my connection to the file on the web.
03:09I'll place the cursor after InputStream, it looks like I didn't get my import
03:13statement and then press Ctrl + Spacebar and I'll make sure that I'm choosing
03:17the input string class from Java.I/O and there is the import.
03:21Next I'll create an object which is an instance of BufferedInputStream.
03:26I'll type the beginning of the class and then press control space and Eclipse
03:30automatically auto completes it and I'll name that object buff for buffered and
03:35I'll instantiate it using the class' constructor method new BufferedInputStream
03:40and I'll pass in the stream object.
03:42The purpose of the BufferedInputStream is to do the same sort of looping that I
03:47did in the file, allowing me to read one or more bytes at a time as I loop.
03:53Again, there is an indication of an error over on the left, don't worry about
03:57that I'll handle it later.
03:58Now we are ready to loop through the content of the file.
04:02I'm going to be reading the file this time one byte or one character at a time.
04:07In order to collect that data I'll create an object based on the
04:11StringBuilder class.
04:12I showed you how to use this class in an earlier video.
04:16The purpose of StringBuilder is to let you append content or insert content into
04:20a string without having to constantly rebuild the string object.
04:25I'll name the StringBuilder object sp and I'll instantiate it with
04:28its constructor method.
04:33Now I'm ready to loop through the file and read it one byte at a time.
04:37I'll create a while loop, I'll type the word while and press Ctrl + Spacebar and
04:42choose while loop with condition.
04:44And I'll set the condition to the keyword true, that means I'm going to keep
04:48on looping until I call the break command and that will cause the flow to jump out of the loop.
04:54Each time through the loop, I'm going to read a single character from the stream.
04:58The BufferedInputStream class has a method called read which returns a single byte.
05:03It will be returned as an integer initially, so I'll declare a variable named
05:08data and declare it as an int and I'll get its value from buf.read().
05:13The rules are that as long as there is an available character to read in the
05:17stream the read command will return an integer value representing that
05:21character, but if it's gotten to the end of the stream, and the end of the file
05:26it will return a value of negative one.
05:28So I'll take a look at the value that I just received, I'll use an if command
05:33and this will be an 'if' statement and the condition will be data has a value of
05:37negative one, if that condition is true that means that I'm at the end of the
05:41document and so I'll break out of the while loop.
05:45But otherwise which I'll put into the else block down here I'll append the
05:50value that was returned first converting it to a character using the syntax sp.append(data).
05:58But before I can pass that data value, I have to convert it to a character
06:02otherwise it'll be converted as a numeric.
06:05So I'll use casting syntax, I'll place the cursor before the data value and put in (Char).
06:13That means take the integer convert it to a character and then append it to the string.
06:18I'll place the cursor after the while loop and finally I'll output the value
06:24that I've collected using system.out. println and I'll just output the value of
06:30the StringBuilder object.
06:32You could if you prefer convert the StringBuilder to a string, if you're going
06:36to keep it around in memory for a while.
06:38Now I've still got these errors up I have to deal with.
06:41Each of the errors indicates that there is an unhandled exception that could
06:44occur, as with all such conditions you deal with them by wrapping the code
06:49inside a TryCatch block.
06:51So I'll select everything that I've coded inside the main method, I'll right
06:55click, I'll chose surround with TryCatch block.
06:59And Eclipse figures out which exceptions could occur and creates catch
07:04blocks for each of them.
07:05I will remove the TODO comments and my application should be complete.
07:09I'll Save and Run it and there is the result.
07:12The XML file is retrieved over the web and displayed in the Console.
07:17So again, this is one approach to retrieving files over the web and dealing
07:22with their content.
07:23Once you have the content in memory, you could save it to the local file
07:27system, you could display it on the screen in whatever sort of application
07:30you're working in, or because it's structured XML, you could search for and extract its data.
07:36This sort of coding using the class library of the JDK will work in any Java
07:42environment, regardless of whether you're working with Console applications,
07:46Web applications, Android applications, it's all the same code because it's all Java.
Collapse this transcript
Parsing an XML file with DOM
00:00There are many ways to read XML files in Java, there are many programming
00:05interfaces and packages available.
00:07They are known by their acronyms, there is JDOM and Stacks and Sacks, but the
00:12most venerable, the one that's been around the longest is known as DOM or
00:17Document Object Model.
00:18The Document Object Model approach to reading XML isn't the most fun or the most
00:23concise, but it's the most deeply embedded in the Java libraries.
00:27And so that's the version I'm going to show you here.
00:30I'm not going to show you everything about DOM that's something that would
00:33require a whole separate course, but I'll introduce you to some the most
00:36critical classes that are available.
00:39And as with the classes that I've shown you to read files from the local
00:42file system and from the network these are classes that are available in the
00:46core Java class library.
00:49As with the previous video, I'm going to be working with this XML feed at
00:53services.explorecalifornia.org/rss/tours.php.
01:00The code I'll show you will work with any RSS feed because the structure of an
01:04RSS file is standardized.
01:07So let's start with this empty glass.
01:09So the first step in reading an XML file is retrieving it and when you're
01:13working in the document object model world, your first goal is to create a document object.
01:19It takes a few classes to get there.
01:21I'm working in an empty project named parsexml in its class read XML and
01:26its empty main method.
01:28The first step is to create an instance of a class called document builder factory.
01:33I'll type outside DocumentBuild and press Ctrl + Spacebar and I'll choose the
01:38DocumentBuilder factory class from Javax.xml.parsers.
01:43And I'll name the variable factory.
01:45Now this code is going to get a little bit wide, so I'll maximize my editor and
01:50then I'll press Enter or Return and go to the next line and the
01:54DocumentBuilderFactory class is a class that you instantiate by calling it
01:58Static Method New Instance.
02:00So I'll call DocumentBuilderFactory.newInstance().
02:04Now I have an instance of that class and I am ready to go onto the next step,
02:08creating an instance of a class called DocumentBuilder.
02:11I'll type in the name of the class and I'll choose the class from
02:14Javax.xml.parsers the same package as the factory class.
02:20I'll name this one builder and I'll get its reference from
02:23factory.newDocumentBuilder.
02:26Now I'm ready to create my XML document object.
02:30The data type for this will be document, I'll type in the name of the class
02:34and press Ctrl + Spacebar and I'll make sure that I'm choosing the document
02:38class from org.w3c.dom.
02:42This document class implements the document object model programming interface
02:47as defined by the W3C.
02:50It's the same programming interface that you might use in JavaScript and in
02:54other programming languages, but it's specifically implemented for Java.
02:57I'll name this variable doc and I'll get its reference by calling the document
03:03builder classes parse method like this builder.parse and then I'll pass in the
03:10URL to the parse method.
03:12I'll go back to my browser, I'll copy the URL to the clipboard, I'll return to
03:17Eclipse, type in a double quote, paste in the URL close the string and close the statement.
03:24When you call the parse method, it takes care of the downloading of the file and
03:29parsing the document and turning it into a hierarchical set of objects that you
03:34can traverse using document object model programming.
03:38Once you have the document in memory, the next step is to get the data, you
03:42could walk down the XML tree one level at a time, but there's a really great
03:47convenience method that's a part of the document class named get elements by tag name.
03:52If you know the tags that is the element names in your XML file, then you know
03:57how to get the data out.
03:59So I'm going to create an object which is data typed as NodeList.
04:04In DOM a node list is kind of like an array, it's an ordered collection of objects.
04:10It has its own API which is a little bit different from an array as you'll see
04:14in a moment, I'll type in NodeList and press Ctrl + Spacebar and choose the Node
04:19List from org.W3C.dom.
04:23I'll name the variable list, and I'll populate it using the syntax
04:27doc.GetElementsByTagName and I'll pass in the name of an element I'm
04:32looking for, title.
04:34In RSS, each news item is named an item and each item element has a sub
04:41element named title.
04:43For this exercise, I'm only interested in the titles of the news articles.
04:48So that's what I'm retrieving.
04:49And now let's find out how many items we got back.
04:56I'll output a string, "There are" and then here's a way in which the node list
05:01class is different from an array.
05:04With an array, you determine the size of the array with its length property.
05:08With the node list you call a getLength method.
05:12It looks like this list.getLength I pressed Ctrl + Spacebar to auto complete the code there.
05:19Then I'll append the string items.
05:23I'll save my changes and see if there are any errors, I see one right here
05:27that I need to fix.
05:28It tells me that there's a syntax error here and I just missed my plus
05:31operator, here we go.
05:33I'll save that change, and see that there are errors from unhandled exceptions
05:37as I've done earlier exercises, I'll handle that by selecting the code and then
05:42surrounding the code with a Try Catch block.
05:45There are three possible exceptions and Eclipse generates catch block for each of them.
05:50I'll get rid of the TODO comments to shorten the code and then I'm ready to save
05:55and run the application.
05:56And I'm told that there are 27 items.
05:59So now, the next step is to go get the text value of each title element.
06:04In the document object model, each part of the XML file is seen as something
06:08called a node, and each node is of a particular type.
06:13So for example, let's say that you had an XML node that looked like this
06:17starting with title and ending with title and then between those tags some text.
06:24In the document object model, that's actually two separate notes, one parent and one a child.
06:31Title is an element node and the text within it is a text node, and if you know
06:38then you know how to get the text out from the title.
06:42I'm going to create a loop.
06:43I'll use a for loop to loop through the node list contents, I'll choose iterate
06:49over array and I'm going to keep on looping as long as my counter variable
06:54doesn't exceed the length of the node list.
06:57So I'll change args.length to lists.getLength.
07:00Within the for loop, I'll get the item in the list.
07:04I am going to data type the item that I'm retrieving as an Element.
07:08Once again, this is a class of the DOM interface.
07:13I'll name the object item and I'll set its value using casting syntax.
07:19I'm going to be retrieving an item from the list, the node list will return it
07:23as a note, the superclass but I know it's an element the subclass.
07:29I'll retrieve it, by calling the item method and passing in the "I" counter variable.
07:35Finally, I'll output the value within the element.
07:39To do this, I'm going to walk down the XML tree from the Element Node down to
07:43its Child Node, the Text Node.
07:46I know it's the first child of the element, because text nodes always are.
07:51So I'll use system.out.println and I'll output item.getFirstChild and then from
07:58there I'll call a method called getNodeValue.
08:02When you're working with a Text Node, the GetNodeValue method returns the string value.
08:07I'll save and run the application and there is the result.
08:11A listing of all the titles, from all the items within the RSS feed.
08:17Now if that seems like a lot of code, just to get titles you're right, it's more
08:22code than is really needed and if you switched over to one of the third-party
08:26libraries for working with XML and Java such as JDOM you'd find your code was
08:31significantly smaller and easier to work with but it's important to know what's
08:36available in the Java class library.
08:39When you're working with XML in the class library that's a part of the SDK the
08:43document object model is always available.
08:45It works in all Java development environments, Console applications, Web
08:50applications, mobile applications for Android and Blackberry, because as
08:55always it's just Java.
08:57There is obviously a lot to learn just about working with the document object
09:00model, but you can choose between that approach and the other libraries that are
09:05available in the Java community.
Collapse this transcript
12. Preparing an Application for Deployment
Creating your own JAR files
00:00The process of packaging a Java application for deployment is radically
00:04different from one platform to the next.
00:06You don't package a console application and a web application the same or a
00:10mobile application or a desktop application, they each have their own rules, but
00:15the one thing that all Java platforms have in common is the use of JAR files.
00:20A JAR file is a Java archive file, a compressed file in zip format that contains
00:26compiled Java classes, but has a file extension of .jar.
00:30I'm going to show you how to create a jar file from within Eclipse.
00:35You can also do the same thing from the command line using the JAR command from the JDK.
00:40I'm working in a version of my application called CreateJAR, and the first thing
00:44I'll do is Run the application and make sure that it runs correctly.
00:48This version of the application outputs the names of the olives that I'm
00:51crushing and how many units of oil I have and where the first all of this from.
00:57I do this before I try to package the application to make sure I'm running valid code.
01:02Now, to create the JAR File, go to the menu and choose File, Export.
01:08In the Export dialog choose Java, JAR File and click Next.
01:13Make sure you've selected your entire application including all of the
01:16applications packages, but deselect the options for the class path and
01:21project files on the right.
01:23These are Eclipse configuration files that you don't need to include in
01:26your deployed JAR File.
01:28The first option here in this list should be selected, Export generated class
01:33files and resources.
01:34For a console application that doesn't include any graphical assets or other
01:38files, you can deselect everything else.
01:41Next, indicate the location and name of your JAR file.
01:44I have already filled in the value with my project name and the name of the JAR
01:48file I want to create, separated with a slash character, use a backslash on
01:52Windows and a forward slash on Mac, alternatively you can click Browse and
01:58select a location anywhere on your disk to create the file.
02:01I am creating my JAR File in my project folder, Create JAR and I'm giving it a
02:06name of olivepressapp.jar.
02:09You can name the file anything you want, just make sure you don't include any
02:12spaces or special characters, but you must use a .jar extension.
02:17I've selected the option to compress the contents of the JAR File and
02:21deselected the other options.
02:23I'll click Next and show you these two options.
02:26For debugging I recommend selecting these options, Export class files with
02:31compile errors and warnings.
02:34For final production, you might want to deselect these options.
02:37And on this final screen, there are options for the manifest file.
02:42A manifest file is a text file that's automatically included in your JAR.
02:46It includes metadata about your application, but again, for a simple console
02:51application, you can accept all of these default values, click Finish and your
02:56new JAR File will be created.
02:58If you created it in your project folder as I did, it should show up right away
03:02in the package Explorer.
03:03Now let's take a look at the contents of the JAR File.
03:06I'll go to my desktop to my Exercise Files folder, from there I'll go down to
03:1012 Deployment to the Create JAR Folder and here's the .jar file that I just created.
03:17I'm going to copy it and paste it so that I create a new version, and then I'm
03:22going to rename this version of the file and give it a file extension of .zip.
03:26This will allow me to easily extract its contents, so I can see what's inside.
03:32Next, I'll extract its contents.
03:34On Windows, I'll right-click and choose Extract All and Extract.
03:40On Mac, just double-click on the file.
03:43If you have any special archive utilities installed on your system, such as
03:47WinZip on Windows, you can extract the file with that tool.
03:51Here is the contents of the JAR File, there is a folder called MetaINF in and
03:56within that the manifest file.
03:58I'll open that up with a text editor and show you that for a simple console
04:02application like this, it's pretty much empty.
04:05Now I'll go back to the main folder and show you that your packages have been
04:09translated to folders within the JAR file.
04:12Here is com, Lynda, olivepress, my main package.
04:17Here is my main compiled class and then within the press package, there is
04:21olivepress.class and within the olives package my three olive classes.
04:27So that's all a JAR File is. It's a zip file;
04:30it has a file extension of .jar, and its purpose is to package up your
04:34application for deployment.
04:36If you're using Java in another development environment such as say Android,
04:41take a look at the documentation for that development environment to learn about
04:45deployment options for that platform, regardless of how you're deploying your
04:49Java application, JAR Files are almost certainly going to be involved.
Collapse this transcript
Understanding the classpath
00:00Once you've packaged up an application as a JAR File you're ready to run it from
00:04the command line, but in order to run it from the command line, you need to
00:08understand how the concept of the class path works.
00:11I'll described how to use the class path and how to set it on both Mac and
00:15Windows in this exercise.
00:16I'm working in the class path project, a version of my olivepress application
00:21that I've already compressed into a JAR File.
00:24If you have access to the Exercise Files you can use this file or you can use
00:28any other JAR File that you want to create.
00:31I'm going to copy this file to my desktop, so I don't have to worry about the
00:35specific folder in which it's located, once I go to the command line.
00:39I'll right-click on the file and copy, then I'll go to the desktop and paste.
00:44Now, I'll open up a command window, on Windows, I'll run the cmd application
00:50and on Mac, open terminal, and then switch to your desktop folder, do a
00:55directory listing, type dir on Windows or LS on Mac, and you'll see the
01:01OlivePressApp.jar file there.
01:04Now, to run the application you need to know the complete path of the Main class.
01:09I'll go back to Eclipse briefly, and show you within Main.java that the package
01:15is com.lynda.olivepress, and the class is main.
01:21In order to run the class from the command line you need to know both of
01:24those bits of information, you'll put the package and the class name together
01:28separated with a dot, and that's how you launch the application using the Java tool.
01:33I'll go back to the command window and I'll try running the application the first time.
01:39I'll type java com.lynda.olivepress.Main, and I get the error could not find or
01:48load Main class and then the full path of the class that I typed.
01:52Now I typed that correctly, but the problem is that Java doesn't know where to
01:57find the class, here's how you tell it.
02:00You tell Java where the class is that you want to run by setting the class path.
02:05The class path is a list of file locations.
02:08Typically it starts with a single dot, meaning the current directory, and then
02:13lists all of the folders and JAR Files that contain compiled classes.
02:18You can set the class path either as part of the Java command or as an
02:22environment variable and I'll show you both.
02:25Here's how you incorporate the class path into the command that starts the
02:28application, start with Java and then - classpath, you can shorten that to -cp
02:36if you prefer, then type in a dot for the current directory.
02:40On Windows, add a semicolon on Mac or Linux add a colon, and then type in the
02:47name of your JAR File.
02:48I'll start by typing olive and then I'll tab, and on either Mac or Windows, that
02:53should auto complete the class path.
02:55Now type in the full path of your starting class com.lynda.olivepress.Main,
03:02make sure you spell it exactly correctly, it is case-sensitive, regardless of
03:07whether you're working on Windows or Mac press Enter or Return and the
03:11application should run.
03:12Now you can also set the class path as an environment variable, this works
03:17pretty much the same way on either Windows or Mac, but again the difference will
03:21be how you separate the values.
03:23You use a semicolon to separate the values on Windows and colon on Mac.
03:28This time I'll type SETCLASSPATH put it in all uppercase, it doesn't matter on
03:34Windows, but it does on Mac, and then an equals operator, and then just as I
03:39did before I'll type in a dot, then a ; on Windows or a : on Mac, and then the
03:45name of the file, and once again, I can type the beginning of the file name and press tab.
03:50I'll press Enter or Return and then this time I won't need to add the -class
03:56path argument to the command, because the value was already set in the
04:00environment variable.
04:01I'll type in java com.lynda.olivepress. Main, and now my application works again.
04:09When you set an environment variable this way, you're setting it only for the
04:13current command window session.
04:15For command on Windows or terminal on Mac, and when you close the command window
04:20or you close terminal, that setting will be lost.
04:23You could set this permanently in what Windows calls the system environment
04:27variables, or through a special file on Mac that I don't recommend doing it.
04:32It's better to create a batch file or a bash script to set these values if it's
04:37something you need to do over and over again, but again, you can set the class
04:41path either as part of the Java command, or as an environment variable,
04:46whichever works best for you.
04:48Once you know how the class path works, you can get started on your own Java
04:52applications, running them either from within Eclipse as we've been doing
04:55throughout the entire course, or in the command window, if that works better for
05:00your debugging purposes.
Collapse this transcript
Documenting code with Javadoc
00:00Java docs are files that you can generate out of your source code to document
00:05your code, because a well-designed Java application can contain dozens,
00:09hundreds or even thousands of Java classes, documentation is critical for
00:13long-term maintenance.
00:15As you code, it's a good idea to add comments to your code to describe how the
00:19classes are designed to work.
00:20Then later on you will be able to look at the documentation and figure out how
00:24the application was architected.
00:27The first step to generating Java docs is to add what are known as element
00:32comments into your code.
00:33An element comment is a comment that applies to a particular element of the
00:37code, such as a class, a method, a field and so on.
00:40Here's how you add an element comment.
00:42I'm working in a version of the project called Java docs and I'm in the Main
00:47class, I'll double-click the name of the class and then I'll go to the menu and
00:51choose source, generate element comment.
00:54Notice that there's a keyboard shortcut available for this.
00:58By default, Eclipse adds an annotation my name as the author.
01:03An element comment is like a block comment, it starts with a / and then *, but
01:08then it adds another * on the first line, that double asterisks is the indicator
01:13that this is an element comment that should be used by the Java Doc system.
01:18You can add other annotations to your element comments.
01:20I'll place the cursor on the next line and type in @ character and I'll get a
01:25list of the known annotations, and I'll choose version, and I'll set it to 1.0.
01:31You can also add your own comments.
01:33These typically go before the annotations.
01:36I'll place the cursor on the first line of the comment and press Enter or Return
01:40and I'll say This is the main class for my app.
01:45I'll Save that change and scroll down a little bit and show you that all of this
01:49class has a main method and I'll decide, I don't need to comment anymore of
01:53this, but I do want to add comments to some of my other code.
01:57So I'll go to the Olive class.
01:59I'll double-click the class name and choose Source, Generate element comment,
02:04I'll decide I don't need to put in my author information, I already have that in
02:08the Main class, but I will add a comment, This is a superclass for all olives.
02:15You can also add element comments for fields and methods, I'll double-click
02:20BLACK and choose Source, Generate element comment, and say This is for black
02:26olives and I'll double-click GREEN and generate the comment and say This is for green olives.
02:32I'll scroll down and select the crush method and add a comment for that and say
02:42call this to crush a single olive.
02:46Finally, I'll go to the kalamata.java file, and I'll comment this particular
02:52method which was only implemented on this particular class.
02:55I'll select the method name, add a comment, and I'll add This method is
03:01unique to kalamata olives.
03:06Now I'm ready to generate my Java docs.
03:09I'll make sure I saved all of my changes and I'll go to the menu and
03:12choose File, Export.
03:15In the Export dialog I'll select Java and then Java Doc and click Next, in this
03:21screen I'm asked what the Java.command is?
03:24If this value is blank, click the configure button and navigate your JDK
03:29installation folder, and then to the bin folder, and the java.command.
03:34Next, indicate what types you are going to generate Java docs for?
03:38I'd recommend selecting the entire application;
03:41this will make sure that you're generating Java docs for all packages and all classes.
03:46You can also be specific about which access modifiers you're creating Java docs for.
03:50I'd recommend the default of public.
03:54Next, Browse and indicate where you want to generate your docs.
03:58I've selected a new folder named doc under my project folder that value may
04:02appear by default on your system, but if it doesn't, browse and select it.
04:07Now I'll click Next, and here I'm asked if I want to include referenced archives
04:11and projects, I'll leave these all unselected.
04:15If you were to select any of these, you would also get Java docs for classes in
04:19the core Java class library, and you probably don't want to do that.
04:23You can also set an explicit document title and indicate which of these tags
04:28you want to document.
04:29I'll click Finish and it will take just a few moments to generate the Java docs.
04:35I'll close the window and here's my new doc folder in my project folder, if
04:39you don't see it there, try refreshing, right-click on the project and choose Refresh.
04:46I'll open the doc folder and I'll see a whole bunch of files that have been generated.
04:51The beginning file is named index. html working in Eclipse you can just
04:56double-click it, and it will open in a browser view.
05:00I'll double-click the tab of the browser view to expand it to full screen and
05:05here's all my documentation.
05:07I'll click into the olivepress package and see my main class and here's my
05:11comment "This is the main class for my app."
05:14Here is my version and here is the author information.
05:18Now, I'll go to the olives package over here and I'll click into the olive class
05:24and I'll see the comment, This is a superclass for all olives, and I'll also see
05:29the comments for my black and green static long fields.
05:32And finally I'll go to Kalamata, where I added the comment for the custom method.
05:37I'll scroll down to get origin, and there is my comment.
05:41Now, because this is being generated in HTML, you can use a certain small set of
05:46HTML tags to mark up your comments.
05:50I'll close the browser view and I'll go back to Kalamata, and I'll place the
05:55cursor before Kalamata and I'll add a beginning b tag, and then after Kalamata,
06:01I'll add a closing tag.
06:03I'll Save and then I regenerate the Java docs, I'll go to File, Export, Java
06:09Doc, Next, I'll make sure that I selected the entire Java docs application
06:14again, and then I'll click Finish and that will overwrite the existing files.
06:21I'll go back to my Doc folder, I'll open index.html, I'll go to Kalamata and
06:28scroll down, and there is the result.
06:31The word, Kalamata is bolded.
06:34So the last thing I'll show you is that in Eclipse there's a Java docs tab which
06:38will show you Java docs information for classes in your application.
06:42When you're working with classes from the Java class library, all you need to do
06:47is place the cursor in the name of the class and then look in the java.tab, and
06:51if everything is configured correctly, which it should be by default, you should
06:55see simple Java docs displayed there, but once you've generated your own Java
07:00docs, this will work for your application as well.
07:03I'll go to the Kalamata.java file and I'll click onto the getOrigin method
07:08and I'll see the Java doc comment that I just generated, this method is
07:12unique to Kalamata olives.
07:14It's a good idea as a Java programmer to get used to adding element comments as
07:19you create new methods, fields, and classes.
07:22That will then ensure that when you're ready to generate the Java docs, you
07:26don't need to go back and add all that documentation later on, that's a tough thing to do.
07:32If you do it in small pieces as you code, and as the purpose of the elements
07:36is fresh in your mind, it'll result in well-documented and well maintainable applications.
Collapse this transcript
Conclusion
Goodbye
00:00Hi! David here again.
00:02Thanks for watching this course, Java Essential Training.
00:05Learning the language is just the beginning, you're now ready to move on and
00:09learn how to build applications for a wide variety of Java development and
00:13runtime environments.
00:15If you're interested in mobile applications check out Lynda.com's course,
00:19Android App Development with Java Essential Training, or you might be
00:23interested in building web applications for Java Enterprise Edition Servers,
00:27such as JBoss and Tomcat.
00:29The Apache Commons project, which I described in the chapter about working with
00:33files has an enormous amount of existing code you can use to get your
00:38applications working quickly.
00:40However you plan to use Java, I hope this course gave you the information you
00:44needed to get started.
00:45Thanks and happy coding!
Collapse this transcript


Suggested courses to watch next:

Foundations of Programming: Fundamentals (4h 47m)
Simon Allardice



Are you sure you want to delete this bookmark?

cancel

Bookmark this Tutorial

Name

Description

{0} characters left

Tags

Separate tags with a space. Use quotes around multi-word tags. Suggested Tags:
loading
cancel

bookmark this course

{0} characters left Separate tags with a space. Use quotes around multi-word tags. Suggested Tags:
loading

Error:

go to playlists »

Create new playlist

name:
description:
save cancel

You must be a lynda.com member to watch this video.

Every course in the lynda.com library contains free videos that let you assess the quality of our tutorials before you subscribe—just click on the blue links to watch them. Become a member to access all 104,069 instructional videos.

get started learn more

If you are already an active lynda.com member, please log in to access the lynda.com library.

Get access to all lynda.com videos

You are currently signed into your admin account, which doesn't let you view lynda.com videos. For full access to the lynda.com library, log in through iplogin.lynda.com, or sign in through your organization's portal. You may also request a user account by calling 1 1 (888) 335-9632 or emailing us at cs@lynda.com.

Get access to all lynda.com videos

You are currently signed into your admin account, which doesn't let you view lynda.com videos. For full access to the lynda.com library, log in through iplogin.lynda.com, or sign in through your organization's portal. You may also request a user account by calling 1 1 (888) 335-9632 or emailing us at cs@lynda.com.

Access to lynda.com videos

Your organization has a limited access membership to the lynda.com library that allows access to only a specific, limited selection of courses.

You don't have access to this video.

You're logged in as an account administrator, but your membership is not active.

Contact a Training Solutions Advisor at 1 (888) 335-9632.

How to access this video.

If this course is one of your five classes, then your class currently isn't in session.

If you want to watch this video and it is not part of your class, upgrade your membership for unlimited access to the full library of 2,024 courses anytime, anywhere.

learn more upgrade

You can always watch the free content included in every course.

Questions? Call Customer Service at 1 1 (888) 335-9632 or email cs@lynda.com.

You don't have access to this video.

You're logged in as an account administrator, but your membership is no longer active. You can still access reports and account information.

To reactivate your account, contact a Training Solutions Advisor at 1 1 (888) 335-9632.

Need help accessing this video?

You can't access this video from your master administrator account.

Call Customer Service at 1 1 (888) 335-9632 or email cs@lynda.com for help accessing this video.

preview image of new course page

Try our new course pages

Explore our redesigned course pages, and tell us about your experience.

If you want to switch back to the old view, change your site preferences from the my account menu.

Try the new pages No, thanks

site feedback

Thanks for signing up.

We’ll send you a confirmation email shortly.


By signing up, you’ll receive about four emails per month, including

We’ll only use your email address to send you these mailings.

Here’s our privacy policy with more details about how we handle your information.

Keep up with news, tips, and latest courses with emails from lynda.com.

By signing up, you’ll receive about four emails per month, including

We’ll only use your email address to send you these mailings.

Here’s our privacy policy with more details about how we handle your information.

   
submit Lightbox submit clicked