Sei sulla pagina 1di 53

Skillsoft Course Transcript https://library.skillport.com/courseware/Content/cca/jl_jsee_a01_it_enus/...

Course Transcript

Java SE 8 Fundamentals: Introduction to Java


Getting Started with Java
1. Course Introduction

2. Introduction to Computer Programs

3. Introducing the Java Technology

4. Key Features of the Java Language

5. Setting up the Java Development Environment

6. Features of the Installed JDK

7. Overview of Compiling and Running a Java Program

8. Compiling and Running a Program

Creating a Java Main Class


1. Java Classes and Packages

2. Creating a Java Class

3. The Main Method

4. Creating a Main Method

Data In the Cart


1. Introducing Variables

2. Overview of the String Variable

3. Introducing the NetBeans IDE

4. Using String Variables

5. Introducing the int and double Numeric Data Types

6. Using Standard Mathematical Operators

7. Using and Manipulating Numbers

Managing Multiple Items


1. Working with Conditions

2. Using if Statements

1 of 53 11/27/2018, 5:45 PM
Skillsoft Course Transcript https://library.skillport.com/courseware/Content/cca/jl_jsee_a01_it_enus/...

3. Working with an Array of Items

4. Using an Array

5. Loops and Array Items

6. Using a Loop to Process an Array

Practice: Introduction to basic Java concepts


1. Exercise: Fundamentals of Java

2 of 53 11/27/2018, 5:45 PM
Skillsoft Course Transcript https://library.skillport.com/courseware/Content/cca/jl_jsee_a01_it_enus/...

Course Introduction
Learning Objective
After completing this topic, you should be able to
start the course

1. Introduction to the course


Java is a popular object-oriented programming language used by developers everywhere to create
powerful and secure applications that run on desktops, servers, home, media, and mobile devices,
and even smart cards. I'm Jamie Campbell and in this course I'll introduce you to the Java language,
show you how to create a Java main class, discuss various core programming principles, and
demonstrate structures like arrays, if statements, and for loops. I hope you enjoy the course.

3 of 53 11/27/2018, 5:45 PM
Skillsoft Course Transcript https://library.skillport.com/courseware/Content/cca/jl_jsee_a01_it_enus/...

Introduction to Computer Programs


Learning Objective
After completing this topic, you should be able to
describe the characteristics and purpose of a computer program

1. Computer programs
When learning how to become a computer programmer, the first place you need to start is with
understanding what computer programs are, and how they work. We use high-level languages like
Java, because it would be very difficult to write programs in the native language of computers – 1s
and 0s. So in this video, I'll introduce you to computer programs and explain concepts like compilers
and libraries. So what is a computer program? Well, it's a set of instructions that run on a digital
device, and those instructions perform certain tasks. When combined, these instructions form a
computer program. The program could be a word processing program, a photo-editing program, a
small application like a calculator, and it could even be a computer operating system, which is just a
very large and complex program. At the very core, at the machine level, computers speak in a
language of binary, that is 1s and 0s and we call the basic binary instructions machine code. You can
think of binary as an on or off relationship like a light switch, a 1 represents on and a 0 is off. These
instructions are processed extremely quickly by computers, and that's the basic premise of any
computer – 1s and 0s machine code. But no one creates programs using 1s and 0s, it would be very
difficult to do so because using a language with two characters, two letters really would be next to
impossible, certainly on a large scale.

[Heading: Purpose of a Computer Program. A computer program is a set of instructions that runs on a
computer or other digital device. At the machine level, the program consists of binary instructions –
ones and zeros, or machine code. Most programs are written in high-level code or readable code,
which must be translated to machine code.]

Fortunately, we don't have to develop programs with 1s and 0s, because we use something called
high-level code. High-level code means that programming instructions have been translated into
meaningful language, friendly, readable instructions that perform tasks, using words that are easy for
humans to understand. These high-level programs still need to be translated into machine code,
because that's how computers process instructions, but we have programs to do that for us and they
are called compilers. Compilers translate our programs, our high-level code, into machine code. And
it's important to know, that compilers need to be able to speak the same language as the computer
system. In other words platform, as the computer system, in other words platform, running the
compiler. So in this example here is some C Code on the left-hand side and that code won't change,
that is it's the same regardless of, it's the same regardless of the computer you're coding for. But
when it's compiled it needs to be compiled for the computer it's going to run on. There are three
different platforms here; a Solaris computer, which is UNIX, a Linux computer, which is similar to
UNIX, and a Windows computer. And each one has its own compiler that takes the high-level code,
and interprets it for that specific platform. It compiles the code into an executable file.

[Heading: Translating High-Level Code to Machine Code. A diagram illustrates computer code running
through three different platforms and being compiled. The code running through Solaris OS translates
to Solaris OS Binary, code running through Linux translates to Linux Binary, and code running
through Microsoft Windows translates to Microsoft Windows Binary.]

4 of 53 11/27/2018, 5:45 PM
Skillsoft Course Transcript https://library.skillport.com/courseware/Content/cca/jl_jsee_a01_it_enus/...

A compiler will combine the code with additional files, if there are any to create a platform dependent
executable, and in this example we have to compile it three times for three different platforms. There
is more to it though, because not only are there compilers that are written for specific platforms, there
are also Project Libraries, groups of instructions and tasks that help simplify the programming
process. For example, if you're writing an application and want to incorporate a File Open procedure,
something that pops up a window that allows a user to select and load a file, you don't have to
recreate that procedure from scratch every time you write a new program. And that helps simplify the
task of programming. There is a library for that and it will differ depending on the platform being used.
So during the compiling process, libraries are used along with the programming to create the
executable, the actual program that you run by double-clicking it. Libraries are reusable over and over
again, and it's important to know that the compiler will only use items that it needs from the library.

[Heading: Linked to Platform-Specific Libraries. Examples of binary code are Solaris OS Binary, Linux
Binary, and Microsoft Windows Binary. Each one runs through its respective operating system and
project libraries to translate to the respective executable file, namely Solaris OS Executable, Linux
Executable, or Microsoft Windows Executable.]

Different systems have different Project Libraries designed to work with those systems. Just like
compilers, the library meant for that system is used, and library files are linked to the specific program
that you design for a specific system. Once the library information has been compiled along with the
programming code, we have an executable, which can be run on the platform it was compiled for.
Those program files that you double-click to run, those are the binaries that have been compiled for
whatever platform you're using. And while this is a common theme for computer programming
languages, Java is different. Unlike C and C++, the Java programming language is platform
independent, which means that it doesn't need to be compiled three times for three different platforms;
it just needs to be compiled once. As long as you have a JVM, a Java Virtual Machine, installed on the
target computer, it doesn't matter what platform was used to compile it. And that's a very attractive
feature for software developers.

[Heading: Platform-Dependent Programs. The Solaris OS Executable file runs on Solaris OS


Workstation, the Linux Executable file runs on Linux Workstation, and the Microsoft Windows
Executable file runs on Microsoft Windows Workstation.]

5 of 53 11/27/2018, 5:45 PM
Skillsoft Course Transcript https://library.skillport.com/courseware/Content/cca/jl_jsee_a01_it_enus/...

Introducing the Java Technology


Learning Objective
After completing this topic, you should be able to
describe Java's role in the world, identify Java technology product groups, and list
the stages of a Java product life cycle

1. Introducing Java
In this video, I'm going to introduce the Java technology. To put things in perspective, Java is the most
widely used development language in the world today. Over 9 million developers report that they
spend at least some of their time developing Java, according to a recent Evans Data study. And that's
9 million out of about 14 million developers worldwide. Not only do developers like Java, so do end-
users. According to Nielsen Online and Gartner, 1.1 billion desktops run Java. Between 2009 and
2010 there were 930 million downloads of the Java Runtime Environment or JRE. The JRE is used by
end-users who wish to run Java applications. And during the same time period there were 9.5 million
downloads of the Java Development Kit or JDK. The JDK is used by developers for Java software
development. Java is everywhere. Today all non-smartphones commonly referred to as feature
phones run Java.

One hundred percent of Blu-ray players run Java. In addition, 71.2 million people connect to the web
on a Java-powered device. 1.4 billion Java Cards, the technology that securely runs Java on smart
cards, and other low-memory devices are manufactured every year according to InStep 2010. This
friendly looking character reading up on his Java code is Duke, Java's mascot. The Java
programming language was originally called Oak, and appeared on the scene in 1991 as part of a
research project to develop a programming language, that would bridge the communication gap
between consumer devices like VCRs and televisions. A team of skilled software developers at Sun
Microsystems, known as the Green Team, and under the leadership of James Gosling wanted to
create a programming language, that allowed consumer devices that used different central processing
units or CPUs, to share the same software enhancements. The initial concept failed after several
deals with consumer device companies proved unsuccessful. The Green Team was compelled to find
another market for their new programming language. Fortunately, the Worldwide Web was becoming
popular, and the Green Team recognized that the Oak language was perfect for developing
multimedia components that would enhance web pages. These small applications called applets
became the first practical usage of Oak. And programmers who developed for the Internet, quickly
adopted what soon became the Java programming language. The turning point for Java came in 1995
when Netscape incorporated Java into its browser.

Oracle provides a complete line of Java technology products, ranging from kits that create Java
technology programs, to emulation that is testing environments for consumer devices, such as cellular
phones. And you can see here all Java technology products share the foundation of the Java
language. Java technology, such as the Java Virtual Machine, are included in different forms in three
different groups of products, each designed to fulfil the needs of a particular target market. The figure
illustrates the three Java technology product groups and their target device types. Each edition
includes a Java Development Kit or JDK, also known as a Software Development Kit or SDK that
allows programmers to create, compile, and execute Java technology programs on a particular
platform. The JavaFX API or Application Programming Interface, is a rich client for creating user
interfaces for your Java program. The MSA API is the Mobile Software Application used to create user
interfaces on portable devices. Applets and applications differ in several ways. Applets are launched

6 of 53 11/27/2018, 5:45 PM
Skillsoft Course Transcript https://library.skillport.com/courseware/Content/cca/jl_jsee_a01_it_enus/...

inside a web browser, and applications are launched within an operating system as a standalone
program. Most of the concepts surrounding Java application development can be applied to applet
development. Java platform Standard Edition, commonly referred to as Java SE, is used to develop
applets and applications that run in web browsers and on desktop computers.

[Heading: Identifying Java Technology Product Groups. A table lists key APIs, languages, and
platforms for different products groups. The table consists of six columns and three rows. The column
headings are the product groups – Servers, Desktop, Embedded, TV, Mobile, and Card. The first row
lists key APIs, the second row provides platform information, and the third row lists the languages
used. The language used for all columns is Java. Servers and desktops use the Java SE platform,
and TV and mobile products use the Java ME platform. Embedded product groups use a combination
of both Java SE and Java ME platforms. Card products use the Java Card platform. The key API for
servers is Java EE. For desktop products, the key API is JavaFX. For TV, the key APIs are BD-J and
Java TV. The key API for mobile is MSA. There are no key APIs for embedded and card products.
Heading: Java SE. Java SE is used to develop applets that run within web browsers and applications
that run on desktop computers.]

For example, you could use the Java SE JDK to create a word processing program for personal
computer. NetBeans is a Java desktop application used for the development of Java applications. And
it's an Integrated Development Environment or IDE, which means that it provides a comprehensive
interface, and all the necessary tools needed for developing in Java. Java platform Enterprise Edition,
commonly referred to as Java EE, is used to create large enterprise, server-side and client-side
distributed applications. For example, you can use the Java EE JDK to create an e-commerce
application for a retail company's web site. Java EE is build on top of the Java SE platform, extending
it with additional Application Programming Interfaces or APIs, that support the needs of large scale,
high-performance enterprise software. The APIs are packaged and grouped to support different kinds
of containers, such as a web container for web based applications, a client container for thick clients,
and the Enterprise Java Beans or EJB container to run workhorse Java components. Some of the
kinds of functionality supported by the different APIs include objects, UI, integration, persistence,
transactions, and security.

[Heading: Java EE. Java EE is used to create large enterprise, server-side, and client-side distributed
applications.]

Java platform Micro Edition, commonly referred to as Java ME, is used to create applications for
consumer devices that are constrained by the resources. For example, you can use the Java ME JDK
to create a game that runs on a cellular phone. Blu-ray disc Java applications and Java TV use the
same SDK as Java ME. Java Card is typically used for securing sensitive information, that you'd
normally find on a smart card. And these examples are only a small sampling of the power of Java
Card. It can be used for things like identity, security, transactions, and mobile phone SIMs. In software
development, we talked about the Product Life Cycle. The iterative cycle that finds an end-to-end
process beginning with conceiving your software, and ending with the day your software isn't going to
be developed or supported anymore. The first stage is Analysis, which is the process of investigating
a problem that you want to solve with your software product. Among other things Analysis consists of
clearly defining the problem you want to solve, the market niche you want to fill or the system you
want to create. The boundary of a problem is also known as the scope of a project.

[Heading: Java ME. Java ME is used to create applications for resource-constrained consumer
devices. Heading: Java Card. Java Card is used for identity, security, transactions, mobile phone
SIMs, and many more purposes. Heading: Product Life Cycle, or PCL, Stages. The PCL stage starts
at the Analysis stage and moves through Design, Development, Testing, Implementation,
Maintenance, and finally End-of-Life, or EOL, stages.]

7 of 53 11/27/2018, 5:45 PM
Skillsoft Course Transcript https://library.skillport.com/courseware/Content/cca/jl_jsee_a01_it_enus/...

Simply put, scope is the big picture that encompasses every aspect of the software you want to
develop. You need to identify the key subcomponents of your overall product. So you understand the
needs of the project from beginning to end. Software developers and project managers, are very
aware that it's important to perform a thorough analysis of the problem. It leads to a good design of
the solution and to decrease development and testing time. The Design stage is the process of
applying the findings you made during the Analysis stage, to the actual design of your product. The
primary task during the Design stage, is to develop blueprints or specifications for the products or
components in your system. The Development stage, is when we use the blueprints created during
the Design stage to create actual components. Once those components have been created, we need
to test them. And the Testing phase is the stage when we test to ensure that individual components,
and the product as a whole meet the requirements, that we established for our software during the
Design phase. Testing is usually performed by a team of dedicated testers, who weren't involved in
the actual development of the product. This is because we want to ensure the product is tested
objectively and without any bias.

