Obtaining, Setting up, and Using a Development Environment

Get the latest download from Sun Technologies
Sun Java Tutorials

Java Applications and Applets

There are two main types of Java programs, Applications and Applets. Applications are like programs in other languages, they are "standalone" and can be run from the command-line. Applets are designed to work within browsers, specifically to be used on the World Wide Web. Applets not usually outside of browsers and must be called from within an HTML page. Some Java compiler/developer environments have browser emulators, but I recomend always testing on the real thing. Your browser can be off-line when you test applets and the HTML code used to call them is very easy to write. A major i0ssue in Applet writting is browser compadability. Many older browsers will not run applets, others will only run certain types of Java applet code. If you are creating applets from behind a firewall, check with your sysadmin to see if applets are blocked. You must also check your browser preferences to allow applets to be run.

Compiling and running Java from the command line

-->If you are using windows, you should build your .java files in the folder called "bin" in you java directory. This will make things easier.
-->Make sure the internal class name is the same as the file name. Example:
The file name is
class MyProg

Program goes here!!!

-->In the bin directory, from the command-line, type javac + the filename and hit ENTER. Example:javac
-->If there are no error there should be a .class file with the same name as your .java file. Example:    MyProg.class.
-->Now type java MyProg to run the program(no file extension needed!)

How to run Applets in a Browser

In order to run Applets you will need a compiled Java program(the "class" code), a browser to test it in, and a very simple HTML script. Many people who program have never written HTML code and gett stumped when they have to use it for Applets. Here is a very simple HTML script that will run any Applet, you just have to change the name it points to.

< HTML >< HEAD >< TITLE > Applet Runner < / TITLE > < / HEAD >
< BODY >
< APPLET CODE= "MyApplet.class" >
< / BODY >
< / HTML >

Copy this into a text editor, eliminate the spaces with in the < > tags, change the name of the Applet to the one you're running(APPLET CODE=), and save the HTML script as app_run.html. Now, double-click on file's icon to open your browser, or open the browser and go to File, Open and open the HTML file that way. Once you get your Applet running, you may go back and change the HTML code to make it look better.

The first program is an application, the second is an applet.

Application Displays the Olympic Rings

