Creating java code

JVMs are built into most web browsers, however to compile your own code you also need the Java Development Kit (JDK or SDK) from Sun microsystems (Java was invented by Sun, which is still the best source for the basic tools, although the specification is open so others can also develop them)

Go to http://java.sun.com/ and to products and APIs (top-left menu), then pick a version to download.

This is a dilemma: the basic web browsers (NS4.5+, IE4or5) use a variant of Java 1.1 (with some features missing), but Sun is now promoting Java 1.3 (or even 1.4). It is safer to start with JDK 1.1, so as not to be confused by many new features that won't work in most web browsers.

Also download the Java Tutorial from Sun which you can find under the docs and training section (top-left menu)

Note as well as the main tutorial package (also big!), you are advised to download the old archive "creating a user-interface AWT only", since the newer "Swing" classes aren't available in most web browsers.

Unpack and setup the package on your computer according the instructions included

Then you can, in theory, start compiling code by typing instructions at the DOS prompt (in Windows) or a terminal window (Unix). The JDK documentation explains this,

However you could soon get bored typing in commands this way. To make it easier, you can set up your windows explorer to compile java files, just by right-clicking with the mouse. This involves some tricks using DOS batch routines, which I got from a small package called JDEX.

Getting Started with Writing Java Applets

An interactive, object-oriented code has no simple beginning and end, but you must start somewhere. An applet is a special class that appears in a web browser. Here is the simplest possible:
import java.applet.Applet;  import java.awt.*;  
public class Myapplet extends Applet { 
public void paint(Graphics g) { g.drawString("Hello",4,20); }
} 
The first line imports the necessary java packages (awt=abstract window toolkit). The next specifies you are adding to the existing Applet class. The paint method will be called by the browser which provides the graphics context "g". All applets must have either a paint or an init method, which must be declared "public".

Copy the four lines above into a text file called Myapplet.java. Then compile this file, which should produce Myapplet.class Then make a very simple web page (put it in the same directory).


<html><body>
Below is my applet<p>
<applet width=100% height40% code="Myapplet.class"></applet>
</body></html>

Then just open that web page, in internet explorer. You should see it says "Hello" inside the grey rectangle.

The example below is more fun, it makes a wavy sea with floating balls.


import java.applet.Applet;  import java.awt.*;  
public class Wave extends Applet { 

boolean loop; int i,x,y,w,h; 

public void paint(Graphics g) { 
w=this.size().width; h=this.size().height;
i=0; while(loop) { 
i++; if (i>1256) i=0;
for(x=0; x<w; x++) {
y=(int)((0.5*h + (0.4*h)*Math.sin((double)(x+i)/50.0) + (0.05*h)*Math.sin((double)(x+i*4)/10.0) );
g.setColor(Color.cyan); g.drawLine(x,0,x,y);
g.setColor(Color.blue); g.drawLine(x,y,x,h);
if (((x+(int)(1.5*i))%80)==0) {g.setColor(Color.yellow);g.fillOval(x-10,y-8,12,12);}
if (((x+(int)(2.0*i))%150)==0) {g.setColor(Color.red);g.fillOval(x-20,y-16,20,20);}
}}}

public void start(){loop=true;} 
public void stop(){loop=false;} 
}

Now you need this web page to run it:

<html><body>
<applet width=100% height40% code="Wave.class"></applet>
</body></html>

Once you see what it does when you run it, you might be able to understand how the code works, by reading my notes on java syntax appended below.

Extra notes:

  • start() and stop() are called when you open and close the page (applies to any applet)
  • while(loop){} will keep looping so long as loop is true
  • %80 calculates the remainder after dividing by 80
  • the g.methods are part of java.awt.Graphics but it should be fairly obvious what they do
  • note the type conversions (double) (int) etc.

    Changing the applet size will change the wave speed too, since the java is calculating as fast as it can. Math.sin is a rather slow function, so you could make this more efficient by storing an array of y values before the main loop.


    Compiling/Testing Tips

    Internet Explorer's JVM starts up the first time it meets an applet, and then stays open as long as Explorer does (note your desktop is also a copy of Explorer!). This JVM doesn't check whether you have changed a class file. So to force the JVM to start again after you changed a java class file, use CTRL-F5 immediately after refreshing or reopening the web page.

    You can instead use the java appletviewer supplied with JDK, which always refreshes. However beware it doesn't understand percentage width/height in the html applet tag!