The Implementation stage, is where we deliver the software product and make it available to
customers. Of course, this leads into the next stage, Maintenance, because there are no testers quite
as rigorous as end-users. It's rare that any software is perfect at version 1.0. And it's inevitable that
users will take your software product through the paces, and discover things that weren't caught
during Development and Testing. So the Maintenance stage is when problems are fixed and the
software is re-released, either in the form of patches for marginal bug fixes and other minor changes,
and in the form of new versions when there are enough changes that a new version is merited. Finally,
there is the End-of-Life, the EOL stage. Although, the Product Life Cycle doesn't have a separate
stage for the commencement of a project, it does have a stage for the end of a project. EOL means
carrying out all the necessary tasks, to ensure that the customers and employees are aware that a
product is no longer being sold, and supported, and most commonly that a new product is available.
The Product Life Cycle is an important part of product development, because it helps ensure the
products are created and delivered, so that time-to-market is reduced, the quality of the product is
high, and the return-on-investment is maximized, meaning that the project isn't only on time but it's
also on budget. Developers who do not follow the Product Life Cycle often encounter problems with
the products that are not only costly to fix, but they could in fact have been avoided.

8 of 53 11/27/2018, 5:45 PM
Skillsoft Course Transcript https://library.skillport.com/courseware/Content/cca/jl_jsee_a01_it_enus/...

Key Features of the Java Language


Learning Objective
After completing this topic, you should be able to
describe the key features of the Java language

1. Java's key features


In this video, I'll discuss key features of the Java language. There are many key advantages to using
Java, but what sets it apart from other languages is that it's platform-independent, meaning that you
can develop on one platform with the intent of delivering it to others. In addition, Java is an object-
oriented language. Object-oriented programming is a broad subject but simply put, it allows you to
create and manage data objects that can be referenced in powerful ways. Java programs can run on
many different CPUs and operating systems, for example Solaris Unix on a SPARC chip, Mac OS X
on an Intel chip, and Microsoft Windows on an Intel chip, usually with few or no modifications. Java
programs are compiled using a Java Compiler, and the result of a compiled Java program is platform-
independent Java Bytecode, instead of CPU-specific machine code. Once the bytecode has been
created, it's interpreted by a bytecode interpreter called a Java Virtual Machine or JVM. A virtual
machine is platform-specific, meaning that it's designed to run on a specific OS, but it understands
that platform-independent bytecode that was created by the Java Compiler.

[Heading: Key Features of the Java Language. Some of the features that set Java apart from most
other languages are that Java is platform-independent and object-oriented. Heading: Java is Plaform-
Independent. A diagram shows that Java code runs through a Java compiler, via project libraries. The
result is Java Bytecode.]

For this reason, the Java programming language is often referred to as an interpreted language, and
Java technology programs are said to be portable or executable on any platform. This image
illustrates a Java Bytecode file executing on several platforms. Virtual machines get their name
because they are software applications that act like hardware, running code that's normally meant for
a CPU. For Java programs to be platform-independent, a virtual machine called the JVM is required
for every platform upon which your program will run. The JVM is responsible for interpreting Java
code, loading Java classes, and executing Java programs. However, a Java program needs more
than just a JVM to execute. A Java program also needs a set of Java class library specific to the
platform executing the JVM. Java class libraries are libraries of pre-written code, that can be
combined with the code that you write to create robust applications. Combined, the JVM software and
Java class libraries are referred to as the Java Runtime Environment, or JRE.

[Heading: Java Programs Run In a Java Virtual Machine. Java Bytecode, which includes the .class
file, and Java Virtual Machine, or JVM, can run on Solaris OS, Linux, and Microsoft Windows.]

Java Runtime Environments are available from Oracle for many common platforms. Early
programming languages were based on a programming paradigm called procedural. Procedural
languages use a sequential pattern of program execution one step at a time. You may have even
heard of some of these procedural programming languages: Cobol, Fortran, C and Pascal are all
procedural. This style of programming has become less popular, because it's difficult to design real-
world applications using sequential patterns. The world just doesn't work that way. And programs
written in procedural languages are difficult to maintain and enhance. So earlier, I mentioned object-
oriented programming. As I mentioned, one of Java's many powerful features is that it's an object-

9 of 53 11/27/2018, 5:45 PM
Skillsoft Course Transcript https://library.skillport.com/courseware/Content/cca/jl_jsee_a01_it_enus/...

oriented programming, or OOP language. OOP languages emerged in 1967 and have led to the
creation of popular programming languages, such as C++ upon which Java is loosely based. Object-
oriented programming differs from procedural programming, because procedural programming
focuses on a sequence of coding steps to solve a problem. But object-oriented programming stresses
the interaction of objects.

[Heading: Procedural Programming Languages. Many early programming languages followed a


paradigm called Procedural Programming. These languages use a sequential pattern of program
execution. The drawbacks to procedural programming include difficulty in translating real-world use
cases to a sequential pattern, difficulty in maintaining programs, and difficulty in enhancing programs
as needed. An image represents a sequential pattern. Step one is followed by step two, step two is
followed by step three, and so on, in order, up to step five. Heading: Java Is an Object-Oriented
Language. Java relies on the interaction of objects, with no prescribed sequence. The benefits include
modularity, information hiding, code reuse, and maintainability.]

One of the main goals of an OOP language is to create objects, pieces of a autonomous code that
can interact with other objects to solve problems. There are several benefits to doing this. First, is
modular, meaning the source code for an object is independent of the source code for other objects,
and objects can be easily passed around inside a system. Second, it's perfect for information hiding,
because the JRE only interacts with an object's methods. The details of its internal implementation
remain hidden from the outside world. Objects are also reusable. If an object already exits, maybe one
you wrote for another program or one written by another software developer, it can be used in new
programs. Finally, objects are powerful because they are highly maintainable. If a particular object is
found to be problematic, you can create another slightly modified one, and simply replace the original
one in your application. It's like fixing mechanical problems in the real world, if a bolt breaks you
replace the bolt not the entire machine.

10 of 53 11/27/2018, 5:45 PM
Skillsoft Course Transcript https://library.skillport.com/courseware/Content/cca/jl_jsee_a01_it_enus/...

Setting up the Java Development Environment


Learning Objective
After completing this topic, you should be able to
install, set up, and verify the JDK on Windows

1. Installing JDK on Windows


In this video, I'll explain how to set up the Java Development Environment. Now what we want is the
Java Development Kit, the JDK. So from any search window we can just go ahead and type JDK and
press Enter. And we have some options here, now the one I want is the Java SE Development Kit 8,
so I'll go ahead and click that link. And we're brought to that page, now if I scroll down a bit, you see
here are the various options we have for various operating systems. Now the first thing we have to do
is accept the license agreement, so I'll go ahead and click that. And once we've done that, we can
now click one of these download links. Now it really depends on the system you are using. In my
case, I'm using a 64-bit version of Windows, so that's the one I want right there, I'll go ahead and click
that. And at this point I can save it or run it. So if I save it, I'm saving it to the disk and then I have to
go and find it and install it, and I can certainly do that. I think I'll just go ahead and run it. Now if you've
already got a version of the JDK installed, the first thing that's going to happen is it's going to be
removed, so that's all automatic. We don't have to do anything we just wait, I had a previous version
installed, and it's going to remove that before it goes ahead and installs the new version.

[The presenter enters JDK in the Google Search bar and then clicks the Java SE Development Kit 8
link in the results. The Java SE Development Kit 8 Downloads site opens on the Downloads tabbed
page. The presenter scrolls to a section that lists various platforms, such as Linux x86, Mac OS X x64,
and Solaris x64. He selects the Accept License Agreement radio button and then clicks the link to
download the executable JDK file for Windows x64. A dialog box prompts the presenter to run or
save. The presenter clicks Run. A dialog box displays a progress bar, which tracks the progress of the
installation.]

Okay, so now we just go ahead and go through the settings for the installation. Click Next and there is
really very little reason to change any of these settings, but if you want to you can go ahead and
explore what's available here. I'll just go ahead and stay with the default settings, Next. Now we can
stick with the destination folder. There is very few reasons why you would want to change that, but if
you want to, you can do that with this button right here. I'll go ahead and click Next, okay we're done.
So if you want to you can click this button called Next Steps, and that'll take you through some
information about running Java, but I'll just go ahead and close this out. Close our browser and the
first thing I want to do is bring up our File Explorer, and go to drive C and then Program Files. And
there is our Java directory, so I'll go ahead and double-click that, and there is the JDK right there. Now
if I open that, there is a folder called bin, I'll go ahead and open that and bin is where all the binaries
are contained for Java. So we have Java program right there, we have the Java C compiler and a
bunch of other useful Java applications. Now what I want to do at this point is make sure that
Windows knows where to find these files. And the easiest way to do that is just click in the address
window here. When I do, it changes to the full address of the folder. Right-click that and choose Copy,
because I want to copy that on the clipboard. Go ahead and close that out.

[The Java SE Development Kit 8 Update 31 (64-bit) – Setup wizard displays a welcome message and
the presenter clicks Next. The Custom Setup page of the wizard lists features you can choose to
install, grouped under three nodes – Development Tools, Source Code, and Public JRE. It also lists

11 of 53 11/27/2018, 5:45 PM
Skillsoft Course Transcript https://library.skillport.com/courseware/Content/cca/jl_jsee_a01_it_enus/...

the installation address, in this case C:\Program Files\Java\jdk1.8.0_31\. The presenter clicks Next.
The Destination Folder page contains a Change button with the prompt Click "Change" to install java
to a different folder. The presenter clicks Next. A Progress page tracks the progress of the installation.
The Complete page then confirms that the JDK was successfully installed, and the presenter clicks
Close. The presenter closes the browser window and, using File Explorer, navigates to C drive -
Program Files - Java - jdk1.8.0_31 - bin. The bin folder contains files such as javac.exe, javadoc.exe,
and jar.exe. The presenter clicks the File Explorer address bar and the address displays as
C:\Program Files\Java\jdk1.8.0_31\bin. He copies the address and closes the File Explorer window.]

So I want to go to our Start screen and then type in adv and as I start to type, we see View advanced
system settings here. I'll go ahead and click that. Now in System Properties under Advanced, we have
a button here called Environment Variables, what I want to do is click that and then in the lower
window scroll down until I find Path, there it is right there. So I'll go ahead and click Edit. And the path
contains all the various paths that Windows is going to use, when it's locating programs. And at the
very end of the path, I'll put a semicolon that separates different paths. And then just right-click and
choose Paste. And that pastes in that link that we've just, or the file location that we just copy from
Explorer. I'll go ahead and click OK and OK and OK to close that out. Now at this point you'll have to
reset your system to make sure the path variable took. I've already done that, so let's go ahead and
go back to our Start screen, and bring up the command prompt with cmd.

[The presenter navigates to the Start screen and begins typing to open the Search pane. He enters
adv in the Search text box. He then clicks View advanced system settings in the search results list.
The System Properties dialog box opens on the Advanced tabbed page, and the presenter clicks the
Environment Variables button. The Environment Variables dialog box contains User variables and
System variables tables. In the System variables table, the presenter selects the Path variable, which
is currently set to C:\ProgramData\Oracle\Java\javapath;... He then clicks Edit. The Edit System
Variable dialog box contains two text boxes – Variable name and Variable value. The variable name is
Path and the variable value is set as Files (x86)\Microsoft SDKs\TypeScript\1.0\ In the Variable value
text box, the presenter types a semicolon, followed by the copied path C:\Program Files\Java
\jdk1.8.0_31\bin. He then clicks OK to accept the changes and close the remaining windows.]

Now from the command prompt and the reason I changed the path variable, is so that you don't have
to be in that bin directory whenever you execute a Java program. You should be able to do it from
anywhere in the file system in Windows. So you can see that right now, I'm at C:\Users\Jamie and I'll
go ahead and just type java, and this will tell me that the path variable took, press Enter and there
we go. So we're into Java, that's great, everything is working wonderfully. And when you type java
and press Enter, if you don't put any arguments after java, you'll have this great Help section come
up that'll give you some information, about the various switches and options that you can use with the
Java application.

[The presenter accesses the Search pane and types cmd in the Search text box. A Command Prompt
window opens. The prompt is currently set at C:\Users\Jamie>. At the prompt, the presenter enters
the command java. The output is as follows: Usage: java [-options] class [args..] <to execute a
class> or java [-options] -jar jarfile [args...] <to execute a jar file> The output also includes a Help
section with a list of switches and options for the Java application.]

12 of 53 11/27/2018, 5:45 PM
Skillsoft Course Transcript https://library.skillport.com/courseware/Content/cca/jl_jsee_a01_it_enus/...

Features of the Installed JDK


Learning Objective
After completing this topic, you should be able to
describe the features of the installed JDK on Linux and Windows

1. Installed JDK features


In this video, I'll discuss features of the installed JDK. The Java SE, short for Standard Edition
Development Kit, includes the tools and classes used to develop a Java program. The tools and
utilities are stored in the bin directory seen here. They include a Java Virtual Machine, which is also
known as a JVM for the platform you are using. The example here is from a Linux computer, and the
runtime engine is started by running the Java program. There is also a Java compiler, which is started
by running the program javac. Then there are additional utilities, such as tools for creating Java
archive files, which are known as jar files, and for debugging Java programs.

[Heading: Examining the Installed JDK – Linux Example: The Tools. Under the java node, the jdk1.8.0
folder includes a bin folder. It's to this folder that the PATH variable points. The bin folder contains a
number of files, including the files java and javac, which launch the runtime compiler.]

As well, there is a bin directory, which must be in the system path in order to run or compile a Java
program. Normally, this is something you don't need to worry about, as the Java installer automatically
adds the bin to your system path. And it's worth mentioning that the Java Runtime Environment,
called the JRE, used in production is also included with Java SE Development Kit, and it can be found
in the JRE directory. In addition to the executable files found in the bin directory of the JDK, various
class libraries are installed, and they conform to the particular platform that you are using. This
example is from a Windows computer. The core libraries are found in the lib directory seen here. The
Java Runtime engine requires these libraries. In addition to the Java SDK download, other items are
available as a separate download, such as the Java Class Library or API documentation and the Java
Language Specification.

[Heading: Examining the Installed JDK – Windows Example: The Libraries. Under the Java node in
File Explorer, the jdk1.8.0 folder contains the subfolders bin, db, docs, include, jre, and lib. The lib
folder contains a number of files, including the LIB files jawt.lib and jvm.lib.]

13 of 53 11/27/2018, 5:45 PM
Skillsoft Course Transcript https://library.skillport.com/courseware/Content/cca/jl_jsee_a01_it_enus/...

Overview of Compiling and Running a Java


Program
Learning Objective
After completing this topic, you should be able to
describe how to compile and run a Java program and describe the ways a Java
program can output data

1. Introducing Java programs


