Java the easy way James A. Rome Tennessee Governor's Academy August 2010

Java the easy way
James A. Rome
Tennessee Governor's Academy
August 2010
Why Java?
 Java is the most in-demand
language (= job opportunities)
 It is a modern object-oriented
language
 It is similar to C and C++
 It leaves out pointers, multiple
inheritance, operator overloading
 Write once, run anywhere
 From supercomputers to cell
phones, Macs, Windows, Linux
 It is faster than any language other
than Fortran or Assembler
 There are oodles of libraries
 Free excellent development tools
Java programmers are in demand
http://www.eweek.com/c/a/ITManagement/ProgrammingDevelopment-Skills-In-Demand-505665
In the WSJ recently, there was a long
article on how the language you use
affects how you think.
Computer languages foster logical
thought.
• But many scientific calculations do
not fit nicely into existing computer
languages
• Remember that digital computers do
discrete mathematics and computations:
calculations are done at a finite number
of points.
-> round-off and truncation errors
-> most floating point numbers cannot
be represented exactly in binary
Tools you will need (installed I hope)
 The Java development kit
http://www.oracle.com/technetwork/java/javase/d
ownloads/index-jsp-138363.html
 The NetBeans IDE. Some people prefer Eclipse
http://www.netbeans.org
 A programmer's text editor such as
http://www.crimsoneditor.com/
 We may get to databases, so I asked for MySQL
http://www.mysql.com/downloads/mysql/
http://dev.mysql.com/downloads/workbench/#do
wnloads
Our foray into Java
Purpose: Get your feet wet so you can understand how
scientists use computers and teach yourself more Java.
 The book is really good, so please read it.
 I want to concentrate on what is not in the book
 How to do a graphical user interface (GUI)
 How to model a real problem and get it into a form a
computer can solve
 How to teach yourself
 Along the way we will use and learn many Java
Classes and techniques
Some basic syntax
 Assignment uses an equals sign
 int b = 4; // assigns 4 to the integer variable b
 Testing for equality uses ==
 if(b == 4) { /* do something when b is 4 */}
 // Comments to the end of the line
 /* . . .*/ Comments blocks, which can be many lines
 /** . . . */ A JavaDoc comment
 Java is self documenting if you put these comments into your
code they get converted to nice html
 Formatting is optional but important for readability
 All statements must end in a semicolon
 Braces {} group lines of code and define a scope
 Things defined in the braces are not accessible outside them.
 Names must start with a letter
Java syntax
Built-in types for variables:
 char, int, short, byte, long, float, double, boolean
 These are not Objects. But all have wrapper classes
that turn them into Objects
int a = 5;
Integer aInt = new Integer(a);
 Everything else is an Object (think noun, its a thing)
 Unlike in C or C++, these are the same on all platforms
 Otherwise (without ints, floats,…) , you could not
write
a = b + c;
Loops
starting values
do while
at end of loop do this
int j = 0;
for(int i = 0, j = 5; i < 3; i++) {
j += i;
// becomes 5, 6, 8 (same as j = j + i)
}
// j = 8 at end of loop
// i no longer defined here because outside the {}
while(j < 10) {
// Test at start of loop
System.out.println("j=" + ++j); // preincrement
} // Prints out j=9, j=10
Class methods or fields
are referenced using "."
System.out returns a
do {
// Test at end of loop
PrintStream object,
System.out.println("j=" + j++);
which has a method
println()
}
while (j < 20); // prints out j=10, ...j=20
Logic (make decisions)
int a = 3;
while(a < 12) {
if(a == 5) // == is a test for equality
System.out.println("Hit a=5");
else if(a < 10)
System.out.println("a < 10");
else
System.out.println("a >= 10");
a++; // if you forget this, you get an infinite loop!
}
// Ternary operator
int b = ((a > 7) ? 0 : 1); // Usually a good idea to put
if(b != 5) b += 7;
// Parens around the condition
Case statements
char c = 'b';
switch(c) {
case 'a':
System.out.println("a");
break; // if break is missing, this “falls through”
case 'b':
System.out.println("b");
break;
default:
System.out.println("not a or b");
}
The argument you switch on must be an int, char, short, or
byte. Used to improve logic and speed decision trees with a
hash.
Everything in Java is part of a class
Classes represent objects from the real world.
Think of a class as “The definition of a set where each member of the set exhibits
the same behavior and has the same attributes and associations.”
 Good programmers decide what classes they need to write before
