Java




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 MyProg.java
class MyProg
{

Program goes here!!!

}
-->In the bin directory, from the command-line, type javac + the filename and hit ENTER. Example:javac MyProg.java
-->If there are no error there should be a .class file with the same name as your .java file. Example: MyProg.java    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" >
< / APPLET>
< / 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.setVisible(true);

f.addWindowListener(new WindowAdapter () {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}

public void paint (Graphics g) {
g.setColor (Color.red);
g.drawOval (10,30,30,30);
g.setColor (Color.green);
g.drawOval (35,30,30,30);
g.setColor (Color.yellow);
g.drawOval (60,30,30,30);
g.setColor (Color.blue);
g.drawOval (23,52,30,30);
g.setColor (Color.black);
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++.

Calculator.java(contains 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();
System.out.println("This is the Fuel Distance Check Program");
System.out.println(21/7f);

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");
System.out.println();

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();
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() {
callSwitchStatement(getRandomNum());
}

/**
* 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(sloganNum);
System.out.println("Java Beans - hand picked by Juan Valdez");
break;
case 1:
System.out.println(sloganNum);
System.out.println("Thou shall brain them...- from Handel's Messiah");
break;
case 2:
System.out.println(sloganNum);
System.out.println("An Apple a day keeps Microsoft away!");
break;
case 3:
System.out.println(sloganNum);
System.out.println("640K ought to be enough memory for anybody - Bill Gates");
break;
case 4:
System.out.println(sloganNum);
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");
break;
case 5:
System.out.println(sloganNum);
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");
break;
default:
System.out.println("Death to the switch statement!");
//NO chance of happening in this case!
break;
}

}

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 SavitchIn.java. 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 SavitchIn.java 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 SavitchIn.java. 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.

Rabbits.java

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

Mmm.java

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

Nim.java

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

Matryoshka.java

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

License.java

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

LeapYear.java

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

Initials.java

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

Baseball.java

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

BabySitter.java

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

Sum.java

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

RepeatedDigits.java

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

Rocks.java

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

ThisOldMan.java

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

House.java

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

KnightMoves.java, 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*/
try{
&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 MainInterface.java within the Java Web Generator and Editor


Arrays

Sum.java
General array info


Commenting

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

BabySitter.java
Baseball.java
BasicList.java
BasicQueue.java
BasicTree.java
Calculator.java
Casino
    BlackJack.java
    GameDriver.java
    LoopLL.java
    Queue.java
    Roulette.java
    Slots.java
    Tree52.java
DistanceCheck.java
DoWhileTest.java
FindNext.java
House.java
Initials.java
KnightMoves.java
LeapYear.java
License.java
LL21.java
LL22.java
LL23.java
LLString.java
Matryoshka.java
Mmm.java
Nim.java
PP_1_2.java
PP_1_3.java
PrintBinTree.java
PascalTriangle.java
ProveNull.java
Rabbits.java
RepeatedDigits.java
Rings.java (This page)
Rocks.java
StringTests.java
SimpleApplication.java
SimpleApplet.java
Sum.java
SwitchTest.java (This page)
TicTacToe.java
TrafficLight.java
Triangles.java
TempConverter,java (This page)
ThisOldMan.java
Web Generator and Editor
    Hlib.java
    HTMLGen.java
    MainInterface.java
    WebEdit.java
    WindowDestroyer.java



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
freewarejava
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)
Calculator.java
hp_calculator.java.html