Java - An Introductory Language Tutorial
by E. Andrew Johnson, The Open Group Research Institute
Overview - What is Java
- New, general purpose object-oriented programming language from Sun
Microsystems
- Allows users to interact with Web pages beyond simply:
- reading them
- filling out a form
- answering questions
- Allows interaction with program running as an extension to your Web browser
- May be used to augment web page with both a new protocol and the program
which implements that protocol
- May be used for writing both network-oriented and local application
programs
History of the development of Java
- Started out in 1991 as Project Green
- focussed on O/S software for consumer electronic devices
- James Gosling recognized inadequacy of C++ and initiated development of Oak
language
- Green went through several false starts before dissolving
- Small group decided to adapt Oak (later named Java) to a web technology --
result was a new web browser, WebRunner (later named HotJava), operational in
1994
- Paper on Oak byte codes presented by Gosling at Programming Language Design
and Implementation (PLDI) conference in 1995
History of the development of Java
- Java/HotJava announced in April '95 - Alpha software release made
available
- Netscape licensed Java in May '95
- OSF ports of Alpha software started in June 1995
- Beta Java Developers Kit preliminary release in September '95 - no HotJava,
but support for other Java-capable browsers
- JDK release in January '96
Highlights of the Java Language
- It's Simple
- It's Object Oriented
- It's Safe
- It's Secure
- It's Portable
- It's Fast (potentially)
- It's Multi-threaded
Java - It's Simple
- Java has only the necessary functionality needed to implement its feature
set.
- It has omitted the features of C and C++ which have been considered to be "unsafe"
- pointer "forging"
- operator overloading
- static objects
- Memory is managed automatically, relieving the programmer from being
responsible for freeing unused space
- There is no Java preprocessor - the program that you see is the same
program that the Java compiler sees.
Java - It's Object Oriented
- Syntax and semantics inherited from C and C++, but many of its object
management features come from Objective C (e.g. interfaces).
- Unlike C and C++, there are no stand-alone functions, but only methods
associated with a class.
- Everything (except for the built-in primitive types) is either a class, a
method, or an object.
- Extensive class library comes with Java, to interface with:
- host operating system
- window manager
- network
- Java Applications and Applets may provide their own class library support
- May not replace "system" classes (for security purposes)
Java - It's Safe
- Four different levels of safety checks and enforcement to prevent the
introduction of viruses
- protect against deleting or modifying files
- protect against corrupting the operator of user's computer
- More strict type model than either C or C++
- Arrays are first class objects
- always range checked
- no visible conversion to pointer plus offset
- No implicit declarations in Java
- Only a minimum number of implicit conversions
Java - It's Secure
- Designed with the knowledge that binaries would be transmitted across
the network
- Run-time system performs the necessary checks to assure the integrity of
the system
- The classic points of entry into protected sectors of memory used by
viruses and Trojan horses are impossible
Java - It's Portable
- Java defines not only the language syntax but its detailed semantics
as well
- There are no "implementation defined" behaviors in Java
- All implementations must adhere to the Java rules exactly
- Integer types byte, short, int, long are 8, 16, 32, and 64-bit
- Floating point types float and double are 32 and 64-bit IEEE 754
- Character type is 16-bit Unicode
- Architecture neutral byte code format the same regardless of which platform
the Java compiler was running on
- Detailed rules in Java Language Specification and/or Java Virtual Machine
Specification
Java - It's Fast (potentially)
- Currently, all mainstream implementations of Java are running Java
programs interpretively
- port of the interpreter developed by Sun
- alternative implementation built from the Java Language and Virtual Machine
specifications
- Java byte code is similar to functionality to P-code or U-code
- Several experimental projects translating Java byte codes to either C or
native machine code
- Slower than C or C++, due to mandatory run-time checks
- For many small Java programs, no advantage of compiling over interpreting
Java - It's Multi-threaded
- Threads of control are an integral part of the Java language, not a
run-time library "add-on"
- Java offers preemptive multi-threading, implemented via the Thread class
- Especially important when developing applets
- provide the proper dynamics between the Java applet and the host browser
- prevent applet from usurping most of the compute cycles
The Java Language
- Program Structure
- Built-in Types
- Constructed Types: Arrays and Classes
- Packages
Program Structure
- Source code consists of one or more compilation units (.java files)
- Each compilation unit can contain:
- a package statement
- import statements
- class declarations
- interface declarations
- Java compiler reads a Java compilation unit and produces one or more binary
bytecode files (.class files)
- Named according to the names of the classes or interfaces in the
compilation unit
- Case is always significant
- Example: compilation unit MyClass.java containing classes named MyClass and
MyList will produce MyClass.class and MyList.class as output files.
First Java Program
// HelloWorld.java
// First Java program, to get experience with using the Java tools
class HelloWorld
{
public static void main (String args[])
{
System.out.println("Hello, World!");
}
}
To compile this program, enter the command:javac HelloWorld.java
This will produce the binary bytecode file HelloWorld.class as output.
To execute this program, enter the command:java HelloWorld
Hello, World!
should appear on your terminal.
Lexical Structure
- Java has a lexical structure similar to C and C++
- By design, to allow programmers familiar with either language to read Java
programs with little difficulty
- Both C and C++-style comments:
/* C-style comment: text is
ignored up to comment ending */
// C++-style comment: text is ignored up to
the end of the line
/** javap doc: text included in automatically generated
documentation */
- Extensive set of reserved words (beyond C and C++). Many to be introduced
during tutorial.
Analysis of HelloWorld Program
- A
class
statement, which introduces the class to be
defined.
- Identifier following the class keyword is the name by which the class will
be referenced.
- Set of possible modifiers on the class statement which affects its
utilization by other classes.
- A
main
method.
- Prototype (including the modifiers) must be written as shown to indicate
the Java program starting point.
- A
void
method must not return a value.
- Note that
String
is part of the Java language, so no special
headers or declarations are needed to use it.
- A call to the method
println
, which is defined in the Java
library.
- Java compiler will use the System class definition to do argument type
checking
- Java run-time system will use the System class to perform the
println
method
Control Constructs
- Java supports a complete set of control constructs:
- if-then-else
switch
while
loops (both top test and bottom test)
- for-loops
- try-catch blocks (for exception handling)
break
used to exit from a switch or loop statement
continue
used within looping constructs to advance to the
next iteration
- Both
break
and
continue
may optionally indicate which construct they apply to
(useful in nested constructs)
- There is no
goto
statement in Java
- The
return
statement is used to exit a method
- No return value is specified for
void
methods
- Otherwise, expression must be of same type as method return type
Exception Handling
- Try-catch blocks allow the Java program to handle error conditions
- occur directly within the try block
- occur in methods called in the try block
throw
statement raises an exception
- Nearest catch block prepared to handle the exception gets control
- Following catch block, execution continues at the next statement following
the entire try-catch block
- There is no resume capability
Java Built-in Types
- Each Java variable or expression has a definite type
- Java has a collection of built-in types for integer, floating point,
character, and logical data
- Each must have identical size and behavior on all Java implementations
- No need for conditional compilation directives
- New composite types constructed in terms of built-in types, classes, arrays
and interfaces
- There are 4 integer types, all with signed twos-complement values:
byte
(8 bits)
short
(16 bits)
int
(32 bits)
long
(64 bits)
- Expressions with mixed integer types will "widen" the smaller
type to the larger type
- There are two floating point types, both conforming to IEEE 754 rules:
float
(32 bits)
double
(64 bits)
- gradual underflow and generation of infinity on overflow (no exceptions)
- mixed floating and integer expressions automatically convert integers
Java Built-in Types (cont.)
- There is one character type:
char
(16 bits)
- Always unsigned
- Represented in the Unicode character encoding
- There is one logical type:
boolean
(1 bit)
- One of two values:
true
or false
- No implicit conversion to or from
boolean
Operators
- Both integer and floating point (arithmetic) types support all of the
standard arithmetic operations:
- addition (+), subtraction (-)
- multiplication (*), division (/), remainder (%)
- increment (++), decrement (--)
- comparison (==, !=, <, <=, >, >=), always yielding a
boolean
result
- Bitwise operators (operate on integer or boolean types):
- and (&)
- or (|)
- not (~)
- left shift (<<)
- signed right shift (>>)
- unsigned right shift (>>>)
Operators (cont.)
- Conditional operators, && and || (operate on
boolean
expressions only):
- Evaluate from left to right
- "short circuit" operators
- Example:
a < b && c > d || e == f
- If a < b evaluates to false, the && subexpression is false and
the evaluation of c > d will be skipped
- If both a < b and c > d evaluate to true, then the expression is
true, and evaluation of e == f will be skipped
- Assignment operator (=)
- To assign a variable from another variable or expression
- May be used in combination with other operators (e.g. "+="
meaning "is incremented by")
- Expression on right hand side converted to type of left hand side operand,
if possible
- No implicit conversions which result in loss of data (must be done via
explicit cast)
Java Pointers
- No explicit pointer types in Java
- Only Object References
- No conversions between Object References and integer types
- The constant
null
indicates a reference to no object
- 0 is arithmetic zero
false
is opposite of true
- Use the distinct constant value that fits the application
Constructed Types: Arrays and Classes
Constructed Types: Classes
- Declaration of a Java
class
shares many common aspects
with classes in C++
- Java only supports single inheritance
- Effect of multiple inheritance may be achieved through the use of the
interface
construct
- A class may be declared to be
abstract
- No method implementations provided
- All derived classes must provide implementations for all methods defined in
the abstract class
- Java classes may declare both variables and methods
- Variable defined inside of a class is an instance variable - one
copy per object
- Class methods invoked by applying them to an instance of a class object
Java Class Example
- Given the following class definition:
class MyClass {
int counter;
int getCounter () { return counter; }
void setCounter ( int val ) {counter = val; }
}
- class instance variables and methods are used as follows:
class Test {
public static void main (String args[]) {
MyClass myinstance = new MyClass();
int myval;
myinstance.setCounter(20);
myval = myinstance.getCounter();
System.out.println("Counter = " + myval);
}
}
Java Class Example: Notes
- Note that variables of the type of a class are also just references
- Actual object only comes into existence when allocated via the
new
statement
- A class variable declared with the
static
modifier has only
one copy of the variable
- A class method declared with the
static
modifier is invoked
without reference to a particular object
- May only reference other
static
variables and methods in the
class
- Each variable or method specifies its own visibility rules:
- public
- accessible to anyone
- protected
- accessible only to class and other derived classes
- private
- accessible only to class
- (default)
- accessible to any class in the same package as the defining class
Java Class Example (revised)
Java Class Example (revised): Notes
- The methods getCounter and SetCounter now have the same name: Counter
- Example of function overloading
- The two functions are distinguished by the type and number of arguments
- The class variable, counter, has been declared with the
private
attribute
- Variable accessible only to methods defined within the class
- Accessor methods provide a means of controlling the state of
instance variables
Object-Oriented Features
Storage Management
- All instances of classes and arrays are allocated via
new
- Resultant objects are managed by a garbage collector
- No free or delete statement (or facility)
- Memory only released when there are no existing references to it
- Reference set to another instance or set to
null
Initialization
- No variables in Java have undefined state
- Arithmetic variables initialized to 0
- Boolean variables initialized to
false
- Char variables initialized to the null character '\u0000'
- Array/class references initialized to
null
- Use constructor method to provide explicit initial values
- Has same name as class name
- May have zero or more arguments
- May be overloaded to allow different initialization types
- Constructor is called when an object is allocated (via new)
- Default constructor (one with no arguments) called if no
arguments supplied to
new
- Otherwise, appropriate constructor called based on type and number of
arguments
First Java Application
// Java program to compute the current value if the $24 paid for
// Manhattan Island in 1624 had been deposited in the bank
// at a specified annual rate, compounded annually.
class Manhattan
{
public static void main (String args [] ) {
long amt = 2400; // Express in cents
int rate;
short yr;
if (args.length == 0)
rate = 2; // default rate is 2% if none specified
else
rate = Integer.parseInt(args[0]);
for (yr = 1624; yr < 1996; yr++) {
amt += amt * rate / 100;
}
System.out.println("The amount in the bank in " + yr
+ " would be $" + amt / 100 + "." + amt % 100);
}
}
Notes on Application
- Every array has an array length associated with it
length
member may be used to query this length
- Used here to restrict access to existing arguments, if any
- Since all arguments are passed as String objects, must use an explicit
conversion to a numeric value
- Explicit conversion to monetary units also must be provided
Packages
- Java classes are collected into groups, known as packages
- Used as a mechanism for grouping classes which
- perform related functions
- constitute a complete API specification
- To be part of a package, a Java class must begin with a
package
statementpackage osf.andyj;
- Class is a member of the default package (empty name) if no package name is
specified
- Package name used for locating the Java bytecode file
- interface specifications
- method implementations
- Dependent compilation model
- Class must be compiled before it can be imported
- No circular dependencies among classes
- Package name consists of one or more dot-separated identifiers
- used to construct a path to locate the bytecode for the class
- usually done via the file system directory structure
Packages (cont.)
Method Signatures
Real Application (part 1)
import java.io.*;
class Mortgage {
// Convert double to dollars and cents
static String format(double dollars)
{ String numString = Double.toString(dollars);
int dotpos = numString.indexOf(`.');
if (dotpos < 0) // Check if whole number
return numString;
// Check if excess fraction digits
else if (dotpos < numString.length() - 2)
return numString.substring(0, dotpos + 3); // `.'+ 2 digits
else return numString + "0"; // Assume only 1 fraction digit
}
Real Application (part 2)
public static void main(String args[]) throws IOException
{ DataInputStream din = new DataInputStream(System.in);
System.out.println("Enter principal (e.g. 8250.00 :");
double bal = new Double(din.readLine()).doubleValue();
System.out.println("Enter annual interest rate (e.g. 10.25) :");
double intyr = new Double(din.readLine()).doubleValue() / 100.;
System.out.println("Enter number of years :");
short nyears = (short) new Integer(din.readLine()).intValue();
System.out.println("\nprincipal=" + bal + " interest=" + intyr
+ " years=" + nyears);
double intmo = intyr / 12.;
int npmts = nyears * 12;
double pmt = bal * (intmo / (1. - Math.pow(1. + intmo, -npmts)));
Real Application (part 3)
System.out.println("payment\ttotal\tinterest principal balance");
System.out.println("number\tpayment\tpayment\tpayment");
System.out.println("\t\t\t\t" + bal);
for (short mo = 1; mo <= npmts; ++mo) {
double prinpmt, intpmt = bal * intmo;
if (mo < npmts)
prinpmt = pmt - intpmt;
else prinpmt = bal;
bal -= prinpmt;
System.out.println(mo + "\t" + format(intpmt + prinpmt)
+ "\t" + format(intpmt)
+ "\t" + format(prinpmt)
+ "\t" + format(bal));
}
}
}
Application Execution
% java Mortgage
Enter principal (e.g. 8250.00 :
14000
Enter annual interest rate (e.g. 10.25) :
10
Enter number of years :
4
principal=14000 interest=0.1 years=4
payment total interest principal balance
number payment payment payment
14000
1 355.07 116.66 238.41 13761.60
2 355.07 114.68 240.39 13521.20
3 355.07 112.67 242.40 13278.80
...
47 355.07 5.84 349.23 352.14
48 355.07 2.93 352.14 0
%
Real Application Notes
- Declarations may appear anywhere within a class or method
- must precede first use
- promotes locality of reference
- contributes to the readability
- InputStream System.in only provides low-level, byte-oriented operations
- Associated with DataInputStream
- provides facilities to read in values associated with the built-in types
Conversions
java.lang
provides classes to treat built-in types as
Object references
- No equivalent of format conversions as in C's
printf
.
format
method included to provide this functionality
- Literal chars should be changed when subject to I18N
Applet Programming
- Basic Principles
- Actions and Events
- GUI Interfaces
Applets - Basic Principles
- Application
- Stand-alone Java program: starts at
main
and runs to
completion
- Applet
- Sub-program that runs underneath some other control program
- Applet Viewer
- Java-capable Web Browser
- Applet is event driven, responding to actions which occur in display
window
- Keyboard actions
- Mouse movement or buttons
Basic Principles (cont.)
Basic Applet Methods
- Many methods available to set up display in assigned area
- Small subset are the mininum requirement for most applets
- init()
- the initializer method
- called once after applet is loaded
- used for environment setup or resource allocation
- start()
- the start method; used to start an applet running
- Called every time the referencing Web page is put into view
- Not called directly by the applet
- stop()
- the stop method; used to stop an applet from running; the companion to the
start() method
- Called whenever the referencing Web page goes out of view
- If not supplied, applet could continue running until browser or viewer
terminates
Basic Applet Methods (cont.)
- Additional basic methods
- destroy()
- cleans up any resources held by the applet, including those allocated by
init()
- paint(Graphics g)
- used to "paint" a Graphics object into the allocated view area
- may happen only once for static area
- may happen many times for dynamic area
- Applet started via APPLET tag in HTML document
First Applet
// HelloWorldApplet.java
// First Java applet, to get experience with using a Java-capable browser
import java.applet.Applet;
import java.awt.Graphics;
public class HelloWorldApplet extends Applet
{
public void paint (Graphics gr)
{
gr.drawString("Hello, World!", 10, 100);
}
}
Notes on First Applet
- Doesn't require an init(), start(), or stop() method because it is
only passively displaying text.
- Any applet that contains overrides the start() method should also provide a
stop() method
- Assure that applet is in sync with the browser
- Prevent runaway applets
Running Applet
Applet Display
Notes on Applet Tag
- The
code
parameter tells which applet is to be started
- In the same directory as the HTML file by default
- Common convention is to place applets in
classes
subdirectory
- Supply
codebase=classes
Applet parameter
classes
directory may reflect package
structure
- Both the
height
and width
parameters are
required
- Determines initial viewing area
- Applet may attempt to resize area (Netscape ignores)
- Other optional Applet parameters (
alt
, name
,
align
, vspace
, hspace
) affect the
placement of the initial viewing area
Applet Parameters
- Desirable to provide initial values to an applet at the time it starts
up
- Use the
param
feature within the Applet tag
- Not for receiving user-specified parameters
- Use GUI (Graphical User Interface) methods in AWT instead
- Interactions within Browser or Applet-specific windows
Actions and Events
GUI Interfaces
- Consider converting the Mortgage program into an applet
- Instead of communicating to the user via the standard input and output
files (System.in and System.out), use GUI features
- Label
- to make annotations in the window
- TextField
- to permit the user to input text
- Button
- a push-button to cause an action
- TextArea
- similar to TextField, but
- may contain a large amount of text
- permits viewing with scroll bars
- Program waits for the user to enter data into the fields and signal via the
push button that fields have been filled in
Mortgage Applet (1)
import java.applet.Applet;
import java.awt.*;
public class MortgageApp extends Applet
{ TextField balField;
TextField intField;
TextField nyrField;
Button OK;
TextArea msgArea;
Mortgage Applet (2)
// Convert double to dollars and cents
static String format(double dollars)
{ String numString = Double.toString(dollars);
int dotpos = numString.indexOf(`.');
if (dotpos < 0) // Check if whole number
return numString;
// Check for excess fraction digits
else if (dotpos < numString.length() - 2)
return numString.substring(0, dotpos + 3); // `.'+ 2 digits
else return numString + "0"; // Assume only 1 fraction digit
}
Mortgage Applet (3)
public void init()
{ balField = new TextField("", 15);
intField = new TextField("", 5);
nyrField = new TextField("", 5);
OK = new Button("Compute");
msgArea = new TextArea("", 15, 60);
msgArea.setEditable(false);
add(new Label("Enter principal"));
add(balField);
add(new Label("Enter annual interest rate"));
add(intField);
add(new Label("Enter number of years"));
add(nyrField);
add(OK);
add(msgArea);
}
Mortgage Applet (4)
public boolean action(Event evt, Object arg)
{ if (evt.target == OK) {
this.update();
return true;
}
else return false;
}
Mortgage Applet (5)
void update()
{ String balString = balField.getText();
String intString = intField.getText();
String nyrString = nyrField.getText();
if (balString.trim().length() == 0)
msgArea.setText("Principal amount missing");
else if (intString.trim().length() == 0)
msgArea.setText("Interest rate missing");
else if (nyrString.trim().length() == 0)
msgArea.setText("Number of years missing");
else {
double bal = new Double(balString).doubleValue();
double intyr = new Double(intString).doubleValue() / 100.;
short nyears = (short) new Integer(nyrString).intValue();
Mortgage Applet (6)
StringBuffer msg = new StringBuffer();
msg.append("\nprincipal=" + bal + " interest=" + intyr
+ " years=" + nyears + "\n");
double intmo = intyr / 12.;
int npmts = nyears * 12;
double pmt = bal * (intmo / (1.- Math.pow(1.+ intmo,-npmts)));
msg.append("payment\ttotal\tinterest\tprincipal\tbalance\n");
msg.append("number\tpayment\tpayment\tpayment\n");
msg.append("\t\t\t\t" + bal + "\n");
Mortgage Applet (7)
for (short mo = 1; mo <= npmts; ++mo) {
double prinpmt, intpmt = bal * intmo;
if (mo < npmts)
prinpmt = pmt - intpmt;
else prinpmt = bal;
bal -= prinpmt;
msg.append(mo + "\t" + format(intpmt + prinpmt)
+ "\t" + format(intpmt)
+ "\t" + format(prinpmt)
+ "\t" + format(bal) + "\n");
}
msgArea.setText(msg.toString());
}
}
}
Running Mortgage Applet
<HTML>
<HEAD>
<TITLE> Mortgage Calculator
</HEAD>
<BODY>
<APPLET code="MortgageApp.class" WIDTH=500 HEIGHT=300>
If you see this text, it means that you are not running a Java-capable browser.
</APPLET>
</BODY>
</HTML>
Mortgage Applet - Initial Window
Mortgage Applet - One Field Entered
Mortgage Applet - Fields Completed
Notes on Mortgage Applet
- The
init
method lays out the initial contents of the
screen
- Three Labels associated with three TextFields
- Correspond to input prompts in application version
- Place for the user to enter (hopefully) numeric data
- Button (labelled "Compute") to signal that the fields have been
filled in
- Program could also respond to the event of each field being filled in
- Complete application when numeric data in all three fields detected
action
method determines if the "Compute" button
was pushed
- Uses
update
method to perform actual computation
- Screen display is automatically updated to reflect the contents of the
message area (msg)
- update method performs some computations as the main method in application
version
- Checks for all fields being filled in
- Performs the actual mortgage calculations
- Output into scrolled window, so any number of months may be displayed