In this video, I'll provide an overview of compiling and running a Java program. This diagram
illustrates what happens when you compile and run a Java program. In the first step, the Java code is
created in a file with the extension .java. This is called the Java source code. Then you use the
javac executable to compile the source code, the c stands for compiler, into a bytecode file with the
extension .class. This is called a Java class. You use the Java executable to run the Java class.
This is your Java program. Compiling converts the source file that you create into a bytecode, that
could be executed by Java Virtual Machine. The source file has a .java extension. It also defines a
public class of the same name, for example, the class SayHello must be saved in a file called
SayHello.java. To compile the SayHello source code, you perform the following steps. First,
go to the directory where the source code files are stored. Second, enter the following command for
each .java file that you want to compile. It's important to note that the .java extension is required.

[Heading: Compiling and Running a Java Program. From left to right, a flowchart lists the items .java,
javac, .class, and then java. The source code is contained in a .java file. The code is compiled by java.
The result is a .class file in bytecode. The class file is then executed by the Java Runtime. Heading:
Compiling a Program. Two steps are listed. First, go to the directory where the source code files are
stored. Second, enter the command for each .java file you want to compile, using the syntax javac
SayHello.java. An example is SayHello.class.]

So in this example you type javac SayHello.java and once the compilation has finished,
assuming no compilation errors have occurred, you'll have a new file called classname.class, in this
case SayHello.class in your directory for each source code file that you compiled. When you've
successfully compiled your source code files, you can execute and test them using the Java Virtual
Machine. To execute and test your program, you first go to the directory where the class files are
stored, then you enter the following command for the class file that contains the main method. Note
that here the file extension .class should not be included. So when we type java SayHello
and this command runs the SayHello class, which contains the main method. The main method is
the entry point to a Java application, and the Java executable only works with a class containing a
main method. In this example, the main method contains code that prints a string Hello World!.
Java provides many options for outputting data and here are a few common examples. You can send
data to other destinations such as a file database, to the console, which is the command line screen,
found in various operating systems, or you can send the data to a web page or other user interface.

[Heading: Executing or Testing a Program. Two steps are listed for executing a program. First, go to
the directory where the class files are stored. Second, enter a command using the syntax java
<classname> for the class file that contains the main method. An example is java SayHello. Note that
you do not specify .class. The output, given the example, is Hello World! Heading: Output for a Java
Program. A Java program can output data in many ways. For example, it can deliver output to a file or

14 of 53 11/27/2018, 5:45 PM
Skillsoft Course Transcript https://library.skillport.com/courseware/Content/cca/jl_jsee_a01_it_enus/...

database, to the console, or to a web page or other user interface.]

15 of 53 11/27/2018, 5:45 PM
Skillsoft Course Transcript https://library.skillport.com/courseware/Content/cca/jl_jsee_a01_it_enus/...

Compiling and Running a Program


Learning Objective
After completing this topic, you should be able to
compile and run a Java program and view its output

1. Compiling and running a Java program


In this video, I'll demonstrate how to compile and run a Java program. I've got a Java program here
called Hello.java. Now keep in mind that Java programs are simply plain text files. And so you can
create a text file in an operating environment like Windows for example. And it's important to
remember that in Windows, by default that extension, that txt extension is going to be hidden by
defaults. There is one thing we need to do. I'll go ahead and bring up Control Panel on the Start
screen, locate Folder Options, click the View tab and make sure that this is unchecked. By default,
Hide extensions for known file types, is going to be checked. We want to uncheck that because if
we don't, what's going to happen is, if we create a file, text file called Hello.java it's actually going to
be Hello.java.txt. And even though we don't see that extension, it's still considered to be a text
extension and we will have problems compiling. So we need to make sure that's turned off, I'll go
ahead and click OK and okay and so there is our file. Now what we want to do is bring up our
command prompt, so I'll click on the Start button, type cmd for command, press Enter. And then
change to our directory that contains the file, so cd Documents...

[In File Explorer, the presenter has navigated to the path This PC - Documents - Java SE - programs.
The programs folder contains the file Hello.java. The presenter navigates to the Control Panel and
clicks Folder Options. The Folder Options dialog box opens on the General tabbed page by default.
The presenter clicks the View tab. The View tabbed page contains a Folder views section with Apply
to Folders and Reset Folders buttons. It also contains an Advanced settings table, which lists a
checkbox for each of several settings. The presenter selects and then clears the Hide extensions for
known file types checkbox and clicks OK. He then closes the Control Panel. The presenter switches to
the Start screen and accesses the Search pane. he enters cmd in the Search text box and a
Command Prompt window opens. The prompt is currently C:\Users\Jamie>. At the prompt, the
presenter enters the command cd Documents\Java SE\programs The prompt changes to C:\Users
\Jamie\Documents\Java SE\programs>.]

and if I do a directory search now, there's our file right there. There's our file right there. Now the Java
compiler is javac, like that, and then you just put a space, and then type in the name of the Java file,
so Hello.java and press Enter. Okay that's great, now we don't get any feedback and that's
good news. If we got feedback then something might have gone wrong. The Java compiler is going to
check to see that that program is properly written. If it encounters any errors, you get those errors fed
back to you during this process. If you get no feedback that means we had a successful compile. Now
if I go back to this folder, you'll see the compile process created a file called Hello.class. And that's the
program that we want to run, so I'll go back to my command prompt and then we use the java
command and then Hello. It's a class file and we don't put in the .class extension, we don't need to
do that, I'll go ahead and press Enter, great, our program worked. So that's how you compile a Java
program from the command prompt using a couple of simple commands, javac to compile the
program and java to run the program.

[At the new prompt, the presenter enters the command dir. The output is as follows: Volume in drive C
has no label. Volume Serial Number is D8F9-CEA2 Directory of C:\Users\Jamie\Documents\Java

16 of 53 11/27/2018, 5:45 PM
Skillsoft Course Transcript https://library.skillport.com/courseware/Content/cca/jl_jsee_a01_it_enus/...

SE\programs 01/29/2015 10:22 AM <DIR> . 01/29/2015 10:22 AM <DIR> ..


01/29/2015 10:26 AM 115 Hello.java 1 File<s> 115 bytes 2
Dir<s> 12,023,910,400 bytes free Next the presenter enters the command javac Hello.java No
output is returned. The presenter switches to the File Explorer window. The programs file now
contains two – Hello.class and Hello.java. The presenter returns to the Command Prompt window and
enters the command java Hello The output is Hello world!]

17 of 53 11/27/2018, 5:45 PM
Skillsoft Course Transcript https://library.skillport.com/courseware/Content/cca/jl_jsee_a01_it_enus/...

Java Classes and Packages


Learning Objective
After completing this topic, you should be able to
describe Java classes and packages

1. Java classes and packages


The Java programming language uses certain building blocks, that form the structures of Java
programs. They are called classes and packages, and they are the starting points for the creation of a
new program. So in this video, I'll introduce you to classes and packages in Java and explain how
they are declared. A Java class is the building block of a Java application. In this example, we have
got a Java program called ShoppingCart.java that includes code, that allows a customer to add items
to the shopping cart, and it provides visual confirmation to the customer. A class is declared using the
keyword class followed by the class name. In the example here, the class name is Hello with a
capital h. Convention dictates that the class name starts with a capital letter, and it's important to
remember that Java is case-sensitive. If there are two words in the class name, for example SayHello,
each word should begin with a capital letter. It's a programming notation called Pascal case, where
you use capitals for new words instead of spaces, because space can't be used in certain
circumstances. You may have heard of Camel case. You may have heard of Camel case, which is
similar to Pascal case except that in Camel case the very first letter is always lowercase.

