.Open The Java Programming Language
.As_is http://www.csci.csusb.edu/dick/samples/java.html
This page is designed to be a step by step introduction to Java
for a competent C++ programmer. Getting your first Java
programs to run is unusually hard because
.Net
Names of files
have to precisely match the identifiers used inside the files.
Names of classes in Applets must match the names of classes in Java.
It is hard to keep all these names in synchronization as the code develops.
Some books do not follow the newer scoping rules.
.Close.Net
Beginners can work through the
.See Overview
section below to make this process less painful.
This page also has many links to more in depth information about Java.
.Open Overview
$Java is designed to be a completely object-oriented programming language
used in consumer appliances like VCRs and toasters.
It is based on the first version of C++ but explicitly leaves out
features of C and C++ that are confusing or unreliable.
It has
inheritance and dynamic polymorphism but not generics and/or templates.
It is designed with concurrent programming in mind. It has
most of the expressions and control structures of C plus $exceptions
but without the "go to". So a C++ programer finds Java programs easy to read
but verbose. It is slightly more work to write, but the result
is nearly always clearer than the abbreviated C++ code.
Java is
compiled into a special machine code that is then interpreted.
Java code does not perform as fast as C++. The interpreter
however protects the machine on which it is running from errors
that can break operating systems in C++. Furhter the same
(compiled) code can run on many different systems: Compile-Once-Run-Anywhere.
So a Java program can be transmitted across a network to
a machine of a different type, with a different operating system,
and different graphic user interface. There it will run safely and
securely (in theory) and look-and-feel as if it was programmed for
that system. Doing this with C++ is extremely expensive.
$Java can be used to write `applications` and `applets`. A $Java
$application is similar to any other high-level language program:
It can only be compiled and then run on the same machine.
An $applet is compiled on one machine, stored on a server in
binary, and can be sent to a another machine over the Internet
to be interpretted by a Java-aware browser.
Java comes with a large library of ready made classes and objects.
The key difference betwen Java 1.0 and 1.1 was in this library. - the $AWT.
Similarly, Java 2.0 has a very much larger library for handling user
interfaces (Swing by name) but only small changes to the core of the language.
.Open Applications
An application is compiled (using $javac) and run like any other program
but it is actually a Java $class that contains a special method called
'main'.
When the interpreter ($java)
is called with the name of the $class,
it looks for the `public static main(String[])` $function in the $class and
calls it.
. Example Application
The following is based on the old traditional C program that prints
"Hello, World" on the computer screen:
(Hello):
.Box
.As_is import java.lang.*;
.As_is public class Hello {
.As_is public static void main(String argv[]){
.As_is System.out.println("Hello, World!");
.As_is }
.As_is }
.Close.Box
The above is best put in a file called `Hello.java`
.See http://ftp.csci.csusb.edu/public/faculty/dick/Hello.java
and then compiled with 'javac Hello.java' and then run: 'java Hello'.
The `import` statement in a Java file allow it to refer
to other classes in other files and directories. The compiler uses these
other classes's definitions to check your code, and the interpreter
loads the binary bytecode into the running program.
The word $public means that the thing following it can
be accessed by anyone. A public class can be imported over
the internet into any other class and so can be sent to a browser.
A public function can be called by statements and expressions in
different classes.
$static indicates that a function
or object belongs to the $class rather than to each individual
$object in the $class. The function is called like this 'Hello.main(...)'
even when there are no objects constructed in class Hello.
Notice that Java code was designed to be interpreted by a
machine independent `virtual` machine ($JVM) that runs
a special machine code called $bytecode.
.Close Applications
. Tools
The $Hello application would be compiled like this:
.As_is javac Hello.java
and run by the java interpreter like this:
.As_is java Hello
Notice that the `file` "Hello.java" is compiled, but a `$class` is
interpreted.
One nice feature of the Sun $JDK is the documentation tool $javadoc.
The above application $Hello has the following documentation:
.See http://ftp.csci.csusb.edu/public/faculty/dick/Hello.html
which was generated by $javadoc.
$javadoc scans source code files (*.java) and creates one HTML
file per $class in the files. Classes and parts of classes can have
special documentary comments (starting "/**" ) added to them that are
reformatted and incorporated into the Hypertext produced by `javadoc`.
This should be a boon for realistic projects. The full syntax
of the special comments can be found at
.See http://www/dick/samples/java.syntax.html#Doc_Comment
on this web site.
The `javap` program disassembles bytecode (*.class files)
and outputs a description of the what is in them.
.Open Applets
An `Applet`
is a small program that can be sent across the Internet and
interpreted on a client machine. To give permission for remote
access it must be a $public $class. Typically it is a
class that inherits and/or defines a special set of functions
needed to run an $applet. These are part of the $class $Applet.
So all Java applets are $public classes that
$extend $Applet.
You can not run a Java applet unless it is
also an application or you have
a WWW page that refers to it.
The page needs HTML
like the following to call the compiled code, in the same
directory:
.As_is
where `h` and `w` are the HEIGHT and WIDTH of the
box in which the applet outputs its response. The `alternate text`
appears when a browser can not handle APPLETs. For the general syntax see
$applet_in_html.
The code in "ClassName.class" above,
is the result of compiling a file called "ClassName.java"
that contains a $public $class called `ClassName` which $extends an $Applet.
(For details on HTML see
.See http://www/dick/doc/www.html
written in the HyperText Markup Language(HTML)
.See http://www/dick/samples/comp.html.syntax.html.
)
. Example
Here is a suitable piece of HTML to test a simple $HelloWorld class:
.As_is
Test
.As_is
.As_is
Put this in a file called:
.As_is test.HelloWorld.html
The code for the $HelloWorld applet has to be a $public $class
called "HelloWorld" that extends $Applet and is in
in a Java file called:
.As_is HelloWorld.java
Here is the Java code:
(HelloWorld):
.Box
.As_is import java.applet.*;
.As_is import java.awt.*;
.As_is public class HelloWorld extends Applet {
.As_is public void init() {
.As_is resize(150,25);
.As_is }//init
.As_is public void paint(Graphics g) {
.As_is g.setFont(new Font("Helvetica", Font.PLAIN, 8));
.As_is g.drawString("Hello world!", 50, 25);
.As_is }//paint
.As_is }//HelloWorld
.Close.Box
The Applet is compiled just like any other program:
.As_is javac HelloWorld.java
This will generate a set of files with extension/suffix ".class".
Notice that the compiler forces you to name the file
"HelloWorld.java", the Class "HelloWorld", and generates the binary $bytecode in a file called "HelloWorld.class".
Sun has written a special program to test applets in page:
.As_is appletviewer test.HelloWorld.html
However you can not use 'java' to run the $HelloWorld $class - it has no 'main'.
Neither can 'java' "run" the WWW pages like the `test.HelloWorld.html` file.
On the Suns in the Sun lab you can tell 'Netscape' to "Open local File..."
and select
.As_is test.HelloWorld.html
but using the older Netscape to debug an applet has some $problems indicated later.
. Public Classes and Pages
The moment a .class file or a package becomes public
on the web, other Java classes, anywhere on the web, can "import"
your public classes and use them to construct more classes!
Normally you should put
applet code (compiled and source) in the same directory as
the public page that refers to them. This is simple and works.
There are more complicated ways of organizing the files.
It is said that if the page is in directory with path name `D` on the server
and your operating system uses `S` to separate directories in path names
.As_is ( S.DOS=`\`, S.UNIX=`/`, S.Mac=`:`)
then the
applet code for $class `C` must be in directory `D``S`classes and have a name
`C`.class. However Netscape 2.01 for Suns looks in directory `D`, unless you
add the attribute `CODEBASE=classes` to the Applet tag.
There is also an interaction between `packages` and subdirectories
that goes beyong the basic knowledge covered here.
. Debugging Problems with Browsers
(problems):
.Set
You may have to change the options/properties of your browser
to be able to run Java. This is a security issue.
Your browser must trust the compiler you use. If it doesnot recognize
the compiler version (hidden in the compiled file) it may reject
the applet.
To be sure of a browser finding all the necessary $class
files they have to be in the same directory as the pages that refer to them.
You can not keep the $bytecode .class file private and the page public.
To put .class files in a subdirectory you may have to place them in
a $package with the same name as well.
If the Applet fails, use the Options menu to
open the Java Console... and look for errors.
The Older Netscape running in background does not make a good development tool
because it is hard to
make the program reload the code of Applets. You can change the code,
recompile it, publish all the files perfectly, `and` hit the reload
button in Netscape and it will not reload the new $bytecode. I've
wasted hours looking for bugs that I've fixed. Instead use Sun's
$appletviewer and/or debuggers. You can also include a main function in
applets that make them applications. See
.See Applications Can Run Applets
next.
If it is absolutely necessary to debug the applet inside an html page
then (1) use the Sun Appletviewer, (2) find a machine with Netscape 4.0
and use Shift+Reload, or (3) execute Netscape directly on
a local copy of the page and Exit from it before working on the applet code.
In vi you can use something like this:
.As_is :!java %
.As_is :!netscape test.page.name.html
to suspend the editor and run Netscape on the test page. Exit Netacape
and tap Return/Enter to continue editting.
On Orion, if you use `Q` to compile a program `Stuff`.java and
you have a readable file called test.`Stuff`.java then it will automagically
execute netscape for you. This is in Beta -- EMail `dick` if you
don't like it.
.Close.Set
. Applications Can Run Applets
The 'java' interpreter can run classes that have an appropriate 'main'
$function:
.As_is java classname
This special $method or $function
is called `main`. To run an applet it must create a window and run the
applet in it. The steps are:
.Box
Create a new window to display the applet.
Create a new object of the correct $class.
Tell the applet to initialize itself.
Tell the applet to start running.
Add the running applet into the window.
Resize the window.
Show the window to you.
.Close.Box
Please use the following sample as a model for your own testing:
(applet_test_harness):
.As_is private final static int SIZE = 300;//size of window
.As_is
.As_is public static void main(String args[]) {
.As_is
.As_is HelloWorld aHelloWorldObject = new HelloWorld();
.As_is //The aHelloWorld object exists
.As_is
.As_is aHelloWorldObject.init();
.As_is //aHelloWorld has now initialized it self
.As_is aHelloWorldObject.start();
.As_is //aHelloWorld has now started running
.As_is
.As_is Frame aWindow = new Frame("HelloWorld");
.As_is //A window called "HelloWorld" will hold the Applet
.As_is
.As_is aWindow.add("Center", aHelloWorldObject);
.As_is //aWindow now has aHelloWorld in it's center
.As_is aWindow.resize(SIZE, SIZE);
.As_is aWindow.show();
.As_is //aWindow is now shown to you (until you CTRL/C)
.As_is
.As_is }//main
You can download an uptodate working copy of the HelloWorld
$class which is both an applications and and applet from
.See http://ftp.csci.csusb.edu/public/faculty/dick/HelloWorld.java
Keep a copy of this and use it generate your own test programs for
applets.... before you put them on the Web!
I have just developed a new tool that will generate an HTML
test page for a new $applet and also a suitable *.java file ready
for the details to be filled in
It is in
.See http://ftp.csci.csusb.edu/public/faculty/dick/instantapplet
Please download and try out -- Beta Testing.
. Another Example
There is a more elaborate example of a Java applet/application program
in
.See http://ftp.csci.csusb.edu/public/faculty/dick/test.Goodbye.html
complete with links to the source code, documentation, and
byte code. It also shows how to control fonts and colors of text.
. Caveat
Here is a warning: The above main programs do not create a complete
environment created by a browser looking at an HTML page.
The Applet can not access the parameters that can be
encoded in the page. Neither can they find out about the
width and height encoded in the