    If the compiler reports an error, you won't get any class file, instead a text file describing the errors.

    But if it succeeds, that doesn't mean you won't sometimes get errors, or "runtime exceptions" which may stop the applet from working. These will usually be reported in "Standard Output". In a web browser, the standard output is the Java Console, which you can find in the view menu in internet explorer (or tools in netscape). If it's not there, you need to enable it first by changing the web browser settings ("java console" or "java logging" under advanced options). The java console also catches anything you write to System.out, e.g. System.out.println("Got to here OK"); (you can put this into your code for debugging)


    Now to go further, read Sun's java tutorial. This is a good introduction to the language, but has much more detail than you need at the beginning!

    Some basic notes about java syntax below, since some of this is not obvious from the tutorial.

    The best way to learn is by trial and error, frequently checking the API documentation that comes with the JDK which describes each class in detail.


    Basic Java Syntax

    Java syntax is based on C++
    Here are some notes to get started Some simple examples:
    Make an integer a and set it to equal 5
    	int a=5; 
    Make an array of 3 integers and set the first one to 5 
    	int[] a = new int[3]; a[0]=5; 
    Note array indices start at 0, so code below will give an error: "array index out of bounds"!
    	int[] a = new int[3]; a[3]=5; 
    
    Make a=5, pass this to a method to calculate b
    	int a=5; 	int b=calcsquare(a);
    And here's that method which could be elsewhere in the code 
    	int calcsquare(int x) {int y=x*x; return y;}
    (note a is picked up as x, and b is returned from y, 25 in this case)
    
    Note that methods are declared using:
    	return-type methodname(parameter-type parameter-name) {dosomething... ;}
    return type can be "void" -in which case it doesn't return anything
    
    Strings (text) are objects in java, but with special properties that you can make a new one with quotes, and can add them
    	String a="good"; String b=a+" morning"; 
    
    Note:
    a=b is an assignment (sets a to be the value of b)
    a==b returns a boolean true/false for use in "if(a==b)" etc.
    ! means not, so a!=b returns true if they are not equal
    i=i+1 , i+=1 , i++  are all the same
    
    Flow control statements may use both () and {} brackets, for example  
    	if (a==b) {dothis(a); andthis(b);}
    start with i=0, keep looping until i<n, add one to i at each step
    	for(i=0; i<5; i++) {j+=i; k+=j;} 
    
    Note the following looks confusing but is ok! 
    	Polygon[] polygon=new Polygon[5]; polygon[0]= new Polygon(); 
    this means make a new array called polygon, of 5 objects with class-type Polygon, and set up the first one using the default constructor method Polygon() 
    
    Dots are used to connect objects or methods to their parent objects, e.g. 
    	model.mod[5].calcsealevel(model.mod[4].temp[2002]);
    You could achieve the same by writing: 
    	m=model.mod; m[5].calcsealevel(m[4].temp[2002]);
    Note mod represents the whole array
    
    Arrays can have as many dimensions as you like.
    You can initialise arrays using {} brackets, useful for data:
    td[][]={ {5,6,7,8}, {1,2,3,4}, {9,10,11,12} };
    
    Putting variable types in brackets converts from one kind to another
    The compiler insists you specify this, whenever you might lose information, e.g.
    	double a=5.4; int b=(int)a; //now b=5, compiler would give an error without (int)
    	int b=5; double a=b+0.4; //here you didn't need (double) because nothing is lost
    Note that "1" is an int, "1.0" is a double, "1.0f" is a float
    Calculations tend to preserve the type of the first variable,
    so 4.1/3 gives 1.36667 whilst 4/3 gives just 1 (not 1.33333)! 
    
    Note if pan is an array of panel objects, graph class extends panel class, and xscale is a method specific to graph class, then the following also works as a type conversion: 
    if (pan[p] instanceof graph) {thisgraph=(graph)pan[p]; thisgraph.xscale(1900,2100);}
    
    Beware regarding method parameters:
    	mymethod(x); 
    	void mymethod(variabletype y) {dosomething...;}
    If variabletype is a simple number (int, double etc.) or boolean (true/false), this passes just the *value* of x, so if mymethod changes y this won't affect x elsewhere in the code.
    But if variable type is any more complex object, it passes the *reference* (imagine location in memory), so if mymethod changes a property of y, this will affect the original x too!