[Heading: Java Classes. A Java class is the building block of a Java application. As an example,
ShoppingCart.java includes code that allows a customer to add items to a shopping cart and provides
visual confirmation to the customer. Heading: Program Structure. A class consists of the class name,
which begins with a capital letter; and the body of the class, which is surrounded with braces – {}. The
body includes data called fields and operations called methods. An example of a class is public class
Hello { // fields of the class // methods } Note that Java is case- sensitive. The "c" in class should be
in lowercase and the "H" in Hello should be in uppercase.]

The keyword public is called a modifier. There are different types of modifiers. Some of which are
used to determine, how other parts of the application can access the section in question, in this case
our class. The entire body of the class is surrounded by braces, one to open and one to close.
Classes typically contain data called fields and operations called methods. Packages provide a
namespace for classes. Think of a package as a folder where a class will be saved and the folder
name, the package, is used to uniquely identify the class. Package names always begin with a
lowercase letter. Using packages when you create Java classes isn't mandatory, but it's strongly
recommended. And I want to call attention to the semicolon after the statement package
greeting. Semicolons are required at the end of each statement in Java, think of it like the period
at the end of a sentence. The sentence may wrap to another line, but it isn't complete until it's given a
period. The Java compiler interprets a statement as being complete when it encounters the
semicolon. If you do any programming with languages like C++, C# and other similar languages the
rule is the same, make sure you put the semicolon at the end of every complete line of code.

[Heading: Java Packages. A package provides a namespace for a class. This is a folder in which the
class will be saved. The folder name, or the package, is used to uniquely identify the class. Consider
the following code: package greeting; public class Hello { // fields and methods here } In this
example, package greeting is the package name and the unique name of the class is greeting.Hello.]

18 of 53 11/27/2018, 5:45 PM
Skillsoft Course Transcript https://library.skillport.com/courseware/Content/cca/jl_jsee_a01_it_enus/...

Creating a Java Class


Learning Objective
After completing this topic, you should be able to
create a Java class and use the Output window to view any syntax errors

1. Building a Java class


In this video, I'll explain how to create a Java class. Okay, so for this example, I'm just going to show
you how to create a Java program using a text file. I'll right-click, choose New - Text Document. Now,
what I want to do is change everything including that three-letter extension, so I'm going to call this
Hello.java. Use the three-letter Java extension, I'll go ahead and press Enter. We get a message
here asking are you sure you want to change that three-letter extension text. And we do, because
we're creating a Java file, even though it's a text file it's got the .java extension. Click Yes, right-click
that, choose edit with my Notepad editor and here's our blank file. So to create a class we just type
this, public class. Use a capital letter here, Hello, so I'm going to call this one Hello. It's
really up to you what you want to call it, but the program itself is called Hello.java, so I'm going to use
Hello and then put in opening and closing braces. So I'm going to add a couple of lines here, and
there is our class. Now it's really important to remember that this is our class name right here, we use
the public class text before that and then put in our braces. And then anything contained inside
these opening and closing braces becomes our class. We can start creating our program from here.

[In File Explorer, the presenter has navigated to the path This PC - Documents - Java SE - programs.
He right-clicks blank space in the pane listing the contents of the programs folder and selects New -
Text Document. A new file, by default named New Text Document.txt, is listed in the programs folder.
The presenter renames the file Hello.java. A Rename dialog box displays the message "If you change
a file name extension, the file might become unstable. Are you sure you want to change it?" The
presenter clicks Yes. Next the presenter right-clicks the Hello.java file and selects Edit with
Notepad++. The file, which is empty, opens in Notepad++ and the presenter types the following code:
public class Hello { }]

19 of 53 11/27/2018, 5:45 PM
Skillsoft Course Transcript https://library.skillport.com/courseware/Content/cca/jl_jsee_a01_it_enus/...

The Main Method


Learning Objective
After completing this topic, you should be able to
describe the role of the main method in a Java program

1. The main method in Java


In this video, I'll discuss the main method. In Java programming, a method is a group of instructions
that are intended to perform some sort of function. For example, if you had a program that allowed
users to type in a bunch of numbers, and then calculate the result. You might create a method, so that
when the user is ready, okay program I've entered all my numbers now and I would like to calculate
them, there is a method that performs the calculation of those numbers. In Java, there is always a
main method. It's a special method, that the Java Virtual Machine recognizes as a starting point for
Java program. So every program that you create needs to have a public main method. Why
public? Because it's the main method and it has to be available to the entire program. Remember,
we can create other methods besides the main one, but the main method is well, it's the main one.
And if a class contains a main method, it's referred to as a main class. So the syntax is always the
same as seen here. The information contained in the parenthesis, is meant for arguments that may
get passed to the main method, say if you had some data that you needed to pass to the main
method for it to execute. So at a command line for example, if you type the command java my
program, followed by a, b, c and those letters are separated by spaces, then args in the main method
would now contain three texts strings a, b and c. Also note that the brackets, the square ones, can be
placed after String or after args, but normally they are right after String.

[Heading: The main Method. The main method is a special method that the JVM recognizes as the
starting point for every Java program. The syntax for the method, which is always the same, is as
follows: public static void main (String args[]) { // code goes here in the code block } Note that the
entire method body is surrounded with braces.]

So here's a simple example of a class called Hello and it includes a main method. The reason
we know the class includes the main method, is that the entire main method is encased within the
braces of the class. See there is the opening brace right after Hello on the first line. And at the very
bottom there is Hello's closing brace. In this example, the main method sends the message to the
console Hello World!, and this is your program output. Also, note that the double forward slashes
begin two of the lines, these are comments and they are ignored by the compiler. Comments are an
important part of computer programming. They let programmers create notes inside code, that could
explain what the following lines are meant to do, provide instructions for other programmers and even
explain procedures and settings. Programming code can get very long very quickly, and one of the
most important tools the programmers need to learn is to use the comment. Usually, the first
command new programmers learn is this one, the command that displays something on the screen,
the output. In Java, the command is system.out.println method to print a message to the
console. Now note that I say print, but it really means send to the display or if you prefer print to the
display. The println or print line command is familiar in many programming languages, and it's a
carryover from the early days of programming when there were no computer monitors. Normally, you
would have a printer or a punch card printer, so that that command is still in use today,

[Heading: A main Class Example. An example of a main class is as follows: public class Hello {

20 of 53 11/27/2018, 5:45 PM
Skillsoft Course Transcript https://library.skillport.com/courseware/Content/cca/jl_jsee_a01_it_enus/...

public static void main (String [] args) { // Entry point to the program. // Write
code here: System.out.println ("Hello World!"); } } In this example, Hello is the class
name. The main method consists of all the code other than public class Hello. The comments section
is as follows: // Entry point to the program. // Write code here: The program output
is provided by the line System.out.printIn ("Hello World!"); Heading: Output to the Console. The
syntax for writing output to the console is System.out.println (<some string value>); An example is
System.out.println ("This is my message."); The string literal is "This is my message."]

...and so that command is still in use today. Note that inside the parenthesis, we use quotation marks
to enclose the text of the message we want to display. This is called a String literal. In programming,
string means one or more alphanumeric characters, or other characters like the asterisk, ampersand,
percentage and so on. In a programming environment, it's important to be able to read your code and
understand what you're reading. New programmers look at code and it might as well be another
language, because it is. But the more you learn, the more understandable the code becomes to you.
A good programming environment provides a programmer with code hinting, which is a way of
showing the code in a meaningful and more understandable way. The Java code console does this by
using color hinting for example, keywords such as class are purple, string literals are blue. Another
way the console helps is by providing output in a window at the bottom of the screen. When you click
Run, the JRE will attempt to compile your code and then run it. If there are any syntax errors, which
are errors that break the rules in the way Java code must be written, that will be caught during
compilation.

[Heading: Fixing Syntax Errors. If you have made a syntax error, the error message appears in the
Output panel. Common errors include missing semicolons, missing close quotation marks, unmatched
braces, and unrecognized words. In the case of unrecognized words, check for case-sensitive errors.
An example of code with a missing semicolon is package exercise; public class hello {
System.out.println ("Hello World!") } In this example, the semicolon is missing after
System.out.println ("Hello World!"). The output from the code will be POST error: error, Internal
Server Error.]

The only problem is that error messages aren't always friendly. Sometimes they will point you exactly
to the problem, but other times they may not help much. So programmers need to be detectives and
understand some of the common programming errors. Common errors are an unrecognized word and
this could mean a word that was spelled correctly, but if you didn't use a capital letter when you should
have, that'll be caught as an error. It might be that you misspelled a method or class name or if you
got the case wrong. Remember, Java is case sensitive, and here we see a big red circle after the only
line in the Hello class, something is missing. It's very common to forget that semicolon at least at
first. When you have written enough code, the semicolon will be like putting a period at the end of the
sentence, it will be automatic. But still look out for the missing semicolon, because it does happen and
it will kick back an error. Another common offender is the missing opening or closing quotation mark,
this will definitely cause an error. And so will unmatched or missing brackets, parenthesis or braces.
Remember braces represent a beginning and an end. And you can nest other sets of braces inside
braces, so it's important to ensure that they are properly nested.

21 of 53 11/27/2018, 5:45 PM
Skillsoft Course Transcript https://library.skillport.com/courseware/Content/cca/jl_jsee_a01_it_enus/...

Creating a Main Method


Learning Objective
After completing this topic, you should be able to
add a Java main method to a class

1. Adding a Java main method to a class


In this video, I'll show you how to create a main() method. Okay, so I've already got a file set up
called Hello.java, and we've created our class, public class, and it's called Hello, that's the
class name. Now we have our opening and closing braces – right there is the opening one, right there
is a closing one – and anything inside those braces is going to constitute our class or the contents of
our class. And here is where I create the main() method. So I'll create a line here, and then type
public static void, and then main in lowercase, m-a-i-n. And then after main I put in
parentheses. Now inside the parentheses I have to put this: String with a capital "S", and then
opening and closing brackets, and then a space, args for arguments.

[An empty file named Hello.java is open in Notepad++. In the file, the presenter types the following
lines: public class Hello { public static void main (String[] args) }]

Now we don't have any arguments and that's fine we can leave that as it is right now, but I'll go ahead
and put a space here, and put in an opening brace and the closing brace is automatically created for
me, and I'll add a line. Now anything contained with inside these braces is going to constitute the
main() method, and remember the main() method is the starting point of any Java program, and
so anything in this line right here, and any subsequent lines that I add, will constitute the main()
method for a Java program. So I'll just go ahead and start with a simple comment, and it always helps
to indent a bit, so I'll go ahead and add a tab there, put in two forward slashes for our comment, and
say, this is our main method, where we create the starting point for our
program, just like that, and that becomes the main() method that's used in Java as the beginning
point for any program.

[The presenter adds to the code. The completed code is as follows: public class Hello { public static
void main (String[] args) { // this is our main method, where we create the starting point for our
program } }]

22 of 53 11/27/2018, 5:45 PM
Skillsoft Course Transcript https://library.skillport.com/courseware/Content/cca/jl_jsee_a01_it_enus/...

Introducing Variables
Learning Objective
After completing this topic, you should be able to
describe variables in Java and outline the guidelines for naming variables

1. Variables in Java
No matter what programming language you use to create programs, variables are a common element
that we use to store, read, and manipulate data. In many ways they're the basis of all computer
programs and Java's no different. So in this video, I'll introduce you to variables and explain the
guidelines for using them. A variable is simply a storage location in memory that holds a specific
value. It's called a variable because its value can be changed over and over again by assigning a
different value to it. And when I say value I mean anything, not just numbers. Variables hold specific
types of data, some are meant to hold numbers, and even then you can have variable types for
integers, different types for numbers with decimal numbers, and so on. And then there are String
variables like the example here. We assign variables with the equal sign, so here the variable that's of
type String and called firstName contains four characters that spell the name Mary. Variables
are always declared as a type. Simply put you have to decide what kind of data you want the variable
to contain and then use a declaration to state this is the type variable. It's then followed by the name
of the variable, and you can assign an initial value to it if you want to using the equal sign followed by
the value. Assigning a value is optional during declaration, but declaring its type is mandatory.

[Heading: Variables. A variable refers to something that can change. Variables can be initiated with a
value, which can be changed. A variable holds a specific type of data. Consider the following line:
String firstName = "Mary"; In the line, String refers to the type of data, firstName is the name of the
variable, and "Mary" is the value of the variable. Heading: Variable Types. Some of the types of values
a variable can hold are String, int, double, or boolean. An example of a String variable is "Hello"; an
example of an int variable is 10,0,2,1000; an example of a double variable is 2.00, 99.99 and
-2042.09; and a boolean is either true or false. If uninitialized, variables have a default value. The
default value for an empty String is "", the default value for an int is zero, and the default value for a
double is 0.0. The default value for a boolean is false.]

Some of the most common variable types are strings which can contain any combination of text,
whether that text is represented by letters, special characters, or even numbers. Of course numbers in
strings aren't treated as numbers, you can't apply mathematical operations to them, at least not easily,
because Java is treating them merely as characters. Also it's important to note that in strings, Java
treats uppercase and lowercase letters as different items, so a lowercase "a" and an uppercase "A"
are going to be seen as being different. That's important because there are operations that you can
perform on strings to determine the characters they contain, very important for long strings especially.
I-N-T or int stands for integers which are whole numbers either positive or negative. Doubles are real
numbers meaning that they can use decimal values; they can be positive or negative. Boolean
variables have one of two values, either true or false. There are many other variable types but these
are the most common variable types. As I said earlier, you don't have to assign a default value when
you're declaring a variable, if you don't then the new variable will be assigned its default value. The
default values for a String, int, double and boolean are shown here. Note that there's one
exception, something called local variables which are variables inside methods, but we don't need to
get into that here. Also note that String begins with an uppercase letter, and this is important
because Java is case sensitive so you need to use that capital "S".

23 of 53 11/27/2018, 5:45 PM
Skillsoft Course Transcript https://library.skillport.com/courseware/Content/cca/jl_jsee_a01_it_enus/...

There are rules and guidelines about variable names that you need to know. First you should begin
each variable name with a lowercase letter, and then capitalize the first letter of each subsequent
word. This method is called camelCase. Think of the humps of a camel and those are the capital
letters. There's also something called PascalCase which is similar, except that the first letter is also
capitalized, but that shouldn't be used for variable names. Variable names like everything else in Java
are case sensitive, so if you had a variable called score with lowercase "s", and Score with an
uppercase "S", they'd be treated as unique variables. Obviously it isn't a good idea to do this though,
in any computer program you're going to end up with a lot of different variables and it's important to
give them meaningful names and make them easy to track in your code, so you should spend some
time thinking about how you'll name a variable. Variable names cannot have spaces, which is why we
have camelCase, and once again it's important to think about the variable name and what it will
represent in your program. It's always a good idea to write your code as if you expect someone else to
come along later and try to figure it out, so you need to make it as sensible as possible. In this
example, we have a boolean variable called outOfStock, and that make sense because it's either
in stock or out of stock and Booleans are true or false variables. And itemDescription is a
String, again a sensible choice, because a description of something is going to be a string of
characters.

[Heading: Naming a Variable. The guidelines for naming a variable include beginning each variable
with a lowercase letter. Subsequent words should be capitalized – for example, myVariable. Names
are case sensitive and cannot include white space. Names should be mnemonic and should indicate
to the casual observer the intent of the variable. For example, outOfStock holds a boolean and
itemDescription holds a String.]

As a programmer you'll use variables all the time in everything you do, the Java programming
language is no exception. Some common uses for variables include holding data that needs to be
used by a method. These are pretty typical examples of different variable types that you'd use. You
can also use variables to assign the value of one variable to another. In the example here, the variable
called name, which was initialized above and given the value "Sam", is being reassigned. Now we're
changing name and using whatever value is in a variable called name1. So if name1 had the value
"Sally", name now also has the value "Sally". Variables are also used to represent values in a
mathematical expression. Here we're assigning a new value to the variable called total, and its new
value is whatever value is in quantity multiplied by whatever value is in price. The asterisk is a
standard symbol for multiplication. If quantity was 10 and price was 20 then total would
equal 200. We can also use variables to perform other operations like printing values to the screen. In
this example, the System.out.println() method will display the value stored in the variable
called name.

[Heading: Uses of Variables. Variables can hold data used within a method. Examples are String
name = "Sam"; double price = 12.35; boolean outOfStock = true; Variables are also used to assign the
value of one variable to another. An example is String name = name1; Variables can represent
values within a mathematical expression, as in the example total = quantity * price ; Variables may
also be used to print values to the screen, as in the example System.out.println(name);]

24 of 53 11/27/2018, 5:45 PM
Skillsoft Course Transcript https://library.skillport.com/courseware/Content/cca/jl_jsee_a01_it_enus/...

Overview of the String Variable


Learning Objective
After completing this topic, you should be able to
describe how to work with the Java String variable

1. String variables in Java


In this video, I'll provide an overview of the String variable. The syntax for declaring and initializing
a variable is type identifier and optionally the initialization which is an assignment of value.
When you declare a variable you can initialize it, meaning give it a starting value or you can leave it
empty. The type represents the type of information or data held by the variable. In these examples
you can see that we're declaring String variables, identifier is the variable name. In the very
first example, the variable name is customer; the second example shows how you can declare
multiple variables of the same type on a single line without initializing them by separating the values
with a comma. The third example both declares and initializes the variable called address, and in
initializing it we've given it a value of "123 Oak St". It shows how to declare and initialize multiple
variables of the same type. Once again, each initialization is separated by a comma. And you can mix
and match these, meaning that you can declare and initialize some, and declare but not initialize
others on the same line using this method.

[Heading: Variable Declaration and Initialization. The syntax for declaring and initializing a variable is
type identifier [= value]; For example, the following code declares one variable: String customer; This
code declares two variables: String name, city; This code declares and initializes a variable: String
address = "123 Oak St"; The following code declares and initializes two variables: String country =
"USA", state = "CO";]

Strings are variables that contain alphanumeric data, text, and numbers. And just like we can add
number variables by using the + sign, we can also add String variables, this method is called
concatenation. You can concatenate a String variable to another String variable. You can also
concatenate a string literal to a String variable. In the example, we're declaring two variables and
initializing them with two words, "Hello" and "World", and then we add them together. And in the
third example, we add a string literal and an exclamation mark to the end. In the last example, we're
doing something a bit different; we're adding a number, 2014 to the string. And this is perfectly okay;
you can concatenate numbers to String variables. It's important that you know that it's no longer
treated as a number when you do this, the compiler will convert the numeric value to its string
equivalent. In these examples, we have two variations of printing out string data by using
System.out.println() method. In the first example, the variable named message that you saw
in the previous slide will be printed. In the second example, the expression containing the
concatenation of variables plus string literals can be used within the method parentheses. The
concatenation will be performed by the runtime engine before the println() method is executed.
As you can see, the output of both methods produces the same results.

[Heading: String Concatenation. String variables can be combined using the '+' operator, using the
following examples of syntax: stringVariable1 + stringVariable2 stringVariable1 + "String literal"
stringVariable1 + "String literal" + stringVariable2 Code examples are as follows: String greet1 =
"Hello"; String greet2 = "World"; String message = greet1 + " " + greet2 + "!"; String message = greet1
+ " " + greet2 + " " + 2014 +"!"; Heading: String Concatenation Output. You can concatenate String

25 of 53 11/27/2018, 5:45 PM
Skillsoft Course Transcript https://library.skillport.com/courseware/Content/cca/jl_jsee_a01_it_enus/...

variables within a method call, using the syntax System.out.println(message); Alternatively, you can
use the syntax System.out.println(greet1 + " " + greet2 + "!"); The output in both cases is Hello
World!]

26 of 53 11/27/2018, 5:45 PM
Skillsoft Course Transcript https://library.skillport.com/courseware/Content/cca/jl_jsee_a01_it_enus/...

Introducing the NetBeans IDE


Learning Objective
After completing this topic, you should be able to
describe the benefits of an IDE, and create, compile, and troubleshoot a Java project
and class in NetBeans IDE

1. Using the NetBeans IDE


In this video, I'll introduce you to the NetBeans IDE. IDE stands for Integrated Development
Environment, and it simply means a program that can make it easier to develop software applications.
Even though programming languages like Java are in plain text format, we can only do so much with
the text editor, because like other languages Java has a structure of files and folders, that are used to
create and compile the programs you write. IDEs typically have a code editor, a file browser, or project
navigator pane, an output window, a code navigator of some sort, and other features that make
software development much easier. An IDE provides syntax checking which makes it easier to identify
errors in your code. They usually provide various features that can help to automate certain tasks.
And they provide a runtime environment that lets you compile, execute, test and debug your code.
IDEs are usually very good at organizing all your resources into projects. Some well-known IDEs for
Java are Eclipse, JDeveloper and NetBeans, and I'll introduce you to NetBeans, which is an open
source application freely available from NetBeans.org.

[Heading: Java IDEs. A Java Integrated Development Environment, or IDE, is a type of software that
makes it easier to develop Java applications. An IDE provides syntax checking, various automation
features, and runtime environments for testing. It enables you to organize all your Java resources and
environment settings into a Project. As an example, a Projects tabbed page lists the node
AnagramGame. It contains folders such as Source Packages, Test Packages, Libraries, and Test
Libraries. The Source Packages folder contains two subfolders. The com.toy.anagrams.lib subfolder
contains the files StaticWordLibrary.java and WordLibrary.java. The com.toy.anagrams.ui subfolder
contains the files About.java and Anagrams.java. Next the presenter switches to the home page for
the NetBeans IDE web site, at the URL https://netbeans.org.]

Installation is very straightforward, you can download NetBeans from NetBeans.org, and I'll go ahead
and just click on there and then the Download button. And you'll see all the various versions that are
available for NetBeans, so you can develop in a number of different Java versions as well as some
other languages as well. Now note that you can also combine, sorry. Now note that you can also
download a combination of the JDK, the Java software Development Kit, with NetBeans in this case
8.0.2 from Oracle, so you can get it here as well. And the thing is, if you download it from
NetBeans.org, you do have to have the Java Development Kit already setup on your system in order
to install it. And I like this feature because simply put, you can download it here and actually have it
installed the Java Development Kit, alongside NetBeans which is great. So I'll go ahead and close
this. Now I didn't down – sorry, let me start that again. Now the installation really is very
straightforward, so there is no need to show you that, it's a pretty step-by-step simple installation. And
once it's installed, you'll see the icon for NetBeans on your desktop, I'll go ahead and double-click that
to run it.

[On the NetBeans IDE site, the presenter clicks the NetBeans IDE tab. A page titled NetBeans IDE
Features contains a Downloads button and describes features of the IDE. The presenter clicks the
Download button. The NetBeans IDE 8.0.2 Download page contains a table that lists supported

27 of 53 11/27/2018, 5:45 PM
Skillsoft Course Transcript https://library.skillport.com/courseware/Content/cca/jl_jsee_a01_it_enus/...

technologies, such as Java SE, Java EE, and C/C++, and the NetBeans IDE download bundles
available for each of these. The presenter switches to a browser tab in which the Oracle web site is
open on the Java SE Downloads - NetBeans page. The Downloads tabbed page contains the Java
SE and NetBeans Cobundle table, which lists supported products, such as Linux x86, Mac OS X x64,
and Windows x86, along with their file sizes and links for downloading the appropriate versions of
Java SE with NetBeans. The presenter closes the browser and double-clicks the NetBeans icon on
the desktop.]

Now when you run it for the first time you are going to see this welcome screen on start page. And
let's go ahead and just create a new project, so File - New Project and you have a number of
different options here. Generally speaking, the normal default option will be Java, Java Application,
click Next. And then we'll give the application a name, so something like mycart, call it mycart
application. You can see that down here there is an option for creating a main class, which is normally
something that you want to do. Unless you want to create your classes or your main class manually
once you've created the project, but I'll go ahead and just click Finish. Okay, so here we are now. It's
going to set up that Java application, that main class application for you as you can see right here,
and it's even putting some comments in there by default right here and here and here and here, just to
sort of give us a structure that we can work with. Now, the first thing I want to do is show you how to
create a new class. So over here in the project navigator you'll see there is, it's a hierarchy, and there
is the mycart project and underneath it is Source Packages and then mycart, which is the package for
application or a project and then the single file, mycart.java.

[The welcome screen for NetBeans IDE 8.0.2 contains a menu bar, a toolbar, and three main tabs –
Learn & Discover, My NetBeans, and What's New. The My NetBeans tab, which is open by default,
contains links to recent projects and an Install Plugins option. The presenter selects File - New
Project. The New Project wizard opens on the Choose Project screen, which contains a Filter text box,
a Categories pane, and a Projects pane. It also contains a Description pane, which provides a
description of the currently selected project. The Categories pane contains the options Java, JavaFX,
maven, NetBean Modules, and Samples. Java is selected by default. The Projects pane contains the
options Java Application, Java Class library, Java Project with Existing Sources, and Java Free-Form
Project. Java Application is selected. The presenter accepts the default options and clicks Next. The
Name and Location page of the wizard contains Project Name, Project Location, and Project Folder
text boxes. It also contains two checkboxes – Use Dedicated For String Libraries and Create Main
Class. The Create Main Class checkbox has an associated text box. The presenter changes the
default project name, JavaApplications, to mycart. The Create Main Class text box automatically
updates from javaapplication8.JavaApplication8 to mycart.Mycart. The presenter then clicks Finish.
The new project opens in the NetBeans IDE, which includes three panes. The first pane contains
Projects, Files, and Services tabs. It's open on the Projects tab, which lists the contents of the mycart
project in Source Packages and Libraries folders. The Source Packages folder contains the mycart
package, which contains the Mycart.java file. The second pane is the Navigator pane. It currently
displays the main node, Mycart, which contains the entry main(String[] args). The third pane, which is
the main pane, contains two tabs – Start Page and Mycart.java. On the Mycart.java tab, the toolbar
includes Source and History options. The Source option is currently selected and the tab lists the
following code: /* * To change this license header, choose License Headers in Project Properties. * To
change this template file, choose Tools|Templates * and open the template in the editor. */ package
mycart; /** * * @author Jamie */ public class Mycart { /** * @param args the command line
arguments */ public static void main (String[] args) { // TODO code application logic here } }]

Now what I'll do is I'll right-click on the mycart package, and you'll see a New option right here and
right here we have the option for Java Class, so I'll go ahead and click that. And you can give it a
name and I'll call this Item. And you can also choose the package that you want to attach it to, if you
have multiple packages or different packages you can choose there. We only have the one package

28 of 53 11/27/2018, 5:45 PM
Skillsoft Course Transcript https://library.skillport.com/courseware/Content/cca/jl_jsee_a01_it_enus/...

mycart. So once I've given it a name I'll go ahead and just click Finish and there is our new class.
Now notice that when I click on that, if I click on Mycart.java you'll see down here in the Navigator
that this has changed now. Now this is the Navigator that allows you to sort of get some information
on your packages, and the various classes that are available in Java. So it's context sensitive, so
when you click there the navigator is going to change. Right now, we are on the main Mycart.java, the
main class. And if I hover that mouse over it you're going to get some help that pops out there, so it's
really useful in any IDE, sorry, in any IDE. And NetBeans is no exception, where you can actually
have this help available to you as you hover over things. And if I click here you'll see that now our
Navigator has changed, so I click on the Item.java class and we'll see that change, so we have some
options there.

[The presenter right-clicks the mycart source package on the Projects tab and selects New - Java
Class. The New Java Class Wizard opens on the Name and Location page, which contains Class
Name and Project text boxes, Location and Package drop-down list boxes, and a Created File text
box. The presenter changes the class name from NewClass to Item and points out the Package drop-
down list box is set to mycart. He then clicks Finish. The Item.java tab is added to the main pane. It
contains the following code: /* * To change this license header, choose License Headers in Project
Properties. * To change this template file, choose Tools|Templates * and open the template in the
editor. */ package mycart; /** * * @author Jamie */ public class Item { } Item.java is also listed under
the mycart package in the Projects pane, and the Navigator pane lists the Item class. The presenter
selects Mycart.java in the Projects pane. The Navigator pane then lists Mycart with the class
main(String[] args). The presenter hovers the cursor over the class and a Source pop-up box displays
the following code: mycart.Mycart public static void main (String)[] args) Parameters: args - the
command line arguments The presenter selects Item.java in the Projects pane and the Navigator
pane displays Item once more.]

Now you also notice that the file Item.java, the class file has opened as well. So when you create a
new class or any objects in NetBeans, it's going to open it up for you automatically and create that
syntax, that starting syntax for you. Now I'll go back to the Mycart.java, because I want to show you
how the code navigator works. So the code navigator is really simple to use and it just works like any
text editor, and we'll go ahead and just start typing. Okay, now when I press the period after System,
you can see that you get this help popup, and this is the really useful thing about an IDE like
NetBeans, is it gives you this context help where you can actually go ahead and sort of go through
and say, well this is what I was planning on typing. So in this case, we know that we wanted to do
System.out.printline, I'll just go ahead and just type out., and you can see once again that help has
come up and here we can see all these different options available to us. And if I type in p, it's going to
keep narrowing that down to the different options that are available to us, so this is a really great
feature that I like. So this is a really great feature that I love about NetBeans and I'll go ahead, and just
double-click that, and that will autofill that in for us, so you can do that really easily. And I'll just type
our first text in here, Hello world,

[The presenter returns to the Mycart.java tab. He positions the cursor below the lines: public static
void main (String[] args) { // TODO code application logic here The presenter types System,
followed by a period. A pop-up menu lists options such as err, console, exit, and clearproperty (String
key). The err option is highlighted and a second pop-up box displays the code java.lang.System public
static final PrintStream err Both java.lang.System and PrintStream are links. The pop-up box also
provides information about the "standard" error output stream, noting that it's ready to accept output
data and explaining its typical use.. The presenter scrolls through the list of options in the pop-up
menu but doesn't select an option. Instead he types the word out, followed by a period. A new pop-up
menu lists options such as append, close, and getClass(). A second pop-up box displays information
about the currently selected option. The presenter types p and a pop-up menu displays options
starting with p, such as print (float f), println(), and println(char x). The presenter double-clicks println()

29 of 53 11/27/2018, 5:45 PM
Skillsoft Course Transcript https://library.skillport.com/courseware/Content/cca/jl_jsee_a01_it_enus/...

and it is automatically entered in the line of code. The presenter finishes the new line by typing "Hello
world" between brackets. The new line is System.out.println("Hello world");]

and there you go. Now note that everything is color coded here and that's one of the great features of
any IDE, it's going to give you that color coding, that helps you differentiate between different items in
your code. Keywords will be one color, certain system related words will be another, text strings will be
another and so on, so you can actually differentiate that. And also as you click on any object for
instance or word I should say, I'll click on public and okay it didn't work here, so let me go ahead and
try something else here, I'll just type System right there. Now you see as I type that, that both these
words become highlighted, so it'll actually highlight the different words, and if there are multiple
instances of that in your code, it'll highlight all of them. And the really nice thing about that is that you
can quickly click on say a variable or a constant, and it will highlight all the variables or constants of
that name in your code, and it makes it really easy to sort of search out and find your various code
aspects, using this feature. The other thing you should notice too, is that right now the second
instance of System is red underlined. It'll give you that red underline to indicate that there is a
problem, a syntax error of some sort or some other sort of error. And if I hover over it, it'll tell you that
then this just pops up just by hovering the mouse over the word, that semicolon is expected and that
this isn't a statement,

[The presenter positions the cursor below the line System.out.println("Hello world"); The presenter
types System. The word System is highlighted in both lines and the second instance of System is
underlined. The presenter hovers the cursor over the second instance of System and a pop-up box
displays the following message: ';' expected not a statement --- (Alt+Enter shows hints)]

and it even gives us a little hint there that says Alt+Enter shows hint. So if I press Alt and then Enter,
it'll show us some various hints as to what we can do to fix our code. So that's a really great feature of
an IDE, I'll go ahead and delete that because we don't need it, that you can use these visual cues to
help you develop your code. Now once your program is finished, what you can do is you can go up to
the Run menu and just run the project, and you can just press F6 if you want to. But I'll just go ahead
and select Run Project and it might take a second to compile. But here we go, we have our Output
window, and the Output window just shows us whatever output we need to get from our application. In
this case, that single line that says, Hello world, and it gives us a nice green cue here telling us
that the build was successful. So IDEs are very powerful, NetBeans is a great package for developing
your Java code. It's very easy to get your hands on and install, and once you've got it installed and
you up and running, you'll be able to write your Java, I'm sorry. And once you've got it installed and up
and running, you'll be able to start writing your Java programs quickly and easily.

[The presenter presses Alt+Enter and a pop-up box lists various hints for correcting the code. The
presenter deletes the second instance of System. He then selects Run - Run Project (mycart). The
Output - mycart (run) pane displays the following output: Hello world BUILD SUCCESSFUL (total
time: zero seconds)]

30 of 53 11/27/2018, 5:45 PM
Skillsoft Course Transcript https://library.skillport.com/courseware/Content/cca/jl_jsee_a01_it_enus/...

Using String Variables


Learning Objective
After completing this topic, you should be able to
use String variables in a Java program

1. Using Java String variables


In this video, I'll demonstrate how to use String variables. Okay, so I've got my program set up and
I've got my main() method here, so let's go ahead and start creating some strings. We use the
capital "S" for String, and then we'll give the variable a variable name, and we'll assign it
something. So inside quotation marks, "Mary Smith". Put a semicolon in. We're going to create
three strings, custName, itemDesc, and finally I'm going to create a message. Now because the
message is something we're going to display to the screen, we don't have to give it a value yet, we're
going to do that in a second. As a matter of fact, we'll create it right now: message = custName –
remember that's the first variable that we created containing "Mary Smith" – use a + sign, and then
we're going to put in a string literal, so " wants to purchase a " – and notice that I've put spaces
before and after those words, that's because we want to put in physical spaces otherwise Mary Smith
will butt up against wants, so we want to make sure that we do that – another + sign and then
itemDesc.

[In the NetBeans IDE, a Java project named ShoppingCart is open. The ShoppingCart.java tab
contains the following code: package shoppingcart; public class ShoppingCart { public static void
main(String[] args) { } } A pane with Refactoring and Output tabs is open below the file. The
presenter adds to the code in the ShoppingCart.java file. In full, the code is as follows: package
shoppingcart; public class ShoppingCart { public static void main(String[] args) { String
custName = "Mary Smith"; String itemDesc = "shirt"; String message; message =
custName + " wants to purchase a " _ itemDesc } }]

And that's the message, now once we've created the message we need to display that to the screen
so we're going to use System with a capital "S", .out.println for print line, and then
(message). So remember we created that variable message here, and here we're assigning the
message to the values, the first string custName, we've added that string literal to it, and then
we've added the itemDesc, that's the second string that we created, to get the message itself which
we're going to display to the console. So let's go ahead and try it out and see how it worked. Okay, so
there you go, there's your output, Mary Smith wants to purchase a shirt. It's a really simple process
once you get familiar with creating strings and concatenating them together. Concatenate means to
add together, or to combine using that plus symbol, and there we have a wonderful explanation. Let
me say that again. So this is a really good example of how you use concatenation, which simply
means putting together, adding together, and we add them together using that plus sign. And we've
taken these three strings, the first two we've combined with the string literal to get that third string
which we've output to the console.

[The presenter places the cursor after the line message = custName + " wants to purchase a " _
itemDesc He then adds the line System.out.println(message); Next the presenter selects Run - Run
Project (Shopping Cart). The output is as follows: Mary Smith wants to purchase a shirt BUILD
SUCCESSFUL (total time: one second)]

31 of 53 11/27/2018, 5:45 PM
Skillsoft Course Transcript https://library.skillport.com/courseware/Content/cca/jl_jsee_a01_it_enus/...

Introducing the int and double Numeric Data Types


Learning Objective
After completing this topic, you should be able to
describe how to use the int and double numeric data types in Java

1. The int and double numeric data types


In this video, I'll introduce the int and double numeric data types. The int data type stores 32 bits
of data. This means that you can store whole numbers, numbers without any decimal places, within a
pretty large range, between -2.14 billion and +2.14 billion. Now it might be tempting, but remember
that you can't use commas in your code to make numbers more readable when you assign values to
them. However, you can use underscores to make your code more readable as shown in the third
example; the compiler will ignore these underscores. If you print the numbers to system output the
underscores won't appear. The only benefit of this is readability in your code, and there are ways to
display large numbers for output using commas and other international numerical notations but that
requires advance string operations and some other programming magic that you'll learn as you go
along. The double data type stores 64 bits of data and this allows you to store even larger values,
either negative or positive. When we need greater precision or accuracy we use decimal numbers.
Here the example shows an extremely large number with four decimal points of precision, the
negative whole number of -1111.

[Heading: int and double Values. Variables of the int type hold whole number values between
-2,147,483,649, and 2,147,483,647. Examples are 2,1343387 and 1_343_387. Variables of the
double type hold larger values containing decimal portions. This type of variable is used when greater
accuracy is needed. Examples are 987640059602230.7645, -111, and 2.1E12.]

And the third example shows the decimal number using exponential notation which is indicated by the
capital "E". When you initialize variables it's important that you assign the right kind of value to them. If
you try to initialize an integer with a string for example, you'll get an error. And here we're initializing
two int variables, the first value being assigned 10 is perfectly valid, it's an integer, but in the second
example we're using a decimal number and that will throw an error with the compiler. In the second
example both assignments are valid double data types. Now you might be wondering about that
second example where we're assigning 75 as a double data type. Wait a second, it's an integer?
Well, that's okay; integers are perfectly valid because they're part of the overall numbering scheme.
Just because you can use decimals with double numbers doesn't mean you have to, but you might
ask why we've an integer variable type at all if we can use integers in double variable types. Well in
computer programming, just keep in mind that there are times when you need integers and times
when you need precision numbers, and when you begin to write code, you'll learn the difference pretty
quickly.

[Heading: Initializing and Assigning Numeric Values. An example of a statement that correctly assigns
a value to an int variable is int quantity = 10; In the following statement, however, the value is
inappropriate and will cause the compilation process to fail: int quantity = 5.5; Examples of
statements that correctly initialize double variables are double price = 25.99; double price = 75; In the
second example, 75 will be interpreted as 75.0.]

32 of 53 11/27/2018, 5:45 PM
Skillsoft Course Transcript https://library.skillport.com/courseware/Content/cca/jl_jsee_a01_it_enus/...

Using Standard Mathematical Operators


Learning Objective
After completing this topic, you should be able to
describe how to use standard mathematical operators in Java

1. Standard mathematical operators in Java


In this video, I'll discuss using standard mathematical operators. Java uses the standard math
operators found in all computer languages. They're just like the real-world operators we use to
perform math, the only differences being that multiplication is done with the asterisk and division with
the forward slash. This table assumes that we're working with integers, and when you mix numerical
types, for example using double and int types in the same calculation, you'll get different results.
For instance, in the division example, we get 5 when we divide 31 by 6 because we're working with
integers and the remaining decimal portion will be discarded, but if we were working with a double
value of 31 or 6 we'd see the decimal result. And just a note about division, as you can see in the
comments section, you can't divide a number by zero, and doing so result in a divide-by-zero error. A
common requirement in programs is to add or subtract one from the value of a variable. You can do
this by using the add or subtract operator, age = age +1 or count = count -1.

[Heading: Standard Mathematical Operators. A table lists the four standard mathematical operators,
with examples. For addition, the operator is the plus sign. The example given is as follows: sum =
num1 + num2; If num1 is 10 and num2 is two, sum is 12. For subtraction, the operator is a minus sign.
The example given is diff = num1 - num2; If num1 is 10 and num2 is two, diff is eight. For
multiplication, the operator is the asterisk. The example given is prod = num1 * num2; If num1 is 10
and num2 is two, prod is 20. For division, the operator is the backslash. The example given is quot =
num1 / num2; If num1 is 31 and num2 is six, quot is five. For division, the table includes the comment
"Division by zero returns an error. The remainder portion is discarded." Heading: Increment and
Decrement Operators (++ and --). The long way includes age = age + 1; or count = count - 1; The
short way involves age++; or count--;.]

So in the first example, if age was equal to 5 before this line of code, after we performed age = age
+1, age will become 6. The short way is to use double operators, so age++ and count-- will have
the same results as the top two examples. Everyone has probably encountered the concept of
operator precedence usually during math class in grade school. Operator precedence simply states
that certain calculations are performed before others. And that's important because in this example,
the result could be 34 or 9 depending on how you calculated the equation. I can tell you if the answer
is 9, but how do we get there? How does Java decide which parts of the equation it should use first?
To make mathematical operations consistent, the Java programming language follows the standard
mathematical rules for operator precedence. Operators are processed in the following order: first
anything inside parentheses is performed;

[Heading: Operator Precedence. Consider the following problem: int c = 25 - 5 * 4 / 2 - 10 + 4; This


illustrates the need for rules of precedence, which determine whether the answer is 34 or 9. The rules
of precedence dictate that operators within a pair of parenthesis should be dealt with first. Then come
increment and decrement operators, followed by multiplication and division operators, evaluated from
left to right. Finally, addition and subtraction operators are evaluated from left to right.]

then increment and decrement operators, that's the ++ and -- we just discussed, get processed next;

33 of 53 11/27/2018, 5:45 PM
Skillsoft Course Transcript https://library.skillport.com/courseware/Content/cca/jl_jsee_a01_it_enus/...

then multiplication and division operators are evaluated, always from left to right; and then addition
and subtraction operators are evaluated, again from left to right. If standard mathematical operators of
the same precedence appear successively in a statement, the operators are always evaluated from
left to right. Your expression will be automatically evaluated with the rules of precedence, however, it's
a really good idea to use parentheses to provide the structure you intend, and often it's easy to create
an incorrect equation because parentheses were omitted. This example shows a succession of math
statements that result in -6, and the values encased in parentheses at the very top, when calculated
equal -10 as you can see in the second-to-last example. Java will always calculate the equation in the
same way, paying attention to parentheses first to get you the same result every time.

[Heading: Using Parentheses. Some examples in which parentheses are used to specify order of
preference are int c = ((25 - 5) * 4) / (2 - 10)) + 4; int c = ((20 * 4) / (2 - 10)) + 4; int c = (80 / (2 - 10)) +
4; int c = (80 / -8) + 4; int c = -10 + 4; int c = -6;]

34 of 53 11/27/2018, 5:45 PM
Skillsoft Course Transcript https://library.skillport.com/courseware/Content/cca/jl_jsee_a01_it_enus/...

Using and Manipulating Numbers


Learning Objective
After completing this topic, you should be able to
use and manipulate numbers in a Java program

1. Manipulating numbers in Java


In this video, I'll explain how to use and manipulate numbers. Okay, so we've got our shopping cart
application here, and if I go ahead and run it now we get some output there, "Mary Smith wants to
purchase shirt". Well, it's not really properly written, but the reason for that is we're going to modify it.
We want to actually have a meaningful quantity, number of shirts plus whatever the value is, and then
calculate that value depending on how many shirts that Mary wants to buy. So the first thing I'm going
to do is just add some lines here. I want to create some numerical variables, so I'll start by creating an
integer, and the integer is going to be quantity, that's the name of the variable that we're giving it,
and we were thinking that Mary wants to buy three shirts, so I'll make that equal to 3. And then we're
going to create some double variables: double price – so this will be the price of shirts –
equals, let's say, 29.99. And of course you have to pay the tax, so we're going to create a variable
called tax, and that'll be, let's say, 1.10. And then finally I'll create another double variable for
total, and we don't have to assign a value to that because we're going to calculate the total in a
minute.

[A project named ShoppingCart is open in the NetBeans IDE. The ShoppingCart.java tab contains the
following code: public class ShoppingCart { public static void main(String[] args) { String
custName = "Mary Smith"; String itemDesc = "shirt"; String message;
message = custName +" wants to purchase " + itemDesc;
System.out.println(message); } } The presenter selects Run -
Run Project (Shopping Cart). The output is as follows: Mary Smith wants to purchase shirt BUILD
SUCCESSFUL (total time: zero seconds) In the code, the presenter positions the cursor below the
line: String message; He then adds the following lines: int quantity = 3; double
price = 29.99; double tax = 1.10; double total;]

Now what I want to do here is I want to modify this message, because we want to be able to say this
is how many shirts Mary's going to buy, this is the price, and this is the tax. So, Mary wants to
purchase quantity…quantity, and then we want to actually use the value or the item
description. Now, this is important, we actually have to put some spaces in here because the spaces
won't be added for us, so we just put some spaces in there so it's friendlier to read. ItemDesc, I've
got that in there twice, so I'll get rid of that. So Mary wants to purchase number of shirts, and I'll
actually do this: " at " + price. Now if I go ahead and run that now…okay, so Mary Smith wants to
purchase three shirts at 29.99, great, that's what we're looking for. Now what we want to do is do our
calculation down here, so I'm going to use that variable that we created called total, remember it's
a double variable. So total = quantity, the number of shirts, times price.

[The presenter navigates to the line message = custName +" wants to purchase " + itemDesc; He
changes the line to message = custName +" wants to purchase " + quantity + " " + itemDesc + " at " +
price; The presenter runs the code. The output is Mary Smith wants to purchase three shirt at 29.99
BUILD SUCCESSFUL (total time: one second) Next the presenter positions the cursor below the line
System.out.println(message); He then starts typing the line total = quantity * price]

35 of 53 11/27/2018, 5:45 PM
Skillsoft Course Transcript https://library.skillport.com/courseware/Content/cca/jl_jsee_a01_it_enus/...

And remember we have tax here, so we've created a variable called tax and given it a value of 10%
or 1.10. So we multiply the quantity times price times tax to get the total value, and then I'm
going to use System.out.println(), print line again, and this time we're going to do this. So
we've used a string literal here, "Mary's total: ", so we're just going to add that to the text, and
then we're going to display the total value. And finally we'll put in our semicolon to end that line. And
I'll go ahead and run that now. Okay, so not too bad, we've got a lot of numbers there at the end, we
could truncate those using a number of different methods, but you get the point. So, effectively what
we're doing here is we're saying Mary wants to purchase, and we're using these fixed values, 3,
29.99, those are fixed values that we've set in the variables here using the double variable type.
And then we've created the total variable and calculated that using these various numbers that we
have here, these various variables, to get our total value, and that's how you use numbers and
manipulate them using Java.

[The presenter finishes the line, as follows: total = quantity * price * tax; The presenter then adds the
line System.out.println("Mary's total: " + total); The presenter runs the code. The output is Mary Smith
wants to purchase three shirt at 29.99 Mary's total: 98.9670000000001 BUILD SUCCESSFUL (total
time: zero seconds)]

36 of 53 11/27/2018, 5:45 PM
Skillsoft Course Transcript https://library.skillport.com/courseware/Content/cca/jl_jsee_a01_it_enus/...

Working with Conditions


Learning Objective
After completing this topic, you should be able to
describe how to work with conditions in Java programs

1. Using conditions in Java


Computers at their most basic level of processing, simply make decisions. Millions and billions of
decisions every second actually, but nonetheless, 1's and 0's translate into on or off, yes or no. A
basic foundation in computer programming requires the use of conditions too, and they're much easier
to implement in a high-level programming language like Java. So in this video, I'll introduce you to
conditions and explain how they're used in Java programs. As humans we're always making
decisions, and we often use the word "if" when making decisions. If I'm hungry I'll have something to
eat otherwise I won't eat. If I reach and intersection which way should I turn, left or right? Now "if" is a
mighty big word with big implications if you stop to think about it, we do it every day all the time, make
decisions using a little word like "if". Well, computers are no different, in fact all they do is make binary
calculations, yes or no, on or off, 1 or 0 decisions, and they do it very, very quickly. This logic is
conditional, meaning that the computer determines which way to turn based on some condition, left or
right, 1 or 0. One way executes one branch of code and the other way executes a different branch of
code, and this is called conditional logic. And in Java programming it's all done using if, or more
accurately, the if-else statement.

The if-else statement is an important method for making decisions, branching your code
depending on some condition that you establish. It uses two Java keywords, if and else. The
logic's pretty simple at face value, if a condition is true, execute the code within the if block. But then
we have the else statement, and it's used if we want to branch off in a different direction when the if
statement is false. Else if that condition is false execute the code in the code block, in the else block.
The condition to be evaluated is surrounded by parentheses, and it's a Boolean expression because it
must either be true or false. You should take note that the if block and else block are both
contained within braces, a left facing brace to open the container and a right facing brace to close the
container. And the else statement is purely optional, you'll only have to use it if you want to do
something different in case the if statement proves to be false. And you can use multiple else
statements each one testing a different condition.

[Heading: The if/else Statement. An example of an if/else statement is if ( <some condition is true> ) {
// do something } else { // do something different } In the example, the syntax <some condition is
true> is a Boolean expression. The if block is if ( <some condition is true>) { // do something } The
else block is else { // do something different }]

As I said, a Boolean data type can only have two possible values, true or false. In the same way,
a Boolean expression made up of some combination of variables, values, and operators must also
evaluate to either true or false. We accomplish this using a special kind of operator called a
relational operator. Relational operators help determine a relationship between two values. There are
many relational operators that you can use in Java, but a few of the most common ones are shown
here. There's greater than (>) which is usually Shift+Period on the keyboard, less than or equal to
(<=) which is the left-facing angled bracket, usually Shift+Comma on the keyboard followed by an
equal sign, and then the equals to (==) which is a double equal sign. We have to use the double

37 of 53 11/27/2018, 5:45 PM
Skillsoft Course Transcript https://library.skillport.com/courseware/Content/cca/jl_jsee_a01_it_enus/...

equals, because as you know, we use a single equal sign to assign value to something. X=10 means
make X equal 10 now please, but in relational operators we're testing something, we're not making a
statement, we're asking a question, is X equal to 10? So we have to use double equal signs. In the
example here, the result of cost times price is compared to the value of total. If they're both
same the entire expression results in a true, and the if statement block can then be processed.
This is a more complete list of relational operators; the table lists the different conditions that you can
test.

[Heading: Boolean expressions. The Boolean data type has only two possible values – true or false. A
Boolean expression is a combination of variables, values, and operators that evaluate to true or false.
Examples are: length > 10; size <= maxSize; total == (cost * price); In the examples >, <=, and == are
relational operators. Heading: Relational Operators. A table lists relational operators with the
conditions they specify and examples. The operator for the condition "is equal to" is ==. The example
given is int i=1; (1 = 1) The operator for the condition "is not equal to" is !=. The example given is int
i=2; (i != 1) The operator for the condition "is less than" is <. The example given is int i=0; (i < 1) The
operator for the condition "is less than or equal to" is <=. The example given is int i=1; (i <= 1) The
operator for the condition "is greater than" is >. The example given is int i=2; (i > 1) Last, the operator
for the condition "is greater than or equal to" is >=. The example given is int i=1; (i >= 1)]

Remember no matter what kind of test you use, the result will always been a Boolean result, these
examples all yield a Boolean result of true. And just a reminder that the equal sign is used to assign
value and the double equal sign makes comparison and returns a Boolean. So in the very first
example, the first line int i=1; means make i equal to 1. And in the second line the operation inside
the parentheses is asking the question, is i equal to 1? In Java there are usually many ways to
perform the same operation using different syntax, here's an example. This example shows two
different ways to set a Boolean value for the variable called largeVenue. In lines 28 through 33, an
if statement tests the value of the variable called attendees. If attendees is greater than or
equal to 5, largeVenue is set to true, otherwise its set to false. In line 36 the same outcome is
achieved with one line of code. In simple terms, the line is stating, make the value of largeVenue
equal to the result of the question, is attendees greater than or equal to 5? The answer of the
question of course is a yes or no, a Boolean value. Yes it's greater than or equal to 5 means
largeVenue becomes true, and no it's not greater than or equal to 5 means largeVenue
becomes false.

[Heading: Examples. Sometimes there is a quicker way to meet your objective. Boolean expressions
can be used in many ways. The following example is shown: int attendees = 4; boolean largeVenue; //
if statement example if (attendees >= 5) { largeVenue = true; } else { largeVenue = false; } // same
outcome with less code largeVenue = (attendees >= 5); In the example, the following section is
assigned a Boolean by using an if statement: if (attendees >= 5) { largeVenue = true; } else {
largeVenue = false; } A Boolean is assigned directly from the Boolean expression in the line
largeVenue = (attendees >= 5);]

38 of 53 11/27/2018, 5:45 PM
Skillsoft Course Transcript https://library.skillport.com/courseware/Content/cca/jl_jsee_a01_it_enus/...

Using if Statements
Learning Objective
After completing this topic, you should be able to
use if statements in a Java program

1. Java if statements
In this video, I'm going to demonstrate how to use if statements. So I've got a shopping cart
application, I'll go ahead and run it, and all it does is check to see how many shirts Mary wants, and
then display that, and then also to display the total cost with tax based on the number of shirts that
she wants to purchase. Now here's a thing, if Mary wanted to purchase one shirt, this would be great,
but because she wants to purchase more than one we want to be able to add that "s" to the word shirt
if she purchases more than one shirt. I also want to check and see whether that shirt is in or out of
stock, so we're going to use a couple of if statements here to accomplish that. Now I'll start by creating
a new variable called boolean, it's going to be a boolean type, stockStatus. I'm not going to
assign a value to it here, I'm going to do that below, but we want to set that boolean variable just to
see whether that shirt is in stock or not and then display an appropriate message. Now what I want to
do down here is I want to go ahead after I've calculated the total and use an if statement to check
the quantity. So if (quantity > 1), we want to see if it's greater than 1, because if it is we want to
add an "s".

[A project named ShoppingCart is open in the NetBeans IDE. The ShoppingCart.java tab contains the
following code: public static void main(String[] args) { String custName = "Mary smith";
String itemDesc = "shirt"; double price = 21.99; int quantity = 2;
double tax = 1.04; double total; String message = custName+"
wants to purchase "+quantity+" "+itemDesc; total = (price*quantity)*t a x;
System.out.println(message); System.out.println("Total
cost with tax: "+ total); } The presenter runs the code. The output is Mary Smith wants
to purchase two shirt Total cost with tax: 45.7392 BUILD SUCCESSFUL (total time: zero seconds)
The presenter positions the cursor below the line double total; He then adds the lines
boolean stockStatus; total = (price*quantity)*tax; if (quantity > 1) {]

So inside the braces, message = message + "s". So what we're going to do here is just add an "s"
to the end of the message which is in this case item description, so we'll show multiple shirts. Let's go
ahead and just run that and make sure it works. Okay, so there you go, it's properly shown now, now
just to make sure that works properly let's go ahead and change the value of quantity of shirts to 1
and run it again. Okay, so our if statement's working great, I'll change that back to 2. Now again
what we want to do here is test the stock status, so what I'll do here is I'll go ahead and set the
stockStatus = false; and then create another if statement; if (stockStatus).

[The presenter continues adding to the code. In full, the new code is as follows: boolean
stockStatus; total = (price*quantity)*tax; if (quantity > 1) { message =
message + "s"; } The presenter runs the code. The output changes from "Mary Smith wants
to purchase 2 shirt" to "Mary Smith wants to purchase 2 shirts." The presenter then changes the line
int quantity = 2; to int quantity = 1;. He runs the code and the output changes to "Mary Smith wants to
purchase 1 shirt." The presenter changes the line back to int quantity = 2;. Next the presenter places
the cursor below the lines if (quantity > 1) { message = message + "s";
} He adds the lines stockStatus = false; if (stockStatus)]

39 of 53 11/27/2018, 5:45 PM
Skillsoft Course Transcript https://library.skillport.com/courseware/Content/cca/jl_jsee_a01_it_enus/...

Now, there's a couple of different ways we can do this, I could actually use an equals…double equals
and check to see whether it's true or false, but if we just use if (stockStatus), that's going to
check and see whether or not it's a true value. So if a true value is returned here I'll go ahead and
put in my braces, if stockStatus equals true then .out.println("in stock"). And then
create an else statement here, put in our opening and closing braces,
System.out.println("out of stock").So again, this method if (stockStatus) is
going to check for a true and if it's true, it's going to tell us that it's in stock otherwise if it's not
true, it's obviously false which we know it is, and we'll get an out of stock message. So let's go
ahead and run that again.

[The presenter continues the code, as follows: if (stockStatus) {


System.out.println("in stock"); } else { System.out.println("out of
stock"); } The presenter runs the code.]

Okay, so there you go, we're out of stock. So I'll go ahead and change that to true. So we'll get an in
stock message the next time we run it. And finally what I want to do here…okay, jump back to just
after I finish demonstrating that result, or just after I finished changing that to true. Okay, so now that
that's true, let's go ahead and run it again and try this. Okay great, now we see that it's in stock, that
Mary wants to purchase two shirts with a total cost there. And that's how you use if statements in
Java, it's a really useful method of being able to test certain conditions. In this example to test whether
or not the item is in or out of stock, and whether or not Mary ordered multiple shirts, in which case we
modified that line so it's grammatically correct.

[The output is as follows: out of stock Mary Smith wants to purchase two shirts Total cost with tax:
45.7392 BUILD SUCCESSFUL (total time: zero seconds) In the code, the presenter changes the line
stockStatus = false; to stockStatus = true; He then runs the code. In the output, "out of stock" has
changed to "in stock."]

40 of 53 11/27/2018, 5:45 PM
Skillsoft Course Transcript https://library.skillport.com/courseware/Content/cca/jl_jsee_a01_it_enus/...

Working with an Array of Items


Learning Objective
After completing this topic, you should be able to
describe how to work with arrays in Java

1. Arrays in Java
In this video, I'll discuss working with an array of items. Think about a shopping cart, typically when
you go to the grocery store and grab a cart, you're not grabbing it because you plan on buying one
item or a bunch of one type of item, you want some food items, some household items, some milk,
some soda pop, and when you're waiting at checkout you want to add some gum and your favorite
magazine. The same analogy is true with computerized shopping carts. How would your code look if
there were multiple items in the shopping cart? We could set things up as in lines one to four, have a
separate description for each item. That may work fine if you have a small number of items, but what if
you're getting lots and lots of different items? It's not practical and it's not efficient to declare each item
as a separate variable, it makes your code very long, very unwieldy, and very difficult to understand,
but there's a better way and we call them arrays. Think of an array as a container that holds a set of
values, whether strings or numbers of the same type. Each item in an array is referred to as an
element and each element is accessed using a numeric index. We use this index to set or get a value
from a specific element.

[Heading: What if There Are Multiple Items in the Shopping Cart? Using code without an array is not
realistic if there are hundreds of items. An example is // Without an array String itemDesc1 = "Shirt";
String itemDesc2 = "Trousers"; String itemDesc3 = "Scarf"; It would be much better to use code with
an array, as in the following example: // Using an array String[] items = {"Shirt","Trousers","Scarf"};
Heading: Introduction to Arrays. An array is an indexed container that holds a set of values of a single
type. Each item in an array is called an element. Each element is accessed by its numerical index.
The index of the first element is zero. A four-element array has the indices 0, 1, 2, and 3. For
example, an array might contain the numbers 27, 12, 82, and 70, from left to right. Index 0 identifies
the number 27, index 1 identifies the number 12, index 2 identifies the number 82, and index 3
identifies the number 70.]

The index value always beings with 0, not 1, so in a four-element array the index values will be 0, 1, 2,
and 3. An array is a container object that holds a fixed number of values of a single type. They are
always the same type; you can't mix types in an array. So an int array can contain only integer
numbers, and a String array can only contain strings. The length of an array is established when
the array is created. After creation, the length of the array can't be changed. As shown in this
example, index numbering begins with 0, for example the eighth element is accessed at index 7. The
length of an array is using dot notation to access the length field. Assuming that the array in diagram
is called ages, you can determine how many elements are in the array by using the notation
ages.length, and it would return a value of 8 because that's the length of the array.

[Heading: Array Examples. An example of an array of int types contains the integers 27, 12, 82, 70,
54, 1, 30, and 34. An example of an array of String types contains a set of names. Heading: Array
Indices and Length. As an example, the ages array has eight elements – in order from left to right, the
integers 27, 12, 82, 70, 54, 1, 30, and 34. So the array length, or ages.length, is 8. The first index is 0.
The element at this index is the number 27. The element at index 5, for example, is the number 1.]

41 of 53 11/27/2018, 5:45 PM
Skillsoft Course Transcript https://library.skillport.com/courseware/Content/cca/jl_jsee_a01_it_enus/...

Here's the syntax for declaring an array and initializing its values, assuming that you know when you
create the array what the values will be. Just as with variables, you don't have to assign values to an
array when you create it. Syntax is the type of data that will be used following by opening/closing
brackets. These inform the compiler that you're declaring an array. Then there's the
arrayIdentifier which is the variable name that you'll use for your array, and if you know the
values you'll be assigning you can do that using the equal sign followed by a comma separated list of
values enclosed in braces. Note that the square brackets can be placed after the array identifier
instead of the type, but whatever method you choose, you should always be consistent with your
syntax. In this example, the array of type int is called ages, and it's been instantiated with a size of
3, so three index values between 0 and 2. The creation of the array uses the new keyword. On lines
two through four, the elements of the ages array are initialized,

[Heading: Declaring and Initializing an Array. The syntax for declaring and initializing an array is as
follows: type[] arrayIdentifier = {comma-separated list of values}; Examples that declare arrays of
types String and int are String[] names = {"Mary", "Bob", "Carlos"}; int[] ages = {25, 27, 48}; In each
case, the declaration is on one line. An example of a multistep approach for declaring an array of type
int is int[] ages = new int[3]; ages[0] = 19; ages[1] = 42; ages[2] = 92; An example of a multistep
approach for an array of type String is String[] names = new String[3]; names[0] =
"Mary","Bob","Carlos"; names[1] = "Mary","Bob","Carlos"; names[2] = "Mary","Bob","Carlos";]

and on line six the String array called names is instantiated with the size of 3 and its elements are
initialized on lines seven through nine. Elements of an array are accessed by referencing the index of
that element. For example to get the value from the first element of the array called ages you use
ages [0] inside brackets. To get the value from the second element of the ages array you use
ages [1] inside brackets. You can also use the value of an array element directly in an expression
by using the same syntax. In the third example, ages [0] is being referenced directly from the
System.out.println() command. The second examples show a string array and how to set
the values. The first line instantiates the array with three strings, "Mary", "Bob", and "Carlos", but
the following two lines will change "Mary" to "Gary" and "Bob" to "Rob" by using the equal sign. So
it works the same way as with String variables, you can change array elements at any time using
this method.

[Heading: Accessing Array Elements. An example of code that gets values from the ages array is int[]
ages = {25, 27, 48}; int myAge = ages[0]; int yourAge = ages[1]; System.out.println("My age is " +
ages[0]); An example that sets values in the names array is String[] names = {"Mary", "Bob", "Carlos"};
names[0] = "Gary"; names[1] = "Rob";]

42 of 53 11/27/2018, 5:45 PM
Skillsoft Course Transcript https://library.skillport.com/courseware/Content/cca/jl_jsee_a01_it_enus/...

Using an Array
Learning Objective
After completing this topic, you should be able to
declare, initialize, and use an array in a Java program

1. Using arrays in Java


In this video, I'll demonstrate how to use an array. Okay, so I've got the beginnings of a shopping cart
application here, and it's pretty simple right now, we've just got two strings, customer name, Mary
Smith, and then a message that has Mary's name plus a string literal saying she wants to purchase
several items, and then System.out.println() will just print that message out to the console. If
we go ahead and run it now…there we go, that's what we get. Now what I want to do here is I want to
set up an array, because Mary wants to purchase several items, and we could go ahead and create a
bunch of different variables, String variables, each with a different item in it, but that's not very
efficient. So we want to create an array variable, so we do this: String, so we always put the type in
first in which case it's a String with a capital "S", and then opening and closing brackets, and then
the name of the array in this case items. And then inside braces we put our items, inside quotation
marks each separated by a comma, so {"Shirt", "Boots", "Scarf", "Sweater", and
"Gloves", then we put our closing brace in, and then a semicolon.

[A Java project named ShoppingCart is open in the NetBeans IDE. The ShoppingCart.java tab
contains the following code: package shoppingcart; public class ShoppingCart { public static void
main(String[] args) { String custName = "Mary Smith"; String message = custName
+ " wants to purchase several items."; System.out.println(message); }
} The presenter runs the code. The output is run: Mary Smith wants to purchase several items
BUILD SUCCESSFUL (total time: 0 seconds) Next the presenter positions the cursor above the line
System.out.println(message); He then adds the line String[] items =
{"Shirt","Boots","Scarf","Sweater","Gloves"};]

Now this a five-item array, it's got five items, and arrays start their index value with zero, so this will be
zero, and one, two, three, and four, so we've got our five items there as an array. Now what I want to
do here is change this message to show what Mary is purchasing or how many items. So I'm going to
go down here, message = custName + " wants to purchase " – note the spaces in between
because we need those to make it sort of read correctly. Now we've created an array variable called
items. So I'm going to use items and then .length, and .length will tell us the length of the
array which we already know is five items long. And then we'll put in some string or a string literal at
the end just to make everything look nice and neat. Put my semicolon in, go ahead and run that,

[The presenter continues the code, adding the line message = custName + " wants to purchase " +
items.length + " items."; He then runs the code.]

and there we go, "Mary Smith wants to purchase 5 items". So we've actually grabbed the length of
that array, which again we know has five items in it, to display that. Now, we can take this even further.
If we want to actually…if we want to actually show the things that Mary has purchased, or plans on
purchasing, we can do more with it, we can actually do this: I'll add another
System.out.println(), and inside parentheses, inside quotation marks, this is my string literal,
use that plus symbol again, and what we're going to do is grab one of the items, in this case…so
remember it's items is the name of the array, and inside brackets we can put whatever value we

43 of 53 11/27/2018, 5:45 PM
Skillsoft Course Transcript https://library.skillport.com/courseware/Content/cca/jl_jsee_a01_it_enus/...

want to grab from. Let's just go back and take a look here.

[The output is as follows: Mary Smith wants to purchase five items BUILD SUCCESSFUL (total time:
one second) Next the presenter positions the cursor below the line System.out.println(message); He
adds the line System.out.println("Mary definitely wants a " + items[]);]

Remember the index value of Shirt is zero, so zero, one…let's say sweater, she wants to buy a
sweater, so that would actually be three; zero, one, two, three. So inside the brackets put 3. Let's go
ahead and run this, and there you go, Mary definitely wants a sweater. So arrays are extremely
powerful, they're a wonderful way of creating different groupings of items, in this case we've used
strings to set up our little shopping cart application here, and pull that information, not just the actual
item in this case using the index value of 3, but the actual ability to tell how many items. And that's
very important when you start to get into Java programming, understanding how to be able to create
those arrays and reference them, and that'll open up a whole new powerful toolkit for you when you're
programming in Java.

[The presenter changes the new line he added to System.out.println("Mary definitely wants a " +
items[3]); He then runs the code. The output is Mary Smith wants to purchase five items Mary
definitely wants a Sweater BUILD SUCCESSFUL (total time: zero seconds)]

44 of 53 11/27/2018, 5:45 PM
Skillsoft Course Transcript https://library.skillport.com/courseware/Content/cca/jl_jsee_a01_it_enus/...

Loops and Array Items


Learning Objective
After completing this topic, you should be able to
describe how to use loops to process array items and describe how to use the break
statement in Java

1. Using loops in Java


In this video, I'll discuss loops and array items. Loops are an important part of programming, and like
if-else statements you'll be turning to them pretty quickly and often when you're creating programs
in Java. Repetition is an important part of programming just as in life. For example, think of emptying
your clothes dryer, it's unlikely that you'll have just one piece of clothing in the dryer, you'll have many
items. So you grab one item, fold it, put it in its proper place, go back, grab another item, fold it, put it
in it's proper place, and you keep repeating that process until the dryer is empty and all your clothes
are folded and put away. In programming, loops are used to repeat blocks of statements, things you
have to do, like remove items from a dryer, and loops need to keep looping until an expression is
found to be false. For example, if there are no more clothes in the dryer then there's no more need to
look in there and our loop is complete. That's one type of testing condition using true or false, but we
can also establish loops that run a certain number of times. For example, if I have an array with 100
elements and I want to print each element of that array, which means I have to loop 100 times.

[Heading: Loops. Loops are used in programs to repeat blocks of statements until an expression is
false or for a specific number of times – for example, if you want to print each element of an array or
each element of an ArrayList.]

The same is true for an ArrayList, which is like an array but unlike arrays, ArrayLists are dynamic
and can change in size. Here we've got a four-element array called names that contains four different
string values. The syntax for a for loop is to use the word for and follow it by whatever the looping
conditions are enclosed in parentheses, and we're creating a new string inside the parentheses, one
called name. The colon between name and names means assign the value of names, our starting
array, to name, a variable that we're using for the loop. So here we're saying for zero to three because
those are the index values for our string; zero to three, loop four times. The code block, the
commands within the opening and closing braces, will execute four times. And in this example there's
only one command: display the words "Name is", and then the actual name, which in each iteration of
the loop is being taken from the array called names and then assigned to the variable we created for
the loop, the variable called name.

[Heading: Processing a String Array. As an example, the names array contains the String values
George, Jill, Xinyi, and Ravi. The following code is shown: for (String name : names ) {
System.out.println("Name is " + name); } Each iteration of the code returns the next element of the
array. The output is as follows: Name is George Name is Jill Name is Xinyi Name is Ravi]

You can see the output at the bottom of the screen. It's not uncommon that you'll set up a loop to run
a set number of times, say 100 times, and then encounter a condition that makes it unnecessary to
continue with the loop. You've only hit 55 and something happens where you don't need to continue to
100. You can stop loops, break out of them, using the break keyword. When break is encountered,
program execution will move to the first line of code outside and after the for block. This example
uses an if statement within the for block. The if statement is executed on each iteration of the

45 of 53 11/27/2018, 5:45 PM
Skillsoft Course Transcript https://library.skillport.com/courseware/Content/cca/jl_jsee_a01_it_enus/...

loop, so if the purpose of the code is to find out whether any of the scores in the array are equal to or
above the passing mark, we set the variable called passed to true and jump out of the loop as
soon as the first such score is found. When a score of 12 or more is reached, passed becomes true
on line 6, the break is called on line 7, the loop ends, and execution of the program skips to line 10
and continues.

[Heading: Using break with Loops. The following example is shown: int passmark = 12; boolean
passed = false; int[] scores = {4,6,2,8,12,35,9}; for (int unitScore : scores) { if (unitScore >= 12) {
passed = true; break; } } System.out.println("At least one passed? " +passed); Because
there's no need to go through the loop again if passed=true, break is used after this line to exit the
loop and print the output. The output from the example code is At least one passed? true]

46 of 53 11/27/2018, 5:45 PM
Skillsoft Course Transcript https://library.skillport.com/courseware/Content/cca/jl_jsee_a01_it_enus/...

Using a Loop to Process an Array


Learning Objective
After completing this topic, you should be able to
use a loop to process an array in Java

1. Processing an array using a loop


In this video, I'll demonstrate how to use a loop to process an array. So I've got the beginnings of a
shopping cart application here, and I've created a customer, her name is Mary Smith, using a
String variable. And then I've created an array right here that's got four items in it, and I've actually
displayed a message here that shows Mary's choices or the number of items that she wants to buy
using items.length. Remember items is the name of that array, and if you use .length after that
should display the number of items which we have and those are four. So let's go ahead and try that
out. Okay, so there we go, "Mary wants to purchase 4 items", its working great. Now what I want to do
here is cycle through this array and actually show all the items. Now how do you do that? Well, it's
really easy, let's start by doing this: I'm going to add a line here and add another
System.out.println(), print line, message, and this time use a string literal, "Items
purchased: ", and that's just a header. And add another line,

[A Java project named ShoppingCart is open in the NetBeans IDE. The ShoppingCart.java tab
contains the following code: package shoppingcart; public class ShoppingCart { public static void
main(String[] args) { String custName = "Mary Smith"; String message; String[]
items = {"Shirt","Socks","Scarf","Belt"}; message = custName + " wants to purchase " +
items.length + " items."; System.out.println(message); } } The presenter runs the code. The
output is Mary Smith wants to purchase four items BUILD SUCCESSFUL (total time: one second) The
presenter places the cursor below the line System.out.println(message); He then adds the line
System.out.println("items purchased: ");]

and what I'm going to do here is use a for loop, so for, and then in parentheses we're going to do
this, String item, so we're creating a brand new variable called item. Remember our array is
called items with an "s", we're going to use item with no "s" because that'll be the variable we're
going to use to display each item. And then you put a colon – I'll put a space after that – a colon like
that, and then the colon is going to indicate that we're pulling information from something, in this case
items, remember with that "s", so that's the array. What that'll do is that will actually loop through
zero, one, two, and three, the four different items that are in the array. I'll put in an opening brace, and
there's our closing brace. Get rid of that extra line. And now what I'm going to do is, again output here,
System.out.println(), and item – remember we created item right here which is a String
– in each iteration of the loop it's going to go through it four times because that's the length of the
array. It's going to pull the value from the items array, so it'll be "Shirt", "Socks", "Scarf", and
"Belt" in each iteration;

[The presenter continues the code, adding the lines for (String item : items) {
System.out.println(item);]

item, and let's put a little extra text in here because we want to separate this, make it look clean; put
a comma and a space. Now let's go ahead and run that and see how it works. Okay, so there you go,
"Mary Smith wants to purchase 4 items", and each item purchased being shown here, Shirt, Socks,
Scarf, and Belt. Now if you wanted to reformat this a bit, and this is certainly something that's optional,

47 of 53 11/27/2018, 5:45 PM
Skillsoft Course Transcript https://library.skillport.com/courseware/Content/cca/jl_jsee_a01_it_enus/...

you can go ahead and get rid of that ln. So println is going to print a new line, and if we use
print it should print everything on the same line. Let's go ahead and try that and make sure it looks
the way we want it to. Okay, there you go. Now we should probably do something there with an if
statement to make sure that the very last item doesn't have a comma, instead it should probably have
something like a period just to show that it's the end of the list, but effectively that's how you use for
loops to go through a list of items, an array in this case, and actually print out each item very quickly
and easily using a couple of lines in Java.

[The presenter changes the line System.out.println(item); to System.out.println(item + ", "); The
presenter then runs the code. The output is as follows: Mary Smith wants to purchase four items.
Items purchased: Shirt, Socks, Scarf, Belt, BUILD SUCCESSFUL (total time: zero seconds) Next the
presenter changes the line System.out.println(item + ", "); to System.out.print(item + ", "); The
presenter runs the code. The output is Mary Smith wants to purchase four items. Items purchased:
Shirt, Socks, Scarf, Belt, BUILD SUCCESSFUL (total time: zero seconds)]

48 of 53 11/27/2018, 5:45 PM
Skillsoft Course Transcript https://library.skillport.com/courseware/Content/cca/jl_jsee_a01_it_enus/...

Exercise: Fundamentals of Java


Learning Objective
After completing this topic, you should be able to
practice basic tasks such as running a program, creating a main class, and
processing arrays

1. Exercise overview
We've covered a lot of ground up to this point, so here's a chance for you to turn theory into practice.

In this exercise, you'll examine fundamental concepts in Java.

This involves the following tasks:

recognizing characteristics of a computer program


differentiating between different versions of Java
identifying variable types
understanding conditional operators, and
determining mathematical operator precedence

2. Fundamentals of Java

Question

Which statement associated with computer programs is true?

Options:

1. Compilers translate high-level code into machine code


2. High-level code is binary code
3. High-level code is machine code
4. Program instructions run on analog devices

Answer

Option 1: Correct. The purpose of a compiler is to translate high-level, human readable


code into machine binary code so that a computer can interpret the instructions it must
process.

Option 2: Incorrect. High-level code is human readable code, whereas binary code is
machine readable code.

Option 3: Incorrect. Machine code consists of ones and zeros, and is called binary code. It's
the language that computers can understand. High-level code is written in human readable

49 of 53 11/27/2018, 5:45 PM
Skillsoft Course Transcript https://library.skillport.com/courseware/Content/cca/jl_jsee_a01_it_enus/...

language and it is what programmers use when writing computer programs.

Option 4: Incorrect. Computer programs are sets of instructions that run on digital devices.
They may be simple programs such as word processors and calculators, or more complex
programs such as operating systems, which control the overall functioning of computers.

Correct answer(s):

1. Compilers translate high-level code into machine code

Question

What is a function of Java EE?

Options:

1. Creates apps on resource-limited devices


2. Develops applets for web browsers
3. Creates client-side distributed apps
4. Develops applications for desktop PCs

Answer

Option 1: Incorrect. Java ME is used to develop applications for resources-constrained


consumer devices such as tablets and smartphones.

Option 2: Incorrect. The Java SE is used to develop applets that run within web browsers
and applications that run on desktop computers.

Option 3: Correct. Java EE is used to create large enterprise, server-side, and client-side
distributed applications.

Option 4: Incorrect. Java SE is used to develop applications that operate within web
browsers and on computer desktops.

Correct answer(s):

3. Creates client-side distributed apps

Question

Which variable type can hold whole numbers that can be mathematically manipulated?

50 of 53 11/27/2018, 5:45 PM
Skillsoft Course Transcript https://library.skillport.com/courseware/Content/cca/jl_jsee_a01_it_enus/...

Options:

1. Boolean
2. String
3. Double
4. Int

Answer

Option 1: Incorrect. Boolean variables can take only one of two values – either true or false.

Option 2: Incorrect. String is used to define alphanumeric variables that can contain letters,
special characters, or even numbers. Numbers in strings are not treated as numbers so
mathematical operations can't be performed on them.

Option 3: Incorrect. Double variables are numeric variables that can take decimal values.
The values can be positive or negative, and can be manipulated mathematically.

Option 4: Correct. Int refers to numeric variables that are whole numbers, or integers. They
can be positive or negative, and can be mathematically manipulated.

Correct answer(s):

4. Int

Question

Which relational operator is used to describe a relationship as true or false when checking
for an "is not equal to" condition?

Options:

1. !=
2. ==
3. >=
4. <

Answer

Option 1: Correct. This conditional operator represents the "is not equal to" condition. It can
test whether a variable value is not equal to a set value or to the value of another variable.

Option 2: Incorrect. This conditional operator tests whether the value of a variable is equal
to a set value or to the value of another variable.

51 of 53 11/27/2018, 5:45 PM
Skillsoft Course Transcript https://library.skillport.com/courseware/Content/cca/jl_jsee_a01_it_enus/...

Option 3: Incorrect. This operator checks whether the value of a variable is equal to or
greater than a set value or the value of another variable.

Option 4: Incorrect. This operator checks whether the value of a variable is smaller than a
set value or the value of another operator.

Correct answer(s):

1. !=

Question

Which mathematical operation produces a result of 21, given the rules of precedence used
in Java?

Options:

1. 100/5 + (1 * 2)
2. (10 - 3) * 3 - 1
3. 3 * 6 + (5 - 2)
4. 7 * 2 + 1

Answer

Option 1: Incorrect. The operation 1 multiplied by 2 will be performed first because it's in
parentheses. The result is 2. Then 100 is divided by 5, to give 20. These two results are
added, giving the result 22.

Option 2: Incorrect. 10 minus 3 takes precedence because it is in parentheses, so this


operation is performed first. The result, 7, is then multiplied by 3, giving 21. Finally, 1 is
subtracted, giving a result of 20.

Option 3: Correct. Operators within parentheses always take precedence, so the first
operation performed is 5 minus 2, which equals 3. Next 3 is multiplied by 6 to give 18.
Finally, the two results – 18 and 3 – are adding, giving the result of 21.

Option 4: Incorrect. Multiplication takes precedence over addition, so the operation 7


multiplied by 2 will be performed first. Adding 1 to 14 then gives the result 15.

Correct answer(s):

3. 3 * 6 + (5 - 2)

52 of 53 11/27/2018, 5:45 PM
Skillsoft Course Transcript https://library.skillport.com/courseware/Content/cca/jl_jsee_a01_it_enus/...

© 2018 Skillsoft Ireland Limited

53 of 53 11/27/2018, 5:45 PM

Potrebbero piacerti anche