import java.awt.*;
import java.awt.event.*;
class Rings extends Frame {
public Rings (){
setTitle ("Olympics Rings");

public static void main (String [] args) {
Frame f = new Rings ();
f.setSize(300, 200);

f.addWindowListener(new WindowAdapter () {
public void windowClosing(WindowEvent e) {

public void paint (Graphics g) {
g.setColor (;
g.drawOval (10,30,30,30);
g.setColor (;
g.drawOval (35,30,30,30);
g.setColor (Color.yellow);
g.drawOval (60,30,30,30);
g.setColor (;
g.drawOval (23,52,30,30);
g.setColor (;
g.drawOval (51,52,30,30);

g.drawString("Olympic Rings", 40,100);

Calculator Applet

As this is an applet, you will need a simple HTML script to run it in your browser. Every applet must also import the java.applet.* library which contains working code that is need to run the applet. Importing libraries is similar to including header files in C and C++. depricated code)

This program shows the use of arithmetic with Java code

import java.*;

class DistanceCheck {

public static void main (String [] args){

System.out.println("This is the Fuel Distance Check Program");

double normalRoadRate; //Declaration section
double roughRoadRate; //these are our variables for the
float fuel; //program
double km;
static integer Prize = G50;
static int 2ndPrize = G25;
normalRoadRate = 100f / 8f; //Initialization section
roughRoadRate = normalRoadRate * 0.85; //Icreases rate by 15%
fuel = 40f;

km = fuel * normalRoadRate ; //Calculates fuel rate for normal roads

//Section prints out calculations
System.out.print("On normal roads " + fuel + " litres of fuel ");
System.out.println("will take you " + km + " Km");

km = fuel * roughRoadRate; //Calculates fuel rate for rough roads

//Section prints out calculations
System.out.print("On rough roads " + fuel + " litres of fuel ");
System.out.println("will take you " + km + " Km");
System.out.println("End Program");


This code shows the use of the switch statement in Java

* Illustrates the use of the switch statement for multiple selection in
* Java. Also, illustrates the use of a very useful method in the java.lang.Math
* class called random()
public class SwitchTest {

public SwitchTest() {

* Returns a random num from 1-6 (In general, will return
* a random number from 0 to n-1.
public int getRandomNum() {
int n = 6;
return (int)(Math.random()*n);

* method callSwithStatement passes in a random number from 0-5
* and accordingly, gives out a slogan. Depending on which number is
* sent in, the appropriate slogan is written to screen.
public void callSwitchStatement(int sloganNum) {

switch (sloganNum) {
case 0:
System.out.println("Java Beans - hand picked by Juan Valdez");
case 1:
System.out.println("Thou shall brain them...- from Handel's Messiah");
case 2:
System.out.println("An Apple a day keeps Microsoft away!");
case 3:
System.out.println("640K ought to be enough memory for anybody - Bill Gates");
case 4:
System.out.println("C makes it easy to shoot yourself in the foot,");
System.out.println("C++ makes it harder, but when you do,");
System.out.println("it blows away your whole leg");
case 5:
System.out.println("People say you can't compare apples and oranges. ");
System.out.println("But why not? They are both hand-held, round, edible ");
System.out.println("fruity things that grow on trees");
System.out.println("Death to the switch statement!");
//NO chance of happening in this case!


public static void main (String args[]) {
SwitchTest st = new SwitchTest();

Application converts temperatures from Fahreinheit to metric.

Changing the code to make it work in opposite direction is very simple
* A very simple application that calculates the temperature
* in degrees Centigrade when given the temperature in
* degrees Fahreinheit.
public class TempConverter {

* This is a constant. What this means is that the value of T1
* will always be 212. Hence the name constant!
static final int T1 = 212;

* This is the "main" method, the starting point of this
* program. Since it has a main method, we can be sure
* that this program is an application. */
public static void main (String args[]) {
* This is a variable or container that will hold the
* value of the temperature in degrees Centigrade.
* Always use a name that makes sense. Note, that this
* variable is of type double.
double degC = 0.0;
* This is an integer variable for holding the value of
* the temperature in degrees Fahreinheit. Notice how it
* is initialized differently. Always initialize your
* variables.
int degF = 0;
degF= T1; //Here we set the Fahreinheit temperature to our constant
//* T1
degC = (degF - 32)* (5.0/9.0); // our formula
System.out.print("The temperature " + T1 + " degrees Fahreinheit is "); // the output
System.out.println( + degC +" degrees Centigrade"); // to screen.

Typical Programs

The programs below all use the command line input utilities provided in Written by Walter Savitch, this class simplifies the typically difficult input of Java and alows you to focus on other parts of programming. To add this class, copy the file to your java "bin" folder. If you are using Sun's Java on windows it is usually "C:\jdk1.2.2\bin", otherwise look for "bin" folders that have a program called "java.exe". Compile it by browsing to the folder on the command line and typing javac You may or may not need the line "import utils.SavitchIn;" at the top of your class, it is best to have it there commented out in case you move your code to another system.

Calculates generations or rabbits using Fibonacci numbers.
Uses: for loops, methods, parameter passing

Cacluates the mean, median and mode of number lists. The median making method uses the "bubble sort" technique.
Uses: constants, if/else, for loops, methods, parameter passing, int arrays, switch statements

Plays the game of Nim.
Uses: while loops, switch statements, if/else

Sorts sets of Matryoshka doll sizes.
Uses: for loops, if/else

Generates random license plate numbers, 3 letters and 3 numbers.
Uses: nested for loops, random numbers

Figures out if a given year is a leap year.
Uses: while loops, nested if/else, while, booleans, methods, parameter passing

Displays the initials of a name entered.
Uses: String, methods, parameter passing, while loops

Calculates a random batting average.
Uses: String, methods, parameter passing, while loops

Calculates a baby sitter's pay.
Uses: nested for, nested if/else

Calculates the sum of two integer arrays.
Uses: int arrays, methods, parameter passing, for loops

Takes a string of numbers and figures out how many times each digit is repeated in the string.
Uses: switch statements, int arrays, Strings, do/while, for loops, if/else

Calculates the number average rocks thrown at a buidling on any given day.
Uses: while loops, if/else, for loops, nested loops

Displays the lyrics to "This Old Man"
Uses: for loops, switch statements

Larger program the alows a user to move about 4 rooms, pick up and drop 4 objects, turn on/off lights, etc... There's a lot of room for enhancement and improvement here.
Uses: while loops, if/else, for loops, switch statements, int arrays, Strings, booleans, methods, parameter passing, also called "KnightsTour"

An ancient puzzle where a traditional chess knight must move to every spot on the board once(and only once), starting from any square on the board.

Making System Calls

You can call system functions outside the program, like DOS commands for example using Runtime.getRuntime() and exec()
String cmd = "script.bat"; //The name of the batch file, perl script or other external command script.
Runtime r= Runtime.getRuntime(); //Declare the system call

/*Then a try block to run the command*/
&nbps;&nbps;&nbps;&nbps;Process p=r.exec(cmd);
/*can produce errors which must be caught*/
catch(Exception e) { System.out.println (e.toString()); }
A full example is in within the Java Web Generator and Editor

General array info


Text on a single line following // is not read by the compiler Multi-line text between /* and */ is not read by the compiler

Program Index
Casino (This page) (This page)
TempConverter,java (This page)
Web Generator and Editor

Links and Resources

Java On-line Book
Principles of Object-Oriented Programming in Java 1.1
Introduction to Programming Using Java
Java and artificial intelligence programming
Getting the Java Environment
Free Java Books / Tutorials online
Java Programming Resources
Java Programming Resources
String Methods
JavaTM 2 Platform, Standard Edition, v 1.3.1
Class java.awt.Button
Class java.lang.Math
The Unicode Character Code Charts
Shift and Logical Operators
Summary of Operators
Unicode Math Operators(PDF)