starting to write a program!
 Classes in Java may have methods and attributes.
 Methods define actions that a class can perform.
 Attributes (or fields) describe properties of the class
 Classes are described in JavaDocs that are generated from
comments in your code.
(http://docs.oracle.com/javase/7/docs/api/)
 You need to learn what the basic classes do by reading JavaDocs:
String, Collection, HashMap, Vector, BufferedReader, BufferedWriter,
Integer, Math, File, …
 Call with ClassName.method() or ClassName.attribute
Creation of a Pet
public class Pet {
int age;
// with no public, private, these are
float weight; // these are all protected
float height;
String color;
/** Method to put pet to sleep */
public void sleep() {
System.out.println("Good night. See you tomorrow");
file:///home/jar/TGA/Presentations/FermiAc
}
celeration.ppt
/** Method to feed pet */
public void eat() {
System.out.println("Feed me a cookie!");
}
/** Method to let pet speak */
The returned type
public String say(String aWord) {
String petResponse =
"OK!! OK!! " + aWord;
return petResponse;
}
}
What is an IDE?
 You write, compile, run, and profile your program
within the Integrated Development Environment
(IDE).
 It makes your life simpler:
 A code-friendly editor with context highlighting, code
hints, and code completion
 It makes it really easy to create a graphical user
interface
 It write lots of boiler-plate code for you
 NetBeans is also great for C/C++, Python, Ruby,
Fortran
 It is extendable with numerous plugins
 NetBeans is my favorite IDE by far
 You might like Eclipse or JDeveloper
NetBeans should be installed
 Start NetBeans IDE
Start/All Programs/
 Tools/Plugins/Insta
lled Tab
 Make sure that
Java SE is
activated
Set your NetBeans options
Under Tools/Options
 In General: Pick your favorite
Web Browser
 Under Options/Formatting,
set the indent and tab sizes
to 3 characters
 You can look at the other
options at your leisure
Install the JavaDocs
 The Java documents come in
a zip file: jdk-7u??-docs.zip
[download it from the JDK page]
 NetBeans is smart enough to
use it in its zipped form, but
you might also want to use it
in your Web browser, so
copy the file from the cd to
your Documents folder into a
Java subdirectory. Unzip it
by double-clicking on it.
 Add the zip file to NetBeans
Tools, Java Platforms
 You could add the source
code here also
Create a Pet in NetBeans
 File/New Project
 Create a new Project called “MyPets”
 Do not create a Main Class
Make a Package for your project
A package is a way of
specifying a set of classes that
have special privileges because
they belong with each other.
 They avoid name collision
 By convention, you use a
reverse DN (e.g.,
com.sun.java.utility)
 We will use mypets (in lc)
 Right-click the MyPets
Source Package name and
select “New, Java Package”
Create the Pet Class
Right-click the mypets Package and select “New,
Class”
• Note that the file is always
classname.java, and it is stored
in the package directory tree
• By convention, Classes start
with an uppercase letter.
Pet Code
Elements of our class:
 Four class attributes
 Three class methods
 One class constructor
In Java, things have visibility:
 public — visible and usable to all
 private — only accessible by this
class
 protected (default) —accessible by
classes in this package
Visibility keeps code clean and
secure. If you want something
visible, create getter and setter
methods
 So the attributes are private
Classes must be instantiated
In order to do anything with a
class you must “create an
instance of the object.”
This uses the class definition
to make a copy of the object
described by the class and to
put it in the computer’s
memory.
Pet myPet =
new Pet();
myPet is the name of the
instance and is a member of
the class Pet.
We need code to instantiate Pet
public class PetMaster {
class signature
public static void main(String[] args) { main method
String petReaction;
Local variable
}
}
Pet myPet = new Pet();
Make a Pet
myPet.eat();
petReaction =
myPet.speak("Tweet!! Tweet!!");
System.out.println(petReaction);
myPet.sleep();
Call the Pet methods
Make a PetMaster Class
Run the project
The project needs to know where the
main() method is.
• Right-click the Project, and select
Properties
• Note that you must specify the
package as well as the class name in
the Run settings
Run your project by either
clicking the green arrow, or
selecting Run Main Project
on the Run Menu
Inheritance
Our class Pet will help us learn yet another important feature
of Java called inheritance. In real life, every person inherits
some features from his or her parents. Similarly, in the Java
world you can also create a new class, based on an existing
one (but only one).
A special keyword extends does the trick:
class Fish extends Pet {
}
Fish is a subclass of the class Pet.
Class Pet is a superclass of the class Fish.
Fish myLittleFish = new Fish();
myLittleFish.sleep(); (Fish inherits all of the methods of Pet)
Making a subclass
Creation of subclasses in
NetBeans is a piece of cake!
Right-click the package and
select New, Class, and type Fish
as the name of the class.
Then put in “extends Pet”
before the first {
Let’s not forget, however, that
we’re creating a subclass of a
Pet to add some new features
that only fish have, and to reuse
some of the code that we wrote
for a general pet.
Everything inherits from Object
Fleshing out our Fish
public class Fish extends Pet {
private int currentDepth = 0;
// keeps track of the depth
public int dive(int howDeep) { // a new method for fish
currentDepth = currentDepth + howDeep; // Incremental
System.out.println("Diving for " + howDeep + " feet");
System.out.println("I’m at " + currentDepth +
" feet below sea level");
return currentDepth;
}
@Override // An annotation. This overrides Pet.speak
public String speak(String something) {
return("Don’t you know fish do not talk!");
}
}
Need to change PetMaster
public class PetMaster {
public static void main(String[] args) {
String petReaction;
// Your previous code can stay here.......
Fish myFish = new Fish();
myFish.dive(2);
myFish.dive(3);
petReaction = myFish.speak("Glug");
System.out.println(petReaction);
myFish.sleep();
}
}
Run the code again with your fish
How to run without NetBeans
Taken from README.TXT in the MyPets/Dist folder:
When you build an Java application project that has a main class, the IDE
automatically copies all of the JAR
files on the projects classpath to your projects dist/lib folder. The IDE
also adds each of the JAR files to the Class-Path element in the application
JAR files manifest file (MANIFEST.MF).
To run the project from the command line, go to the dist folder and
type the following:
java -jar "MyPets.jar"
To distribute this project, zip up the dist folder (including the lib folder)
and distribute the ZIP file.
User interfaces
The cartoon Lifted was shown along with Ratatouille. It is all about user interfaces.
© Pixar
Note the thousands of identical and unlabeled controls
It is even worse under pressure
© Pixar
Making an application with a GUI
There are several methods of making graphical user
interfaces in Java — AWT, Swing, SWT. We will
concentrate on Swing.
 Swing is built into all modern JDKs
 A Swing book is on your CD
 It is an easy-to-use high-level java interface
 Swing components are Java Beans
 A Java Bean Object has get and set methods
 It adheres to certain naming conventions
 Java Bean properties can be manipulated in GUIs by
tools such as NetBeans
But you must always remember the user!
Making a GUI application using NetBeans
 Open NetBeans and do File,
New Project
 Select Java Application
from the Wizard and hit
Next
 Uncheck Create Main
Class
 Enter the project Name
YourName and hit Finish
 The YourName project will
appear in the left Package
Window, with a package, files,
and a blank GUI
NetBeans has a new GUI framework
Make a new Java package
Create a new GUI class based upon
A JFrame by right-clicking the yourname
Package.
Your new GUI project
Palette has
components
you can place
onto the GUI
Navigator
Lets you
set parameters
of each
component
and rearrange
them
Set the
properties of
each component here
Add a prompt label
The solid semi-circles
indicate that this
component is pinned
to the edge if the
component is resized.
 Click the Label in the Palette (top-right)
Swing controls, and then click near the
top-left of the design area
 Use the dotted guidelines to space from
the top and left edges.
 Double-click jLabel1 to edit the text and
hit Enter (or else it will not "stick")
Add a TextField for data input
 Add a TextField. Note the three spacing option lines and the
lower edge alignment markers
 Drag the right edge of the TextField to the right edge until the
vertical dotted line appears. This pins the field to the right edge.
 Double-click “jTextField1”, delete it, and hit Enter.
Right-clicking and selecting “Edit text” may work better.
 Try to run your project.
Rename your swing objects
 It is very important to replace the default names in a more
complicated project so that you know which text field (or
other object) is which.
 Right-click each label and change its name
 I used “enterNameLabel” and “enterNameTextField”
 Note that by convention, variables start with a lowercase letter, and I retained the Swing type in the name
 Do this to all your Swing objects in the future...
Run the app
 Notice how the TextField is pinned to the top and right
edges as the window is resized.
 Windows Apps do not have this nice property, which is
due to using a Layout Manager
What is a Java Bean?
 A class that exposes its accessor methods:
 For each public class member, there is a get and set
method
 It must be serializable. This allows the instance of
the class to be written to a file and read back
again.
 class ClassName implements Serializable {....}
 It must use member names that start with
lowercase
 private String myString = “Boo!”
public String getMyString(void) {return String;}
public void setMyString(String s) { myString = s;}
 All Swing components are Java Beans
 Therefore, we can make our own GUI components by
extending a Swing class
Eliminate the StatusBar
Source view
Click StatusPanel and
delete it
Delete the statusBar code
At the end of YourNameView, delete
private final Timer messageTimer;
private final Timer busyIconTimer;
private final Icon idleIcon;
private final Icon[] busyIcons = new Icon[15];
private int busyIconIndex = 0;
In the constructor, delete all but
public YourNameView(SingleFrameApplication app) {
super(app);
initComponents();
}
Fix the App name
 Expand the yourname.resources package
 Open Application.description
 Change the Title (to "Your Name" ) and you can replace
the other fields (e.g., Vendor or the Description) if you
wish.
Save your project
Add an OK Button & output Label
 Add a Button aligned to the bottom-right edge guides (which
pins the button to this corner as the frame is resized).
 Rename it to okButton, and change the displayed name to
“OK”.
 Add a Label for the output text called “outputLabel”. Stretch it
to fill the horizontal width up to the right guideline. Delete the
text (the label will collapse to a line).
 I made the whole frame smaller vertically
The Label is
pinned to the
left edge and the
top of the button
Save your project
Change the font for the outputLabel
Double-click the ... to open
the font dialog. Pick a font
you like!
Save your project
Add an action event to the JButton
 The GUI is done, but it does not do anything yet!
 An ActionPerformedEvent occurs when a button
is pressed. At that point we can get the text the
user typed and display it.
 Right-click the okButton and add the event.
Save your project
ActionEvent code
Source view
w
The yellow
bars indicate
unused imports.
Right-click in the
code and
choose "Fix
imports"
(They belonged
to the progress
bar that we
deleted.
Code completion and JavaDocs helps
private void okButtonActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
String name = "Your name is " +
Strings are immutable.
enterNameTextField.getText();
They are stored and
outputLabel.setText(name);
never changed.
}
Save your project
Run the code
Defects in the application:
 It would be nice to let the user hit “Enter” in addition to
clicking the button
 Can make it prettier. (e.g., Colored text)
 This is a possible security hazard because we do not
check what the user typed in. (It would be for sure in a
Web Application.)
Adding a key event
Right click the enterNameTextField
and do Event, Key, keyTyped.
private void enterNameTextFieldKeyTyped(java.awt.event.KeyEvent evt) {
// TODO add your handling code here:
}
Edit the JTextField KeyListener
'\n' is generated when
the user hits Enter.
Note that chars are in
single quotes.
This code appears
twice. It is a good
candidate for a new
class method. Then
any changes to this
code only have to be
done once.
How????
Run your code and verify that hitting Enter is the same as clicking OK
Homework assignment
Make a Magic FortuneTelling Machine
 Make a fortune-telling GUI– press
the button and get an answer.
 Answers: Yes, no, maybe, unlikely,
focus and ask again, cannot foretell
now, looks like yes, indications say
yes, consult me later, can't say now,
absolutely, chances aren't good, don't
bet on it, answer unclear ask me
later, prospect good, very likely…
 Make your own list
 Put in random delays before
answering
 Put in intermediate messages
("I'm thinking")
Code issues:
 Will need Math.random()
 It returns a double from 0.0 to
<1.0
 For example, if there are 10
possible answers
int j = (int)10.0*Math.random();
 Will want to put answers in an
array:
String [] answers =
{"Yes", "No",…}; // 10 entries
 So, to get the random answer,
just use answers[j]
 One way of getting a delay is to
make a for loop in which you
do something that takes time
[e.g., Math.sin()] and repeat it a
random number of times.
Project: A RPN binary calculator
RPN = reverse Polish notation
 Easier logic and faster to use
 Example: 1+1=2
 1 Enter
 1+
// the result is displayed
 Example: 1 + 5 / 6 = 1
 1 Enter
5+
6/
// the result is displayed
 When you start to enter a number, the old result
is erased from the field
A RPN binary calculator
My GUI for RPN Binary Calculator-- you make one you like
This has the same
components you used
in the last project.
Questions to ponder:
• Does the code calculate
in binary or decimal?
• Where does the user
enter numbers?
• What does each
button do?
• How do you handle
negative numbers?
• Do you enter the binary
digits from right-to-left, or
from left-to-right?
Calculator logic
 Calculators have at least 2
registers:
 Accumulator accepts the
current entry
 Result stores the running
result
 The +-*/ keys
 They preform their
operation:
Result +-*/ Accumulator
 Display result
 Set clear flag and clears if
it was on
The number keys
 If first one, erases display
string
 Appends number to end
of display string
 The Enter key
 Replaces the result with
contents of Accumulator
 Sets clear flag
 The Clear key
 1st: Clears accumulator
 2nd: Clears result
Code snippets for the calculator
// New variables for Class
// The accumulator
private int accum = 0;
// The running result
private int result = 0;
// The binary answer
private String display = "";
private String binaryOut = "";
// Define constant variables for the operations
// The entry field needs clearing
private boolean clearEntry = true;
private void
oneButtonActionPerformed(java.awt.event.ActionEvent
evt) {
if(clearEntry) {
clearEntry = false;
accum = 0;
display = "";
}
accum = accum * 2 + 1;
display = display + "1";
binaryTextField.setText(display);
decimalTextField.setText(new
Integer(accum).toString());
}
private void enterButtonActionPerformed(java.awt.event.ActionEvent evt)
{
result = accum;
clearEntry = true;
}
private void plusButtonActionPerformed(
java.awt.event.ActionEvent evt) {
// Calculate the result
result += accum;
clearEntry = true;
binaryTextField.setText(toBinary(result));
decimalTextField.setText(new Integer(result).toString());
}
/**
* Convert a decimal number to binary and return it as a String
* @param decimal - the input integer
* @return The returned String binary representation of the decimal
number
*/
private String toBinary(int decimal) {
String binaryOut = "";
// Convert answer to binary
while(true) {
binaryOut = decimal%2 + binaryOut; //Move right-to-left
private void
decimal /= 2;
clrButtonActionPerformed(java.awt.event.ActionEvent
evt)
if(decimal == 0)
{
break;
// Make this so that the first time it is pressed,
}
// it clears the entry,
return binaryOut;
// and the second time it clears everything
}
if(accum != 0)
accum = 0;
else
result = 0;
display = "";
decimalTextField.setText(new
Integer(accum).toString());
binaryTextField.setText(display);
}
Decimal to binary conversion
Suppose we want to convert 9
to binary:
Must start with the lowest
power of 2(right-most bit)
 9/2 = 4 with remainder 1
 There must be a 1 in
2^0 right-most bit
 Divide the number by 2
which moves the binary
number one-place to the
right, so we are
checking the 2^1 place
 4/2 = 2 + 0 remainder
 There are no 2^1
 Answer so far = 01
 Divide 4 by 2 again to
check the 2^2 place
 2/2 = 1 with 0 remainder
 No 2^2
 Answer = 001
 Divide by 2 again to
check the 2^3 place
 1/2 = 0 with 1 remainder
 Answer = 1001
Additions and improvements
 Handle negative numbers
 Need to define the number of allowed places and the
sign bit
Will have to check for user input errors!
 Still calculate in decimal, but use two's complement in
the display
 Allow the user to input a positive binary number,
but change it to two's complement with a +/- key
 Possibly display the current result register
 Add a memory register