Documente Academic
Documente Profesional
Documente Cultură
How To Java
Student Materials
&
Lab Exercises
Professional Java How To Java
Welcome!
Randall Nagy
rnagy@Soft9000.com
Contents
Step-By-Step Lab Guide ............................................................................................. 8
Solution Files ......................................................................................................... 8
Activity 01: Java Main ............................................................................................... 10
Objective ............................................................................................................. 10
Overview ............................................................................................................. 10
Step by Step Guide ................................................................................................ 10
Step 01: Java Compiler ....................................................................................... 10
Step 02: JavaMain .............................................................................................. 11
Step 03: Program Verification .............................................................................. 12
Exercise 01: Reading Integral Input ............................................................................. 13
Objective ............................................................................................................. 13
Overview ............................................................................................................. 13
Step by Step Guide ................................................................................................ 13
Step 01: Project Tooling ..................................................................................... 13
Step 02: Project, Package, & Class Creation (Eclipse) ............................................. 14
Step 03: Testing the JDK (all versions) ................................................................. 15
Step 04: Running JavaOne (Eclipse) ...................................................................... 16
Step 05: Reading Console Input (all versions) ......................................................... 17
Step 07: Program Verification .............................................................................. 19
Exercise 02: Classic Console Loop .............................................................................. 20
Objective ............................................................................................................. 20
Overview ............................................................................................................. 20
Step by Step Guide ................................................................................................ 20
Step 01: Our New Package .................................................................................. 20
Step 02: Creating a Forever Loop ..................................................................... 21
Step 03: Program Re-factoring ............................................................................. 22
Step 04: Import Saves Typing .............................................................................. 23
Step 05: Program Verification .............................................................................. 24
Exercise 03: Using Arrays.......................................................................................... 26
Objective ............................................................................................................. 26
Overview ............................................................................................................. 26
Step by Step Guide ................................................................................................ 26
Step 01: Exporting Projects (Eclipse & derivations) ................................................. 26
Step 03: Renaming & Deleting Projects (Eclipse & derivations) ................................. 28
Step 04: Creating & Displaying Arrays .................................................................. 29
Step 05: Processing MainMenu Responses ............................................................. 32
This guide has been designed so as to allow students to reason their way through a real-world
problem statement. While experienced students seldom need to look at the final solution,
even experts can be glad to have a completed solution when trouble arises.
Solution Files
If you run into trouble completing a lab, the first thing to do is to locate and extract the
solution from the main solution archive. Named LabSolutions.zip once the solution files are
extracted you will discover that there are two types of archives: One designed for use with
Eclipse, and one designed for use with Netbeans. If you are not using either Eclipse or
Netbeans, there is no need to worry. Students can still open and use the source code in any
archive with any other Java development environment.
While the source code can be copied from any archive into any Integrated Development
Environment (IDE), those who are using either Netbeans or Eclipse will also find detailed
instructions on how to identify & import the appropriate solution either tool set herein.
The instructions documenting how to import the solutions to the lab exercises are located in
the appendices at the end of this document.
The complete set of source code has also been included in the appendix of this document.
Overview
You will be performing the following tasks:
Creating a Java Console Application
Compiling, testing, and & running Java Programs
Using System.out to display messages
You do not need anything fancy to write Java. All that is required is a version of the Java
compiler!
There is nothing special about Java programming files! To prove it, we will create a Java
program using a simple text-editing tool.
}
}
2. The above code can also be found in the solutions folder in the archive file
mentioned at the start of this Exercise.
(end of activity)
Overview
You will be performing the following tasks:
Creating a Java Console Application
Compiling, testing, and & running Java Programs
Using a provided class to read console input
Using System.out to display messages
Professional Java Software Developers have a wide range of tools to select from. From
simple editors like Notepad on Microsoft Windows or gedit on Linux, to full-blown IDEs
such as Eclipse, NetBeans, and JDeveloper, Java can be written in many different
ways.
This training was created using the most recent version of Eclipse.
At a minimum this training assumes that the student has installed a Java Developers
Kit (JDK.) Java Version 1.7 (commonly referred to as Java 7) is the minimum research
& JDK requirement.
NOTE: When installing Java, be sure to match the version of the JDK to the proper
release of your operating system. DO NOT ATTEMPT TO USE 64 BIT JAVA ON A 32
BIT SYSTEM, OR A 32 BIT VERSION OF JAVA ON A 64 BIT SYSTEM!
If you have problems running any exercise described in these labs, be sure to verify that
your Operating System Bit-Addressing Model matches your JDK. (i.e. Be sure to use a
32 bit JDK on a 32 bit OS, 64 to 64, 128:128 (etc.))
At the time of this writing, the Eclipse IDE is the most widely-used Integrated
Development Environment. The instructions for all subsequent labs assume the use of
Eclipse.
When using almost Eclipse (as well as almost any IDE), the mantra most students chant
when setting up a new Java Application is Project, Package, Class.
12. From the main menu, select "File | New | Java Project."
14. Press Finish. Your project is now ready for a Java Package.
17. Accept the default source folder, and provide the name com.soft9000 for the
new package name.
21. Place the class into the com.soft9000 folder by providing the package name
com.soft9000 in the class creation dialog.
23. Most versions of Eclipse also allow us to have a main member function created
automatically. If you version supports that feature, then select it:
Once a basic Project, Package, & Class have been created, writing Java is universally
the same. While the viewer shown by each Java editor might look a little different, the
Java source code (programs) can be exchanged.
Editing JavaOne.java:
1. Most IDEs will have a package view along the left-hand side. By clicking on the
icons, both projects & packages can be explored.
3. After any automatically-created comments, the code for you basic Java program
will look like:
package com.soft9000;
}
}
4. If you are missing a main() method as depicted above, then edit the default file
so at to manually provide one.
5. In order to ensure that the JDK has been properly installed, add the following
statement:
package com.soft9000;
Once errors have been eliminated from a program, the next task is to run it!
Running JavaOne:
1. Most IDEs will have a quick way to right-click & run a program.
2. On Eclipse, the best way to run any program with a main() method is to right-click
on the program view (JavaOne) to select Run as Java Application.
3. After the program has run successfully, the message Greetings Humanoid will
appear in the IDEs Console or Output Tab.
4. Either of those Views will be located along the bottom of the page.
5. If you do not see the message, then check your program for errors. If you are
able to locate but unable to correct any errors, please search for an answer to
you problem on the Internet. Use key phrases from the error message to help
pinpoint a solution to the problem.
Once we have verified that the JDK has been installed properly, we can begin our next
development task.
3. The first tack is to create a way to read the keyboard. To create a member
function that can read the keyboard, insert the following 2 statement directly after
the package statement at the top of JavaOne:
import java.io.IOException;
import java.io.InputStream;
5. Do not be concerned if you do not understand what is taking place in the above
code. We will cover keywords such as try and catch in other lessons.
package com.soft9000;
import java.io.IOException;
import java.io.InputStream;
7. Most IDEs will have a quick way to right-click & run a program.
The member function readInt() has been assigned the task of reading any keyboard
data. While it is not apparent at the moment, readInt() has been designed to work with
System.in, as well as any similar type of InputStream.
Do the following:
package com.soft9000;
import java.io.IOException;
import java.io.InputStream;
2. The above code can also be found in the solutions folder in the archive file
mentioned at the start of this Exercise.
(end of lab)
Overview
You will be performing the following tasks:
Learn how to cut & paste code between Projects
Updating the results from the previous exercise
Creating a never ending key-processing loop
Re-ractoring JavaOne into two different packages & classes
Utilizing the classic import paradigm
Migrating between fully qualified & imported names
We will be using a new package to continue the work from the previous exercise.
26. From the main menu, select "File | New | Java Project"
28. Press Finish. Your project is now ready for a Java Package.
31. Accept the default source folder, and provide the name com.soft9000 for the
new package name.
35. Place the class into the com.soft9000 folder by providing the package name
com.soft9000 in the class creation dialog.
Do the following:
13. Open the previous solution for JavaOne in the Exercise01 Project.
14. Right-click to choose Select All, then Copy (ctrrl+c) to place the content on the
clipboard.
16. Right-click to choose Select All, then Paste (ctrrl+v) to replace the default
program with the content on the clipboard.
option = readInt(System.in);
}
System.out.println("SPECIAL KEY DETECTED!");
}
18. Correct any errors. Be sure each statement ends with a semicolon!
20. Notice that while a single key is pressed, that the special character is what is
received when the enter key is pressed.
21. Notice also that unlike the previous lab the while loop allows us to see that
System.in keeps track of all input typed.
Do the following:
23. Create a new class in the helpers package. Name the class Reader.
24. Open JavaOne. Cut and paste the entire readInt() member into the Reader class,
as well as the two required import statements.
package com.soft9000.helpers;
import java.io.IOException;
import java.io.InputStream;
}
}
}
package com.soft9000;
29. Open the previous solution for JavaOne in the Exercise01 Project.
30. Right-click to choose Select All, then Copy (ctrrl+c) to place the content on the
clipboard.
There are times when fully-qualifying package names are absolutely required (for
example, then using Javas Date class.)
In as much as we have no other Reader class visible, rather than fully-qualifying the
Reader Class, we should update JavaOne to import Reader, instead.
While updating our class to avoid a single class-qualifier is of questionable value, the
more we use classes and functions from other packages, the more important it can be
to use import.
Do the following:
31. Add the following import statement directly underneath the package statement:
import com.soft9000.helpers.Reader;
32. Remove the prefix from the subsequent Reader statements so only the name of
the class (Reader) as well as the member name (readInt()) are present.
package com.soft9000;
import com.soft9000.helpers.Reader;
34. The more we use the resources from other packages, the more typing the import
statement will save!
package com.soft9000.helpers;
import java.io.IOException;
import java.io.InputStream;
package com.soft9000;
import com.soft9000.helpers.Reader;
3. The above code can also be found in the solutions folder in the archive file
mentioned at the start of this Exercise.
(end of lab)
Overview
You will be performing the following tasks:
Learn how to export & import projects from Eclipse
Learn how to rename & delete Eclipse Projects
Add a top-level menu to the previously-completed Exercise
Use arrays to manage application options
Migrate from Javas classic, to Javas static imports
Use a classic for loop to display enumerated user options
Rather than creating a new project, we will rename the previous exercise. Those who
do not wish to save the result of the last exercise can continue to Step 02.
Eclipse users will use the export feature. Other IDE users can use the copy & past
methods described in the previous exercise, then skip directly to Step 04.
39. If you would prefer to use the solution to the previous exercise rather than your
previous solution, skip to Step 02.
42. Check the name of the Project to include in the archive (i.e. Exercise02.)
43. Browse or otherwise specify the name of the archive file to export.
Eclipse users will use the import feature to import a previously exported Eclipse Project.
3. After entering the new workspace name, wait for Eclipse to restart.
4. Depending upon the speed of your machine, a restart can take up to 60 seconds.
7. Click Next.
Exercise.)
10. Select the name of the project to import (in this case, select Exercise02)
The importation & exportation process just described restores any previous Eclipse
Project. In as much as we want to re-use that Project in this exercise, all we need do is
to rename the result of the imported exercise to Exercise03:
To rename a project:
4. Press Okay
3. Press the delete key (most version also support Edit | Delete from the main
Eclipse menu.)
Non-Eclipse users should have created & imported either (1) their own results from the
previous exercise, or (2) the starter file (as listed at the beginning of this exercise) into a
Project named Exercise03.
We will begin by adding a MainMenu class to JavaOne. The MainMenu class will have
an Array. The array will be used to display & manage menu-items.
2. Update MainMenu.java:
package com.soft9000;
a. Unlike arrays in other programming languages, Java Arrays also have the
ability to tell us just how many addresses (items) are being represented.
c. The name of the array is menu. The array manages a set of addresses
that point to a set of strings.
import java.io.InputStream;
import java.io.PrintStream;
import com.soft9000.helpers.Reader;
Displaying a list of string is easy. Turning the display into a menu-processor requires a
little more work.
8. Update getOption():
9. Notice that:
10. Take a moment to test ManiMenu by running main() as a Java Application. If you
enter the number 5, then you should see the following:
Main Menu
1.) Create Record.
2.) Delete Record.
3.) List Records.
4.) End Program.
Number: 5
TESTING: Got 5
11. Feel free to change the MainMenu test program as desired. Be sure to close
hten save MainMenu.java so JavaOne can re-use our updates!
We now have a nice MainMenu processing & testing routine! All we need to do next is
to update JavaOne to MainMenu.getOption() so as to match-up user requests, to any
new program options.
package com.soft9000;
14. We will complete MyProgram as part of future exercises. For now, be sure to
save the & close MyProgram so JavaOne can re-use our new creation!
package com.soft9000;
while (option != 4) {
option = MainMenu.getOption(System.in, System.out);
if (option == '1') {
MyProgram.CreateRecord();
continue;
}
if (option == '2') {
MyProgram.DeleteRecord();
continue;
}
if (option == '3') {
MyProgram.ListRecords();
continue;
}
if (option == '4') {
break; // done!
}
System.out.println("Unknown: [" + option + "]?");
}
System.out.println("End: Thank You!");
}
}
import java.io.IOException;
import java.io.InputStream;
package com.soft9000;
package com.soft9000;
import java.io.InputStream;
import java.io.PrintStream;
import com.soft9000.helpers.Reader;
};
package com.soft9000;
39. The above code can also be found in the solutions folder in the archive file
mentioned at the start of this Exercise.
(end of lab)
(Labs End)
This section contains the answers to the Questions & Activates portion in the lectures
series.
Users who want to run our Java creations on their computer will need to install a Java
Runtime Environment (JRE.)
Software developers who want to create & run Java programs only need to install the Java
Developers Toolkit (JDK.) The JDK automatically includes the instllation of a Java Runtime
Environment (JRE.)
Problem 2: Attempting to read data from any external resource can have unexpected
problems.
In the case of reading data from an InputStream, an IOException must be either thrown or
caught.
NOTE: There are two primary advantages to catching & processing an expression within a
member function.
The first advantage to processing an exception locally is that the exception-processing logic
will not have to be re-written everywhere the routine is re-used.
The second advantage is that - whenever an invalid value can be defined (in this case, a value
of -1,) a simple, single comparison to something like the INVALID_VALUE in the above
example saves time, thought, deliberation, as well as several lines of code.
In general a single comparison to an invalid value is usually far more preferable than
endlessly adding many lines of exception-handling code wherever a predefined member
function is re-used.
After examining the entire program, the problem is that there is no way to know where reader
is. Without the type of fully-qualified path name discussed in the lecture, Java will not be able
to find the reader class.
When performing a string concatination in Java a plus-sign (+), not an amperstand (&), is
required.
While many Java software developers will complain when curly-braces are missing or
misplaced, their omission and misplacement in this context is both permissible, as well
possible amongst all syntax derived from the C/C++ Programming Language.
If phoneNumber remains null, the problem is that showSize will attempt to use a null member
variable. An attempt to access a member of any null object (such as the attempt to access
phoneNumber.length() in the above) will result in a run-time exception.
Please note that the package name for JavaOne need not be the same as show above.
The solution to this Activity is to simply update the calculation in your solution to QA03 to
use the minus (-) rather than the plus (+) operator:
While a double can indeed be used to contain everything that can be expressed as a float, the
float is all that is required to sufficently represent all point-of-sale currency transactions.
While a float can indeed be used to express everything at the point-of-sale, the double is a
better choice whenever an undefined set or series of mathematical calculations may be applied
to the value.
When entering input from a keyboard, flowcharts often use the Manual Input symbol.
For the purposes of this training, a Process box may also be used in your design.
main
Prompt:
Enter
Number
Read
Integer
End
NO YES
To read a number from the keyboard, we can use the readInt() from the lecture.
Immediately after the above, our main() for JavaOne should look something like:
Once run, a basic test case could look like the following:
The more complicated test verifies that all non-numeric input is ignored.
main
Prompt:
Enter
String
Read String
End
NO YES
Display Input
Each is
Character Empty?
The following implementation includes the opportunity to create our own readString ability.
When reviewing the final solution for this activity, notice how casting each byte - by using
(char) in main - converts each integral-byte value into a human-displayable character.
Like all diagram tyes, Flowcharts can depict either a high, or a low-level of detail.
main
Prompt:
Enter
String
Read Number
End
NO YES
Display Is Zero
Even or Bad
Numbers # ?
The following flowchart depicts the low-level detail for the requirement:
main
DONE
Print Prompt:
Done?
Even Enter
Number Number
EVEN
ODD
Is Read #
Even? End
Objective
Install and test the tools required for this training. In order to download the installation
files, an Internet connection is required.
Overview
You will be performing the following tasks
1. Download & install an Oracle Developer Kit for Java (JDK)
2. Adding Oracles Java tools to the command prompt, as required
3. Download & install the Eclipse Integrated Development Environment (IDE)
This training was written to support the most recent version of both Java and Eclipse.
Moving forward, there should be no reason why the training will not work with the
most current release of these two products.
At the time of this writing, the software developer tools used by this training are free.
Minimum Requirements:
Java JDK: Version 1.7, or Java 7.
Eclipse IDE: Juno or Kepler.
Operating System:
Windows XP or greater
Ability to Install Software (Administrator Rights)
8 - 12 GB Available Hard Drive (HDD)
2 - 4 GB Programming Memory (RAM)
a. We recommend using Eclipse Juno or greater. You will want to install the
Eclipse IDE for Java Developers.
b. Juno: http://eclipse.org/downloads/packages/release/juno/sr1
c. Kepler: http://eclipse.org/downloads/packages/release/kepler/r
3. Once both Eclipse and the Oracle JDK have been downloaded, proceed to the
next step.
there can be many settings that may manage where files may be downloaded on
your computer.
i. You might wish to discuss where, when, and if (!) you are able to
download and install Java on your computer.
ii. Try saving downloaded files to removable media (like a USB Storage
Device or Thumb Dirve.) You should have at least 8 GB free on your
removable device.
ii. Be sure you have enough space for the download & installation process.
In order for Eclipse to find the software developer tools, the SDK must be installed
before the IDE.
6. Locate & click-on the downloaded JDK to start the installation process.
12. Verify that a minimum version of Java 1.7.x has been installed. Version 1.7 or
created is required by this training.
a. If the java command is not recognized, then Oracle Java has not been
properly installed.
b. If the version of Java is not 1.7 or greater and the recommended version
of Oracle Java has been installed, note that in order to complete any
command-line exercises in this training that you will need to either:
The Eclipse IDE is distributed either within a ZIP file or (On Microsoft Windows) as an
.EXE installer file.
14. If you have downloaded a Microsoft Windows Installer, click on the .EXE file.
Follow the instructions to complete the installation process.
15. If you have a .ZIP file, clicking on the file will open the archive. To install Eclipse,
merely drag-and-drop the enclosed eclipse folder to your desktop.
16. Once Eclipse has been installed, clicking on the eclipse icon located directly
underneath the eclipse folder will start the Eclipse IDE.
Please refer to the video section on YouTube to locate and download the associated
training exercise solution files, as desired.
(end of setup)