Java for C++ Programmers
History/Motivation
Code
Compilation and Execution
Program
Structure
Class
Libraries and Package
Java
Basics and Arithmetic
Basic
Input/Output
Keyboard input
Formatting output
Flow
of control/Equality
User-Defined
Classes
Reference
Objects
Static
variables and Methods
Arrays
Strings,
characters and StringTokenizer
Inheritance
Packages
Polymorphism
Interfaces
Abstract
Class
Exceptions
Classpath
Variable
Serialization
Applets
History/Motivation
- Developed early 1990s at Sun Microsystems
- First language to directly embrace programs for the Web
- Applications must have a main method
where processing begins
- This main method must be public,
static (no object
required) and void
Code compilation and execution
- Java compiler translates source code into Java bytecode
- Java interpreter (Java Virtual Machine/JVM) reads Java bytecode
and executes it on a specific machine. Java bytecode is
architecture neutral. Requires interpreter (or bytecode compiler)
to be on machine.
- Interpretation of bytecode is more efficient than direct
execution of source code, and bytecode is smaller, so file transfers
are faster.
- A bytecode compiler can translate bytecode into particular
machine language for more efficient execution.
- Java Development Kit (JDK) contains compiler, interpreter and
other tools. Available from java.sun.com.
- Java 2 Platform: collection of Java language features, software
libraries and tools. Three major groups: Standard Edition (J2SE),
Enterprise Edition (J2EE) and Micro Edition (J2ME).
- Our text includes the J2EE
- Java 2 Platform includes Swing, a graphics library that builds on
the earlier Abstract Windowing Toolkit (AWT) and extends its
capabilities.
Compilation
- Java files MUST have the same name as the class, with extension
.java
- To execute the Java compiler, type javac <filename>.java
- Result is placed in <filename>.class
- To execute the program (interpreted), type java <filename>
Program Structure
- As in C++, classes contain data (variables and/or constants) and
methods.
- Entire program is part of a class (unlike C++, which has a main
function that is not associated with an object)
- Program starts execution with main
routine, which must be a member function. Because no object will
have been instantiated, must declare main to be static. Main is also declared
as public and void, with one argument which represents any command-line
parameters (we'll typically ignore).
- Java does not use prototypes; the function definitions are
included inside the class definition.
- Java allows multiple class definitions to be stored in one file,
but only one of those classes can be declared public, and the name of
the file must correspond to the name of the public class. Common
to put each class in its own file.
- As in C++, methods have return types (includes void), parameters,
local data, and can be overloaded.
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello World");
}
}
Class libraries and packages
- Libraries are technically not part of the language definition.
- A class library is made up of clusters of related classes,
sometimes called Java APIs (Application Program Interface).
Examples: Java Database API, Java Swing API. Entire library may
be referred to as Java API.
- Classes of Java standard class library are grouped into packages which group related
classes under one name. There is a general correspondence between
package and API, but package organization is more fundamental and
language-based. Classes that make up a given API might cross
packages.
- Examples of packages: java.applet, java.awt, java.beans, java.io,
java.lang (automatically imported), java.math, java.net, java.rmi,
java.security, java.sql, java.text, java.util, java.swing,
java.xml.parsers.
- To use classes other than java.lang, must either fully qualify
the reference or use an import declaration.
- Example of fully qualified: java.util.Random to access Random
class in java.util.
- May be easier to do: import java.util.Random;
- Or to use all classes in package: import java.util.*;
- Common to use * if two or more classes are used.
Java Basics and
Arithmetic
- Primitive data include numbers and characters.
- Java has Boolean type with values true and false.
Does not automatically
convert integer values to Boolean.
- Java is strongly typed (cannot assign a value that is
inconsistent with the declared type).
- Variable declarations and assignment are similar to C++
- Use final rather than const for constants.
- Perform operations using operators built into language: +, -, *,
/, %
- Arithmetic expressions and precedence similar to C++
- Sometimes values of one type must be converted to another type
(same as C++)
- Widening conversions are safest. Go from one data type
to another that uses an equal or greater amount of space.
Examples: byte to short, int, long, float or double; float to double.
- Narrowing conversions transfer to a data type with less
space. Should generally be avoided.
- Conversions occur due to assignment conversion, arithmetic
promotion and casting.
- Typecasting can be used, just as in C++
- System.out refers to the monitor.
- The print method (of
System.out) is used to display data, println
used to display data followed by a newline.
- Java recognizes escape sequences \t \n \” \’ \\
\b(backspace) and \r(carriage return)
BasicArithmetic.java
Basic Input/Ouput
Keyboard input
- Uses Scanner class (requires java.util.Scanner)
- System.In is associated with the keyboard device. Must create new
Scanner object associated with keyboard.
- Scanner class has variety of methods to read various types of
data, such as nextDouble, nextInt etc. and some methods (not covered
here) such as hasNext which can be used to determine whether the input
stream contains more data.
Formatting output
- Two classes, NumberFormat and DecimalFormat, are used to format
information. Must import from java.text.
- Don’t instantiate NumberFormat with new. Request an object
from methods invoked through the class. For example, NumberFormat
class methods getCurrencyInstance and getPercentInstance return
objects. The format method can then be used with those objects to
return a formatted String.
- DecimalFormat is instantiated using new. The constructor takes a
string that represents the pattern that guides the formatting process
(example in later program).
- The format method is then used to format a particular value.
NOTE: Prior to Java 1.5, programs used a BufferedReader to do
I/O. The BufferedReader class is no longer covered in these
notes.
SalesTax.java
Flow of control
- Flow of control and arithmetic similar to C++: if, if-else,
nested if, switch, ++, --, +=, while, do-while, for
- Blocks of code surrounded by braces
- Use !, && and || for not, and and or.
- Same conditional operator as in C++: int larger = (num1 >
num2) ? num1 : num2.
- Break and continue can be used in loops, but should generally be
avoided.
Equality tests
- Do not use equality or relational operators to compare String
objects. The equals
method returns true if two strings contain the same characters, false
otherwise.
- The test (name1 == name2) tests whether both reference variables
refer to the same String object.
- To determine relative ordering, use compareTo method (similar to
strcmp).
- For floats, == is true only if all bits match. Better to
subtract and compare the result to some tolerance. This is also
true in C++.
Comparison.java
User-Defined
Classes
- Variables declared inside class are local to that class.
Called instance data.
- Java automatically initializes any variables declared at the
class level (i.e., not inside a member function). Still good to
initialize explicitly.
Visibility
- Visibility modifiers control access to the members of a
class. Instance data should be declared with private visibility. Service
methods should be declared as public,
while support methods are intended for use only within the
class and should be private.
- Java also supports protected
access to give access to subclasses.
- Default access (no access specification) allows classes within
the same package to access each other's members (packages covered
later).
Constructors, Accessors and Mutators
- Syntax and usage of constructors, accessors (getters) and
mutators (setters) similar to C++.
- Can use keyword this to
call constructor (C++ has keyword this, but it's not used to call
constructors; initialization lists are used).
Methods
- Cannot overload operators
- Can overload other methods. Binding is based on number/type
of
parameters, can't be based on return type (just as in C++).
- Use object plus dot operator in method call.
Methods Inherited from Object
- When an object is used as an operand of the string concatenation
operator, or is sent to a print or println method, that object’s toString method is called. If
no toString method is defined, a default string will be created that
contains the name of the class and some other data. Normally it’s
a good idea to define toString.
- It's also good to override the equals
method, to allow for checking equality.
Time.java
and TimeTest.java
Reference Objects
- When you use the dot operator to invoke an object’s methods, you
are actually using the address in the reference variable. In C++,
would do ptr->method().
- A reference variable that does not point to an object is a null
reference. If you try to follow a null reference, a
NullPointerException is thrown.
- The compiler will complain if you try to use a reference object
which has not been initialized.
public class PassByValue {
public static void One(Point v) {
v = new Point(0, 0);
}
public static void Two(Point v) {
v.setX(5);
}
public static void main(String[] args) {
Point p = new Point(10, 10);
System.out.println("Original point: " + p);
One(p);
System.out.println("Point after one: " + p);
Two(p);
System.out.println("Point after two: " + p);
}
}
Exercise
Create a class named Person
which has two fields, a String
called name and an integer called age. Include a default
constructor, a 2-parameter constructor, accessors, modifiers, a toString and an equals method.
Create a second class named People
which contains only the main
function. Create several Person
objects and use the toString, equals, == and other methods to get a basic
understanding of using classes in Java.
Static variables
and methods
- Static variables, also
known as class variables, are
shared among all instances of a class. Declared as: private
static int count = 0;
- Can also declare as constants (final).
public class Logins {
static private int numLogins = 0;
// constructor just updates static counter
public Logins() {
++numLogins; // another login has been performed
}
public static void main(String[] args) {
Login l1 = new Login();
Login l2 = new Login();
Login l3 = new Login();
System.out.println("Number of logins: " + Login.numLogins);
}
}
- Static methods are also
known as class methods.
- The main method of a Java program must be static, so the
interpreter can execute it without instantiating an object.
- Static methods cannot reference instance variables, because there
is no instance.
- A static method can access static variables and local variables.
- Main can only call methods which are static, unless it has an
instance of the class.
- Math class provides function which have no state, so there’s no
need to instantiate an object.
- Invoked as: Math.pow(7, 4);
Conversion.java
Arrays
- As in C++, an array is a collection of values of the same type
(primitive or objects), with indices ranging from 0 to size-1.
- Always declared using new:
int[] heights = new int[11];
- Once an array is declared to be a certain size, the number of
values it holds cannot be changed.
- The [] is an operator with the highest precedence of all
operators. Unlike C++, the [] operator performs
automatic bounds checking. If the index is not
valid, an ArrayIndexOutOfBoundsException is thrown.
- The size of the array is stored in a constant named length,
which is public and can be accessed directly, such as heights.length.
- Can use an initializer list instead of new: int scores[] = {100,
90, 85};
- When an array is passed as a parameter, a copy of the reference
to the original array is passed. Allows changes to
be made (as in C++).
- Formal parameter to main is an array of String objects that
represent the command-line arguments to the program. An
ArrayIndexOutOfBoundsException will be thrown if access args that are
not provided.
Person.java
and Friends.java
and TripPlanner.java
Strings and
Characters
- String class is part of Java standard class library that can be
found in any development environment.
- Java is based on 16-bit Unicode character set. Compatible
with ASCII for 0-255, but extends with characters/symbols from many
languages.
- Character strings are defined by class String. Can
use + to concatenate strings,
including concatenating strings with numbers and/or variables.
- Can also have string literals. This is a shortcut; whenever
a string literal appears, a String object is created.
- Once a String object is created, its value cannot be lengthened,
shortened, nor can any of its characters change. String objects
are immutable. String methods do exist to return new String
object that is result of modifying original String’s value, such as
replace (character replacement), substring, toLowerCase and
toUpperCase.
- Functions provided for String objects include:
- length() which returns the number of characters
in the string,
- append (+=) which adds characters to the end of a
string,
- charAt(n) which returns the value of the chracter at
position n,
- subtring(start,end) which returns a new string
consisting of the characters between positions start and end-1 of the
original string. If end is omitted, the substring extends to the
end of the string.
- trim() which creates a new string that excludes any
leading and trailing whitespace
- indexOf(substring, start) which returns the
starting position of the first occurence of substring after the
specified start character, or -1 if the substring is not found.
- lastIndexOf(substring, end) which is similar to
indexOf, but it searches for the substring starting from the end of the
String.
- For the functions related to a position, the first character
of the string is assumed to be position 0 (NOT position 1). The
last position is length() - 1.
- The String class also provides methods to convert other data
types to a string. These methods are called valueOf(),
and take one parameter.
StringTokenizer
The StringTokenizer class
is useful for parsing a
string into individual words.
// Sample String
String s = "I am learning Java. Show me how to use
StringTokenizer.";
// StringTokenizer, pass string into constructor
// Could pass delimiter as second parameter, if
other than \t\n\r, delimiters discarded
StringTokenizer st = new StringTokenizer(s);
// Retrieve and display tokens
System.out.println("The total number of words is "
+ st.countTokens());
// Use the StringToken iterators hasMoreTokens to
see if more words
while (st.hasMoreTokens())
System.out.println(st.nextToken()); // nextToken will get the
next word
System.out.println("Any tokens left? " +
st.countTokens());
Inheritance
- Java supports is-a relationships via inheritance, indicated with
keyword extends:
public class Student extends Person;
- As in C++, the child class inherits public variables and methods
of the parent class. Data with private visibility cannot be accessed
directly, only via methods of the parent class.
- Variables and methods declared with protected visibility
can be accessed directly.
- Constructors are not inherited in a derived class, because it
wouldn’t make sense for a derived class to have a constructor with the
name of the parent class.
- The reserved word super can be used in a class to refer
to its parent class. One use is to
invoke the parent’s constructor. Using super to
invoke a parent’s constructor can be done only in a child’s
constructor, and if included must be the first line of the constructor.
Java will automatically make a call to super() to initialize
the base class if it’s not in the code.
- Java supports only single inheritance, but a class can
implement many different interfaces (covered below).
- A child class can override a parent’s method.
To call the parent class method of the same name, use the super keyword. Example: if
you are overriding a method named doSomething you would call the parent
class method as super.doSomething(). (compare to C++, where
you would use the name of the parent class and scope resolution
operator).
- A class cannot override a method defined with the final
modifier. This technique is used when the parent
class needs to ensure that a particular definition of a function is
used.
- A child class can declare a variable with the same name as one
inherited from the parent. This is called shadowing
and is not recommended.
- Inheritance relationships often develop into class
hierarchies. There is no limit to the number of children a class
can have or to the number of levels to which a class hierarchy can
extend.
- All classes are derived ultimately from the Object class.
Any public method of Object can therefore be invoked through
any object. Object is defined in java.lang.
- Methods of Object include equals, toString and clone.
Default definition of toString returns the class name
followed by a unique numeric value. The default for
equals returns true if two object references refer to the same object
(aliases).
Account.java,
SavingsAccount.java
and AccountDemo.java
Polymorphism
Polymorphism (having many forms)
- A polymorphic reference is a reference variable that can
refer to different types of objects at different points in time.
The specific method invoked through a polymorphic reference
can change from one invocation to the next.
- As in C++, the commitment to execute certain code is referred to
as binding a method invocation to a method definition.
In most situations this binding can occur at compile time.
For polymorphic references, the decision cannot be made
until run time. This is called late binding or
dynamic binding. It is less efficient,
but overhead is generally acceptable to obtain flexibility.
- A polymorphic reference can be created in two ways: using
inheritance and using interfaces.
- A reference that is declared to refer to an object of a
particular class can also be used to refer to an object of any class
related to it by inheritance.
- Example: assume a class Mammal is used to derive a class Horse.
Mammal pet;
Horse secretariat = new Horse();
pet = secretariat;
- An Object reference can be used to refer to any type of object
(because Object is the superclass of all other objects).
- If Mammal were derived from Animal, could also say: Animal
creature = new Horse();
- If all three classes have a move() method, the version used for
creature.move() would be determined at run time. If
creature still contained a Horse (i.e., the last allocation was the
above line of code), then it would call the move() method associated
with Horse.
- The base class Animal could be abstract (covered below).
Exercise
Extend your Person
class to be a Student with
additional field of type double
called GPA. Include
accessor and mutator for your new field. Override toString and equals for your new class.
Write a new driver file to create an array of Person objects. Write a loop
to accept 5 people. Each time through the loop, ask it the person
is a student. If so, add a Student object to the array, otherwise
add a Person object to the array. Accept the appropriate
information, based on the type. Then include another loop to
print out the information in your array.
Interfaces
- Powerful feature that facilitates interoperability.
- A Java interface is a collection of constants and
abstract methods.
- An abstract method does not have an implementation. The
header is simply followed by a semicolon, no body of code (similar to
=0 in C++). All methods in an interface must be abstract.
- An interface cannot be instantiated.
- An abstract method can be preceded by keyword abstract,
although in interfaces it generally is not.
- A class implements an interface by providing method
implementations for each abstract method. It uses the
keyword implements followed by the interface name in the class
header. The compiler will produce errors if any of the methods in
the interface are not given a definition in the class. Methods
from the interface must have the same signature.
- A class that implements an interface can provide additional
methods.
- More than one class can implement an interface. For
example, two different buttons in a program might each implement the
ActionListener interface. ArrayList and LinkedList both implement
the List interface.
- One class can implement more than one interface: class ManyThings
implements interface1, interface2, interface3 { … }. For example,
the Point class could implement the Comparable interface (described
below) as well as the Shape interface.
- The interface provides an alternative to C++ multiple
inheritance. A class can extend one class then implement several
interfaces.
- Java standard class library contains interfaces as well as
classes. Java interfaces have their own hierarchy which is
separate from the class hierarchy. That means a class cannot be
used to derive an interface, and an interface cannot be used to derive
a class.
- An interface name can be used as the type of a reference variable.
Such a variable can be used to refer to any object of any
class that implements that interface.
- Example (from Lewis & Loftus):
public interface Speaker
{
public
void Speak();
public
void announce (String str);
}
If Philosopher and
Dog both implement Speaker, can do:
Speaker guest;
guest = new Philosopher();
guest.speak();
guest = new Dog();
guest.speak();
- When using an interface reference variable, you can invoke only
the methods defined in the interface, even if the object it refers to
has other methods defined. Can use an explicit cast
if you know the type of the object: ((philosopher)
guest).pontificate();
- An interface name can be used as the type of a method parameter.
- The Comparable interface in java.lang contains just the compareTo
method. The intent is to provide a common mechanism for
comparing one object to another.
- The Iterator interface provides a means to move through a
collection of objects. Two methods are hasNext
which returns a boolean and next which returns a
reference. Also contains a remove method.
Shape.java
and Point.java
and
InterfaceTest.java
Abstract
Classes
- An abstract class represents a generic concept in a class
hierarchy. An abstract class cannot be
instantiated, and usually contains one or more abstract methods, which
have no definition.
- Since abstract classes must be extended before they can be
instantiated, they are sometimes referred to as abstract superclass.
Classes that can be used to instantiate objects are sometimes
called concrete classes.
- Unlike an interface, an abstract class can contain
methods that are not abstract, and can have data declarations other
than constants. Since constructors are not inherited, they cannot
be declared abstract.
- Although abstract classes cannot be instantiated, it is possible
to declare variables that can hold references to any concrete objects
derived from that abstract class, and abstract superclass names can be
used to invoke static methods declared in those superclasses.
- To make a class abstract, put the keyword abstract in the
class header. Any class that contains one or more
abstract methods must be declared as abstract. A
class can be declared as abstract, even if it has no abstract methods.
- Example: might have a vehicle abstract class, with car,
boat, truck etc. as descendants.
- Usually abstract classes are located at the upper levels of a
class hierarchy, but it is possible to derive an abstract class from a
nonabstract parent.
- If a child does not provide a definition for every abstract
method it inherits, it too is considered abstract.
- Abstract methods cannot be declared as final or static (wouldn’t
make sense).
- Example usage: Could have an abstract Employee class, which is
extended to SalariedEmployee and HourlyEmployee.
Nested classes
- A class can be declared inside another class (nested).
NOTE: This means inside the class definition, not just within the
same file.
- Nested class produces a separate bytecode file. Name is
<Enclosing>$<Nested>.class.
- Nested class has access to enclosing class’s instance variables
and methods, even if they are private.
- The enclosing class can only access the nested class’s public
variables. The nested class’s public variables are private
outside of the enclosing class.
- The static modifier can
be applied to a nested class.
- A non-static nested class is called an inner class. An instance of an
inner class can only exist within an instance of the enclosing
class. Therefore, methods of the inner class cannot be declared
static.
Outer.java and TestOuter.java
Collections
- Collections framework contains prepackaged data
structures, interfaces and algorithms for manipulating those data
structures (similar in some respects to STL)
- Included in package java.util.
- Collections use existing data structures with no concern as to
how those data structures are implemented.
- Collections are designed for reuse and coded efficiently.
- A collection is an object that can hold references to
other objects.
- A collection interface declares the operations that a
program can perform on each type of collection. The interface Collection
is the root interface in the collections hierarchy. Interfaces Set
and List are derived from Collection.
- Interfaces include: Collection, Set, List and Map.
- The class Arrays provides static methods to manipulate
primitive-type and Object arrays. Some methods include: sort,
binarySearch, equals and fill.
- A List is an ordered Collection that can contain
duplicate elements. List indices are zero-based, and methods are
provided for manipulating elements via their indices. Classes
that implement List include ArrayList, LinkedList, and Vector.
- A Set is a collection that does not contain duplicates.
- A Map associates keys to values and cannot contain
duplicate keys.
ArrayTest.java
File I/O
- Common task: tokenizing a string (extracting parts of a string,
based on a delimiting character). StringTokenizer class from
java.util separates a string into tokens. Default delimiters are
space, tab, carriage return and newline. Methods include the
constructors (with and without specified delimiters), countTokens,
hasMoreTokens, and nextToken.
Anonymous Inner Classes
Basic Input and Output in Java 1.5
Keyboard input
Formatting output
- The printf method can be
used to format output.
- The first parameter is a format
string that specifies how the second parameter should be
printed.
- System.out.printf("%4i", num); // prints variable num as integer
using 4 characters
- System.out.printf('"%6d", value); // prints variable value as
decimal using 6 characters
Exceptions
Abnormal events in a program, such as running past the end of an array
or invalid characters encountered during an I/O operation, generate an
event known as an exception.
The run-time system throws an
exception based on the type of error (e.g., Null pointer exception, IO
Exception, etc.). The program will either catch and handle the exception or terminate
with an error.
Java requires that some potential errors must either be handled
explicitly OR acknowledged via a throws expression. In the first
IO program below, the programmer has decided not to handle IO
errors. Notice the throws IOException clause at the end of the
the main method. If an error occurs during input (e.g., the user
enters an invalid character), the program will abort). Also, the
throws clause is required for the creation of fileScan. In the second
IO program, the IO statement is embedded in a try-catch clause.
The Java runtime will "try" the statement, and if an IO error occurs,
the catch clause will take over and handle it, so the program will not
need to abort.
Some exceptions must be caught (e.g., the fileScan statement in program
one). These are known as checked
exceptions. Others do not need to be caught (e.g., the
scan.nextInt statement in program one). These are known as unchecked exceptions. Runtime
exceptions such as divide by zero are generally unchecked, because the
cost of implementing handlers for them could be too high.
import java.io.*;
import java.util.Scanner;
public class IOThrows {
public static void main(String[] args) throws
IOException
{
Scanner scan = new
Scanner(System.in);
System.out.println("Enter an
integer: ");
scan.nextInt(); // unchecked
// requires throws clause or
FileNotFound must be handled.
Scanner fileScan = new Scanner(
new File("myfile.txt"));
}
}
import java.io.*;
import java.util.Scanner;
public class IOTryCatch {
public static void main(String[] args)
{
Scanner scan = new
Scanner(System.in);
System.out.print("Enter an
integer: ");
try
{
scan.nextInt();
}
catch
(java.util.InputMismatchException e)
{
System.err.println("Error in input, shame on you!");
}
}
}
Serialization
Serialization allows you to take the state of a Java object and
write it in binary form to an output stream. A second program can
then create a new object with an equivalent state.
The Java java.io.Serializable interface is used to enable you
to save the state of a class. Serialization relies on class
metadata and reflection to extract the state of an
instance. Data are written to the output stream in binary format.
A serial number is assigned to each object. If the same object is
written to the output file more than once, only the serial number is
written.
public class Contact implements java.io.Serializable {
String name;
String email;
public Contact() {
name = "";
email = "";
}
public Contact(String name, String email) {
this.name = name;
this.email = email;
}
public String toString() {
return "Name: " + name + " Email:
" + email;
}
}
import java.io.*;
public class IOWriteDemo {
public static void main(String[] args) {
try {
// Specify the
file where you'll store the data
FileOutputStream fos = new FileOutputStream("datafile");
// Create an
ObjectOutputStream
ObjectOutputStream oos = new ObjectOutputStream(fos);
Contact
contact = new Contact("Cyndi Rader", "crader@mines.edu");
// Serialize
the object
oos.writeObject(contact);
}
catch (IOException e)
{
System.out.println("Problem with file output");
}
}
}
import java.io.*;
public class IOReadDemo {
public static void main(String[] args) {
try {
// Specify the
file where you'll find the data
FileInputStream fis = new FileInputStream("datafile");
// Create an
ObjectInputStream
ObjectInputStream ois = new ObjectInputStream(fis);
Object o =
ois.readObject();
System.out.println(o);
}
catch (IOException e)
{
System.out.println("Problem with file input");
}
catch (ClassNotFoundException e)
{
System.out.println("Problem with file input");
}
}
}
Applets
- A Java applet is a Java program that is intended to be
embedded into an HTML document.
- This was the first kind of executable program that could be
retrieved using Web software.
- The appletviewer program can be used to execute applets
without a browser.
- Java bytecode (not source code) is linked to an HTML document and
can be sent across the Web. A version of the Java interpreter
embedded in a Web browser is used to execute the applet.
- Applets do not have a main method, because they are embedded in
an application that is already running.
- The paint method is invoked automatically instead.
This method is also called whenever the window needs to be refreshed.
- A class that defines an applet extends the Applet (or JApplet)
class from the java.applet package. To use swing components, you
must extend JApplet.
- Applet classes must be declared as public.
- Example applet tag: <applet code=”Einstein.class” width=350
height=175></applet>
Applet methods
- public void init() initializes, is called just after applet is
loaded. Common functions are to load images, create threads, get
parameters.
- public void start() is called just after the applet is made
active (e.g., when return to page). Might be used, for example, to
restart an animation.
- public void stop() is called when applet is made inactive (e.g.,
when leave page). Might be used, for example, to suspend a thread
so system resources aren't used when an applet is inactive.
- public void destroy() is called when the browser is exited
- public URL getCodeBase() returns the URL at which this applet’s
bytecode is located
- public URL getDocumentBase() returns the URL at which the HTML
document containing this applet is located
- public AudioClip(URL url, String name) retrieves an audio clip.
- public Image getImage(URL url, String name) retrieves an image
- In a browser, use SHIFT+Reload to force applet to reload.
Applets and Components
- JApplet and JFrame are both subclasses of Container. User
interface components, event-handling and layout managers are therefore
the same in applets and applications.
- JApplet class has a content pane to which GUI components are
added.
- JApplet components should not be drawn on directly. It’s
better to draw on a panel and add that panel to the applet, especially
if there’s user interaction.
- JApplet provides the ability to interact with a browser and
accept parameters through HTML code. It is
constrained by certain security limitations.
Applets and Security
- To prevent damage to files and the spread of viruses, applets
cannot read from or write to the file system of the computer.
- Applets cannot run programs on the browser's computer (so they
can't run a destructive program).
- Applets can't establish connections with other computers except
the server where the applet is stored.
- In Java 2, a security policy file can be used to grant applets
access to local files.
Packages
To create your own package, put a package statement at the top of your
program:
package edu.crader.mypackage
A common practice is to use your domain name in reverse, with a unique
ending to match the purpose of the package.
To compile the source code and have the compiler create the appropriate
directory structure, use the -d . switch:
javac -d . myProgram.java
This will create the directory structure edu/crader/mypackage starting
from the current directory (the . in the command).
To run the program, you must specify the complete pathname:
java edu/crader/mypackage/myProgram
Classpath
The classpath tells Java where to search for a package or class.
CLASSPATH is not a Java variable, it is an operating system
variable. Therefore, the way the CLASSPATH variable is set is
operating system dependent. Some examples:
Unix:
set CLASSPATH=/libraries/java;.
export CLASSPATH
XP:
Control Panel->System->Advanced->Environment Variables
Edit or Add Classpath
Note the . at the end of the classpath. This is needed so that
your classpath includes the current directory.
You can override the CLASSPATH setting when you compile or run a
program by using the -classpath switch on the command line, such as:
java -classpath . myProgram
which tells the java interpreter to run myProgram from the current
directory.