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
This page also has many links to more in depth information about Java.
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.
Applications
import java.lang.*;
public class Hello {
public static void main(String argv[]){
System.out.println("Hello, World!");
}
}
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.
. . . . . . . . . ( end of section Applications) <<Contents | End>>
Tools
The Hello application would be compiled like this:
javac Hello.javaand run by the java interpreter like this:
java HelloNotice 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: [ 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 [ Doc_Comment in java.syntax ] on this web site.
The javap program disassembles bytecode (*.class files)
and outputs a description of the what is in them.
Applets
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:
<APPLET CODE="ClassName.class" HEIGHT=h WIDTH=w>
Alternate text
</APPLET>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 [ www.html ] written in the HyperText Markup Language(HTML) [ comp.html.syntax.html] . )
Example
Here is a suitable piece of HTML to test a simple HelloWorld class:
<head><title>Test</title></head><body>
<APPLET CODE="HelloWorld.class" HEIGHT=150 WIDTH=150>
You can not see this brilliant Java Applet.
</APPLET>
</body>Put this in a file called:
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:
HelloWorld.javaHere is the Java code:
import java.applet.*;
import java.awt.*;
public class HelloWorld extends Applet {
public void init() {
resize(150,25);
}//init
public void paint(Graphics g) {
g.setFont(new Font("Helvetica", Font.PLAIN, 8));
g.drawString("Hello world!", 50, 25);
}//paint
}//HelloWorld
The Applet is compiled just like any other program:
javac HelloWorld.javaThis 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:
appletviewer test.HelloWorld.htmlHowever 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
test.HelloWorld.htmlbut 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
( S.DOS=`\`, S.UNIX=`/`, S.Mac=`:`)then the applet code for class C must be in directory DSclasses 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):
:!java %
:!netscape test.page.name.htmlto 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.
java classnameThis 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:
private final static int SIZE = 300;//size of window
public static void main(String args[]) {
HelloWorld aHelloWorldObject = new HelloWorld();
//The aHelloWorld object exists
aHelloWorldObject.init();
//aHelloWorld has now initialized it self
aHelloWorldObject.start();
//aHelloWorld has now started running
Frame aWindow = new Frame("HelloWorld");
//A window called "HelloWorld" will hold the Applet
aWindow.add("Center", aHelloWorldObject);
//aWindow now has aHelloWorld in it's center
aWindow.resize(SIZE, SIZE);
aWindow.show();
//aWindow is now shown to you (until you CTRL/C)
}//mainYou can download an uptodate working copy of the HelloWorld class which is both an applications and and applet from [ 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 [ instantapplet ] Please download and try out -- Beta Testing.
Another Example
There is a more elaborate example of a Java applet/application program
in
[ 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 <Applet> tag.
. . . . . . . . . ( end of section Applets) <<Contents | End>>
Summary
| To get | write this |
|---|---|
| Application: | public class C ... { ... public static void main(String[])...} |
| Applet: | import java.applet.*; .... public class C extends Applet ... { ... } |
| A class with name | C |
| is best put in a file | C.java |
| and compiled by | javac C.java |
| producing Bytecode | C.class |
| executed by | java C arguments |
| and documented by | javadoc C.java |
| producing | C.html |
. . . . . . . . . ( end of section Overview) <<Contents | End>>
Glossary
Also see [ java.glossary.html ]
. . . . . . . . . ( end of section Glossary) <<Contents | End>>
Syntax
In outline a java file starts with an optional package declaration and some import statements:
package whatever;
import package.subpackage.....class
import package.subpackage.*These are followed by a sequence of class and interface declarations:
modifiers name extends class possible_interfaces{
field and function definitions
}
Field definitions have two forms:
modifiers type name;and
modifiers type name = initial value;where a type is either a classname or a simple data type like 'int' or 'char' or 'double'. If the modifiers include 'final' then the field is a constant, othewise it is a variable. The following is a very common and useful type of declaration:
modifiers type name = new type(arguments);
Arrays are declared like this:
modifiers type name[] = new type[size];You can omit the initializer -- and name will be NIL!
modifiers type name[];The array must not be used until it is initialised in a staement like this:
name = new type[size];
In either case, if the 'type' is a class(like Object or Applet), the individual objects must be constructed and put in the array before they are used.
name[0] = new type;
name[1] = new type;perhaps.
Function definitions have form
modifiers return_type name(arguments){
local definitions and statemants
}the return_type above is "void" or the name of a class or simple data type. modifiers are listed in the glossary. In older Java only variables (fields) can be defined as local.
Statements have following main forms:
variable.function_name(arguments)...;
class.function_name(arguments)...;
variable = expression;
while(expression) statement
if(expression) statement
if(expression) statement else statement
Expressions are typical arithmetic, relational, conditional, expressions of C or C++ plus
variable.function_name(arguments)...;
class.function_name(arguments)...;
Java allows you to declare local variables and constants inside a function. You can declare a new variable or constant at any place in a function but you can not define the same identifier in different blocks. This causes a common error with for statements like this:
for(int i=0; i<array.size; ++i) {...}
You must not declare i anywhere else in the same function!
This constraint makes the interpreter much simpler and possibly
faster since all space for local data is allocated when the
function is called rather than when it is declared.
For a detailed description of the syntax of Java see
[ java.syntax.html ]
at this site.
The following definitions define the syntax of UNIX and HTML
related to Java.
Meta-Notation
(filenames):
. . . . . . . . . ( end of section Syntax) <<Contents | End>>
Predefined Classes
Java is a small language that gets much of its flavor and power
from a very large and expanding library of predefined classes.
Sun has provided a collection of
packages in the Java run-time library
For 1.4.2 API see [ index.html ] and for 1.5.0 [ index.html ] (Summer of 2004).
Also see my rough introduction to some commonly used classes and interfaces [ java.classes.html ]
In theory at least the library includes all the public classes that have been put on the WWW as well!
Javascript is Not Java
Javascript is a scripting language that
extends HTML. In stead of having a tag that names an applet, you
have a tag (<SCRIPT> that contains the script inside the page.
It was invented by Netscape to allow people to
write programs to generate pages dynamically. Javascript programs
are placed in between <SCRIPT> ... </SCRIPT> tags in the HTML page
and they are executed as the oage is loaded by the user's Browser.
They can also be attached to buttons on a page.
Javascript was once called LiveScript. It is beeing standardized by ECMA (European Standards...) as ECMAScript. Meanwhile MicroSoft has produced its own version called JScript! Even Netscape has 3 or 4 versions of Javascript. The common syntactic ancestor (C++) with Java is clear but the details are quite different to Java. The semantics is closer to Smalltalk than anything else.
Both Java and Javascript let you produce more complex pages. Both Java and Javascript run on the user's system. A CGI [ CGI in comp.html.syntax ] is executed on the server and sends the results to the client.
Pointers to news and Google groups:
comp.lang.javascript
Specification of Java
Microsoft would prefer its own version of Java and libraries to be the standard. 10,000 developers who want Java's to be a cross-platform language have formed the Java Lobby.
Sun sued MicroSoft for abusing its licence of Java by giving out a version that will work with only MicroSoft software rather than on all platforms. So far(Winter 1998-1999) Microsoft has been ordered to stop giving out their polluted version and have been forced to distribute an upgrade to the "Pure Java" version.
Now MicroSoft is promoting .NET and C# as rival tecnologies to Java.
Other Specifications
There is a short glossary of the terms used in Java
[ java.glossary.html ]
in my local samples of formal documentation.
The syntax (1.0alpha) is summarized at [ java.syntax.html ] in my documentation samples.
Java has its semantics defined by a compiler that translates the Java source code for a virtual machine (the JVM), There is a detailed specification of the virtual machine. My own notes on Java semantics are under construction [ java.semantics.html ] in my documentation samples.
(File Formats): A specification of the format of a .class file was held at
http://www.javasoft.com/1.0alpha3/doc/vmspec/vmspec_38.html
but I haven't found the replacement.....
Java Documentation
(Java reference): Sun's reference site
[ http://java.sun.com/reference/ ]
(Java Specification):
For the the Official Java(TM) 2 Platform, Standard Edition.
[ http://java.sun.com/j2se/ ]
. . . . . . . . . ( end of section Specification of Java) <<Contents | End>>
USENET NewGroups( searchable via Google Groups): comp.lang.java.announce , . . . comp.lang.java.security , . . . comp.lang.java.programmer , . . . comp.lang.java.tech , . . . comp.lang.java.misc , . . . comp.lang.java.advocacy , . . . comp.lang.java.setup , . . . comp.lang.java , . . . alt.www.hotjava , . . . comp.lang.javascript , . . . comp.compilers.tools.javacc , . . . comp.lang.java.corba:
remote: [ index.html ] [ free-counters.htm ] [ ~espresso ] [ http://www.w3.org/pub/WWW/OOP/9606_Workshop/ ] [ phoneCase.html ] [ wallstreetweb ] [ index.html ] [ http://www.inch.com/~friskel/ ] [ http://www.gamelan.com/ ] [ http://www.inmet.com/java.html/ ] [ algintro.html ] [ index.html ]
remote: [ http://java.sun.com/ ] = [ http://www.applets.com/ ] , . . . For more general information see the Java and HotJava Documentation [ documentation.html ] and in particular the goals of Java [ index.html ] and the Java Tutorial at Sun.com [ http://java.sun.com/tutorial/ ]
A programmer's guide: [ index.html ]
. . . . . . . . . ( end of section Pointers to WWW information on the Java Language) <<Contents | End>>
The Source Code
News and Announcements
[ http://www.cnet.com/Content/News/ ]
The Java announcements archive [ http://wuarchive.wustl.edu/packages/java/ ] plus my local archives of announcements: [ java.www.sites.html ] (after July 29th 1996) [ old.java.www.sites.html ] (before July 29th 1996)
The Java Newbie FAQs from Usenet comp.lang.java: //www.csci.csusb.edu/doc/java.newbie.FAQ
Elliotte Rusty Harold's Official Frequently Asked Questions [ javafaq.html] .
Also see TeamJAVA [ http://www.teamjava.com:80/links/ ] and HowDoI at Digital Focus: [ howdoi.html ] Also see Earthweb's Java Directory on www.Gamelan.com [ http://www.gamelan.com/ ]
I culled a few common questions and answers in [ java.FAQ ] but these are very rough and ready as yet, and not official FAQs for Java. Also see the uneditted version: [ java.mbox ]
USENET NewsGroups(also on Google groups)
(newsgroups):
(computer Language):
comp.lang.java.announce
comp.lang.java.security
comp.lang.java.programmer
comp.lang.java.tech
comp.lang.java.misc
comp.lang.java.advocacy
comp.lang.java.setup
comp.lang.java.corba
comp.lang.java
(Setting the class path): java
[ classpath-linux.html ]
(tools):
alt.www.hotjava
comp.compilers.tools.javacc
Tutorials
Locally: Under redevelopment.
At Fairfield: [ java.html ]
Marty Hall's Tutorials [ #Tutorials ]
Books
Errata for "Java in 21 Days"
[ errata.html ]
Examples etc for "Java in a Nutshell" //ftp.ora.com/published/oreilly/nutshell/java/
Local information on objects in general [ objects.html ] , . . . information on language including Java [ Java in languages ] , . . . and notes and links about software engineering in general [ se.www.sites.html ]
Source Code Examples
[ http://www.Planet-Source-Code.com/PlanetSourceCode/ ]
. . . . . . . . . ( end of section See also) <<Contents | End>>
Trivia
(CAFEBABE):
On UNIX a compiled class can be recognized because it will
contain a magic string of bytes that spell out in hexadecimal
0xCAFEBABE.
The Naming of Java
Some think it means "Just Another Vague Acronym".
The name "Java" is not an acronym. The original name was "Oak", after the tree outside the developers window, but it turned out that "Oak" was already copyrighted/trademarked/in-use. The descriptions of the next stage vary but all indicate some kind of brainstorming session and/or a local coffee shop, during which name "Java" was proposed and accepted.
. . . . . . . . . ( end of section The Java Programming Language) <<Contents | End>>