Java Programming
Dr. Ernest J. Friedman-Hill
ejfried@herzberg.ca.sandia.gov
http://herzberg.ca.sandia.gov/JavaCourse
‘Tis well blown, lads.
This morning, like the spirit of a youth
That means to be of note, begins betimes.
So, so. Come, give me that: this way; well said.
Fare thee well, dame; whate’er becomes of me,
This is a soldier’s kiss. Rebukable
And worthy shameful check it were to stand
On more mechanic compliment. I’ll leave thee
Now like a man of steel. You that will fight,
Follow me close; I’ll bring you to’t. Adieu.
--Antony and Cleopatra, IV.iv.25-33.
If your development tools don’t suck, you’re not on the bleeding edge.
-- Overheard at JavaOne opening reception
Your Instructor
ejfried@herzberg.ca.sandia.gov
http://herzberg.ca.sandia.gov/JavaCourse
PMTS at Sandia National Labs
Ph. D. in Chemistry, MIT 1992
Teaching Java since Spring 1996
Research in distributed computing and AI
Wrote Jess, JIDL, Jlpr
What We’ll Do Today
Class mechanics
Overview of the Java language
Background
Syntax
Objects
First Homework Assignment
Notes on the Web:
http://herzberg.ca.sandia.gov/JavaCourse/
Make sure you're looking at the NEW one!
What We’ll Do Later
More Java syntax
Programming style
Object-based design
Java idioms
Multithreaded programming
Graphics and the AWT
Networking and I/O
Advanced and enterprise APIs
JDBC
Java Beans
Java RMI
What We Won’t Do
HTML and WWW tools
SilverStream, NetDynamics
Servlet APIs
IDEs and RAD environments
Symantec Café, Borland JBuilder
Microsoft extensions
J++, AFC
Java 1.2 features
Java 2D/3D APIs
What You’ll Do
Write programs (40%)
Three programming assignments
Do a term project (40%)
A small application that solves a real problem or serves a real need
Ask questions (20%)
Participation via email or in class is expected
What You’ll Need
A Computer with Internet Access
Win32, UNIX, Macintosh OK
Textbook
David Flanagan, "Java in a Nutshell", O'Reilly, 1997 (2nd ed.), ISBN 1-56592-262-X
A Java Compiler
Sun’s JDK 1.1 or third-party
http://www.javasoft.com/products/jdk/
- I can’t help you with IDEs!
- The JDK Documentation
- Nutshell book
- HTML version (see above URL)
Grading System
Grade:
40% Homework
40% Project
20% Participation
Scores
No Grade, OK, Good, Excellent
Grading on a Curve
Median is B+/A-
Who You Are
Write on a Piece of Paper
What you do
Why you want to learn Java
How long have you been programming…
in C/C++ ?
in another language?
What other languages do you know?
Anything else you’d like me to know
What’s Wrong with (X)?
Portability
Lack of binary or source portability
Lack of cultural portability
Maintainability
Hard to read or understand
Hard to modify
Hard to share
Safety (robustness)
Random crashes
Security (viruses, trojans)
Worse with Internet
Toasters and Televisions
Jim Gosling, Sun Fellow
NeWS, Gosling Emacs
"... small, reliable, safe, long-lived, portable, real-time, distributed systems."
"HomeNet"
Security model based on commerce
C++ was too nonportable, too insecure, too unsafe, too unmaintainable
Enter Java!
Introducing Java
Java is a language plus a machine to run it on.
Portability
Virtual machine architecture
Unicode
Maintainability
Standard APIs
Dynamic linking
Familiar syntax
Safety and robustness
VM has no raw memory access
Security
VM is a "deep sandbox"
The Java Virtual Machine
Java runs on a simulated computer
Compiled, not interpreted
With JIT, close to C++ in speed
The JVM is sophisticated
Code verification
Memory management
Threads
Exceptions
Java is not a scripting language!
Sun's JavaChip: JVM in silicon
Using the JVM without Java
The Java Virtual Machine
The JVM makes Java portable
Simulate JVM on any machine
Very precise specification
The JVM makes Java robust
No stray pointers
No memory leaks
Safe arrays
Code verification
The JVM makes Java secure
Disconnecting virtual hardware
Digital signatures and JAR files
The Java Virtual Machine
The JVM executes a special machine code ("bytecode")
Java compiles to *.class files
It has native support for
TCP and UDP Networking
A graphical windowing environment
Multiple threads of execution
Generally embedded in a program on the host OS
A command-line program ("java.exe")
A web browser
A C/C++ program you write
A monitor program in an embedded device
Java and the WWW
Java was first deployed in Web browsers
Sun's HotJava, written in Java
Netscape 2.0
Applets vs. Applications
An Applet is a small snippet of Java code that implements the Applet API and can therefore be embedded in a Web browser
An application is a larger body of code
Java can do both
Applets can be useful
History of the WWW
1989: Proposal by CERN physicist
Soon links many European sites
1993: First graphical browser (NCSA Mosaic) for PC, Mac, UNIX
Late 1994: WWW is majority of Internet traffic
Spring 1995: Alpha release of Java from Sun
Late 1995: Java in Netscape beta
Spring 1997: Java 1.1 released
Spring 1998: Java 1.2 in beta
Java and Microsoft
Graphical GUI Design
Invisible nonportability
Microsoft J++ (jvc)
Embrace, Extend, Control
Method references and delegation
Secret GUI extensions
"Inner Classes" behavior
Microsoft's JVM (jview)
Internet Explorer
Roughly twice the speed of Sun's
OLE integration
I use jview for testing; Sun's JDK for compiling, production
The Java Language
Java looks like C and C++
int i, sum=0;
for (i=1; i<=10; i++)
{
sum = sum + i;
}
- Variables must be declared
- "
++" means increment
- Semicolons terminate statements
- After this code,
sum contains 55
A C Program
int
main(int argc, char** argv)
{
int i, sum=0;
for (i=1; i<=10; i++)
{
sum = sum + i;
}
printf("The sum of 1 to 10 is %d\n",
sum);
return 0;
}
Whitespace not significant
Pick a style and be consistent!
A Java Program
public class SumOneToTen
{
public static void
main(String[] argv)
{
int i, sum=0;
for (i=1; i<=10; i++)
{
sum = sum + i;
}
System.out.println("The sum of 1 " +
"to 10 is " +
sum);
return;
}
}
Lots of little changes: class declaration, main looks different, no printf...
A Java Program
Classes
public class SumOneToTen {...}
SumOneToTen.java - case matters
All Java code inside classes
The function main()
Entry point of applications, not Applets
Always
public static void main(String [] argv)
argv.length is number of args
program name is not first argument
System.out.println
How to print anything!
We’ll dissect this later
Running A Java Program
Proper file naming
A public class must be in a plain ASCII file named <classname>.java - case matters
Compile source to bytecode:
javac SumOneToTen.java
produces SumOneToTen.class
Run the program:
C:\> java SumOneToTen
The sum of 1 to 10 is 55
C:\>
Code Formatting
Important to maintainability
Bracket placement
Consistent indentation levels
Capitalization
variableNames, ClassNames
Variable declarations
Near first use, not at top of function
More in later lectures
Java is "Object Oriented"
In the beginning, there was FORTRAN...
PROGRAM RECTANGLE
REAL*8 X, Y, H, W, A
X=10.0
Y=10.0
H=5.0
W=12.0
A = RAREA(H,W)
Arrays are the only way to structure or group data
Java is "Object Oriented"
Later languages added records
typedef struct rect {
double x,y,h,w;
} rect;
rect r = {10.0, 10.0, 5.0, 12.0};
double area = rectarea(r);
Data collected together; code still separate
Java is "Object Oriented"
Modern languages use objects
public class Rect
{
double m_x, m_y, m_h, m_w;
public Rect(double x, double y,
double h, double w)
{
m_x = x; m_y = y;
m_h = h; m_w = w;
}
double area() { return m_h*m_w; }
}
Rect r = new Rect(10, 10, 5, 12);
double area = r.area();
Now a Rect "knows" its area!
If there were a Circle class,
Circle c = new Circle(10,10,5);
float area = c.area();
Basic Java Syntax
Strong Typing
Declare all variables before use
Each variable has a very specific type
int i = (int) 3.2; // OK
int i = (int) "Hello!"; // error
if (i)... // error
boolean fun = true;
if (fun) ...
Functions ("methods")
Definite number of args of specified types
Definite return type
Always attached to classes or objects
Basic Java Syntax
Arrays
Always created using new
int[] intArray = new int[20];
An array variable refers to an array
int[] intArray;
int i = intArray[3]; // runtime error
intArray = new int[20];
int j = intArray[3]; // OK
An array knows its length
int length = intArray.length;
Indexes go from 0 ... length-1
System.arraycopy()
An array of String just holds Strings
String[] sArray = new String[2];
sArray[0] = "A String";
sArray[1] = "Another String";
Basic Java Syntax
Strings
Strings are objects, not char arrays
They have methods
String aString = "A String"; // or…
String aString = new String("ABC");
if (aString.equals("Some String"))…
int i = aString.compareTo(bString);
char c = aString.charAt(13);
int len = "A lovely String".length();
A String variable refers to a String
String noString = null;
int i = noString.length(); // error!
String emptyString = "";
int j = emptyString.length(); // OK, 0
Concatentation
String ans = "The answer is " + 42;
Basic Java Syntax
Basic Console I/O in Java
Output:
System.out.print(...);
System.out.flush(...);
System.out.println(...);
Input:
import java.io.*; // top of file
public static void
main(String [] argv)
throws IOException // add this
{
BufferedReader stdin =
new BufferedReader(new
InputStreamReader(System.in), 1);
String s = stdin.readLine();
int i =
Integer.parseInt(stdin.readLine());
Java vs. C/C++
Java is based on C and C++
Influences from Smalltalk, LISP...
Some things removed: Pointers, addresses, unions, preprocessor, multiple inheritance, enums, unsigned types, operator overloadin
g
- Some things added: Garbage collection, Unicode, references, threads, interfaces, signed shifts
- Some things C++ got only recently: Namespaces, uniform exceptions, runtime type info, type boolean, safe casts
Java vs. C/C++
Java is better than C/C++
Java code is easier to read
No memory management code
No complex pointer arithmetic
Platform-independent APIs!
Java code is more robust
Runtime and preflight checking
No stray pointers
Strict, savvy compiler
Java is dynamic
Runtime type info
Portable dynamic linking
Dynamic method calls
Java is portable
You can send binary code around!
Java vs. C/C++
Java is worse than C/C++ ?
Tool problems
Makedepend is hard without IDE
Compiler problems
Optimization still weak (improving)
Speed
Typically, Java code is slower
Dynamic linking
Runtime link and versioning failures
Platform support
Mac, Be, Amiga support weak
Not all UNIXen supported
Benefits outweigh drawbacks
Java vs. C/C++
Java is just different than C/C++
Garbage collection changes everything
Java design vs. C design
Java can't be "a better C"
No global functions or variables
Java design vs. C++ design
Using dynamic elements of Java
"Writing to an interface"
Using Threads and Exceptions
Being an expert C/C++ programmer does not make you a good Java programmer!
Java API Documentation
In textbook...
... or download from JDK page
Packages (collections of classes)
Classes (bags of data and functions)
Functions
Important packages
java.lang, java.io, java.util
Others will wait until later
Look at inherited functions
Since java.lang.String extends java.lang.Object, Strings have the equals()method described in the Object documentation.
Other Java Information
http://www.javasoft.com
The mother lode - free software and tons of information
http://www.gamelan.com
Lots of miscellaneous stuff
http://www.javaworld.com/
An online Java magazine
http://herzberg.ca.sandia.gov/JavaCourse
These notes, online
Your First Assignment
Write a program that prompts for input strings from the user, then sorts them and prints the sorted results. You can use any sorting method you’d like; you won’t be graded particularly on the efficiency of your program. The compareTo() method in the java.lang.String class should prove helpful. Use the API documentation to read about it. You’re going to have to use the documents a lot during the course, so take the time to familiarize yourself with their layout and contents. Don’t be afraid to browse around and read whatever looks interesting.
- Email if you need help
- ejfried@herzberg.ca.sandia.gov
Your First Assignment
For next week:
Set up your development environment
Note that some IDEs will have problems with this command-line program
StringSorter program
PAPER ONLY, PLEASE!
Read Chapters 1 and 2 in Flanagan
Skim Chapter 3 in Flanagan
We'll cover much of this material next week, then reread the Chapter