Warning: strpos(): needle is not a string or an integer in /home/thebestp/public_html/buildingblocksjava/wp-content/plugins/textlinkads/textlinkads.php on line 175

Warning: strpos(): needle is not a string or an integer in /home/thebestp/public_html/buildingblocksjava/wp-content/plugins/textlinkads/textlinkads.php on line 175

Warning: strpos(): needle is not a string or an integer in /home/thebestp/public_html/buildingblocksjava/wp-content/plugins/textlinkads/textlinkads.php on line 175
Uncategorized | Building Blocks Java

Archive for the 'Uncategorized' Category

Acknowledgements

Noone ever truly writes a book alone. This tutorial relies heavily on Brian Kernighan and Dennis Ritchie’s The C Programming Language, one of the alltime classics of computer language manuals.
The presentations at the first Java Day in New York City were crucial to getting my understanding of Java off the ground, especially those of [...]

Part 1: Why Java’s Cool

Java has caused more excitement than any development on the Internet since Mosaic. Everyone, it seems, is talking about it. Unfortunately very few people seem to know anything about it. This tutorial is designed to change that.
People are excited about Java because of what it lets them do. Java was [...]

Installing Java

As of this writing Java is not a fully developed commercial product. Versions of Java at varying stages of completion are available from Sun for Windows 95 and Windows NT for X86, Solaris 2.3 to 2.5, and MacOS 7.5. At the present time there are no versions of Java available for MIPS, Alpha or PowerPC [...]

Windows Installation Instructions

The Windows X86 release is a self extracting archive. You will need about six megabytes of free disk space to install the JDK. Execute the file by double-clicking on it in the File Manager or by selecting Run… from the Program Manager’s File menu and typing the path to the file. This will unpack [...]

Unix Installation Instructions

If you’re on a shared system at a university or an Internet service provider, there’s a good chance Java is already installed. Ask your local support staff how to access it. Otherwise follow these instructions.
The Unix release is a compressed tar file. You will need about nine megabytes of disk space to uncompress and untar [...]

Running Your First Applet

Unix Instructions
Start the Applet Viewer by doing the following:

Open a command line prompt, and cd to one of the directories in /usr/local/java/demo, for example
% cd /usr/local/java/demo/TicTacToe

Run the appletviewer on the html file:
% appletviewer example1.html

Play Tic-Tac-Toe! The algorithm was deliberately broken so it is possible to win.

Macintosh Instructions

Start the Applet [...]

Applets in Netscape

Netscape 3.0 will run Java applets on most platforms except Windows 3.1. Netscape has a Java Demo Page with links to various applets that will mostly run. However do not be surprised if an applet fails to work properly in Netscape.

Hello World: The Application

At least since the first edition of Kernighan and Ritchie’s The C Programming Language it’s been customary to begin programming tutorials and classes with the “Hello World” program, a program that prints the string “Hello World” to the display. Being heavily influenced by Kernighan and Ritchie and not ones to defy [...]

Examining Hello World

Hello World is very close to the simplest program imaginable. Nonetheless there’s quite a lot going on in it. Let’s investigate it, line by line.
For now the initial class statement may be thought of as defining the program name, in this case HelloWorld. The compiler actually got the name for the class file from [...]

Braces and Blocks

Let’s investigate the Hello World program a little more closely. In Java a source code file is broken up into parts separated by opening and closing braces, i.e. the { and } characters. Everything between { and } is a block and exists more or less independently of everything outside of the braces.
Blocks [...]

Comments

Comments can appear anywhere in a source file. Comments are identical to those in C and C++. Everything between /* and */ is ignored by the compiler and everything on a line after two consecutive slashes is also thrown away. Therefore the following program is, as far as the compiler is [...]

Data and Variables

Methods are only half of a Java class. The other half is data. Consider the following generalization of the HelloWorld program:
// This is the Hello Rusty program in Java
class HelloRusty {

public static void main (String args[]) {

// You may feel free to replace “Rusty” [...]

Command Line Arguments

Our Hello program still isn’t very general. We can’t change the name we say hello to without editing and recompiling the source code. This may be fine for the programmers, but what if the secretaries want their computers to say Hello to them? (I know. This is a little far-fetched [...]

If

All but the most trivial computer programs need to make decisions. They need to test some condition and operate differently based on that condition. This is quite common in real life. For instance you stick your hand out the window to test if it’s raining. If it is raining then you [...]

Else

You may have noticed a minor cosmetic bug in the previous program. A cosmetic bug is one that doesn’t crash the program or system, or produce incorrect results, but just looks a little annoying. Cosmetic bugs are acceptable in quick hacks you’ll only use once but not in finished code.
The cosmetic bug here was [...]

Variables and Arithmetic Expressions

We’ll begin this section by finding a more elegant way to handle multiple command line arguments of an undetermined number. Toward this end we introduce the concept of a loop. A loop is a section of code that is executed repeatedly until a stopping condition is met. A typical loop may [...]

Classes and Objects: A First Look

Classes are the single most important feature of Java. Everything in Java is either a class, a part of a class, or describes how a class behaves. Although classes will be covered in great detail in section four, they are so fundamental to an understanding of Java programs that a brief introduction is [...]

Interfaces

Like we said, Java source is really just classes. Import statements are shorthand for many different classes; and comments aren’t really there (as far as the compiler is concerned) in the first place. However there is one thing in Java source code that is neither a class nor a member of a class. [...]

FahrToCelsius

Java is not just used for the World Wide Web. The next program demonstrates a classic use of computers that goes back to the earliest punch card machines. It’s reminiscent of some of the very first useful programs I ever wrote. These were designed to quickly calculate several dozen numbers to keep me [...]

Floating Point Variables

You may have noticed something a little funny about the above output. The numbers aren’t exactly correct. Zero degrees Fahrenheit is actually -17.778 degrees Celsius, not -18 degrees Celsius as this program reports. The problem is that we used only integers here, not decimal numbers. In computer-speak decimal numbers are called [...]

The For Statement

Java isn’t as redundant as perl, but there’s still almost always more than one way to write any given program. The following program produces identical output to the Fahrenheit to Celsius program in the preceding section. The main difference is the for loop instead of a while loop.
// Print a Fahrenheit to [...]

Assignment, Increment and Decrement Operators

In reality almost nobody writes for loops like we did in the previous sections. They would almost certainly use the increment or decrement operators instead. There are two of these, ++ and — and they work like this.
//Count to ten

class CountToTen {

public static void main (String args[]) {
[...]

Methods

All the programs we’ve written to date have been quite simple, well under fifty lines of code each. As programs grow in size it begins to make sense to break them into parts. Each part can perform a particular calculation and possibly return a value. This is especially useful when the calculation [...]

Recursive Methods

Java supports recursive methods, i.e. even if you’re already inside methodA() you can call methodA(). The easiest way I can think of to explain recursion is to look at a simple acronym, GNU. The GNU project, among other things, is trying to produce free versions of the Unix operating system and many Unix tools, [...]

Arrays

In non-trivial computing problems you often need to store lists of items. Often these items can be specified sequentially and referred to by their position in the list. Sometimes this ordering is natural as in a list of the first ten people to arrive at a sale. The first person would be [...]

Creating Arrays

There are three steps to creating an array, declaring it, allocating it and initializing it.
Declaring Arrays
Like other variables in Java, an array must have a specific type like byte, int, String or double. Only variables of the appropriate type can be stored in an array. You cannot have an array that will store both ints [...]

Counting Digits

We’ve already seen one example of an array. Main methods in an application store the command line arguments in an array of strings called args.
As our second example let’s consider a class that counts the occurrences of the digits 0-9 in decimal expansion of the number pi, for example. This is an issue of [...]

Two Dimensional Arrays

The most common kind of multidimensional array is a two-dimensional array. If you think of a one-dimensional array as a column of values you can think of a two-dimensional array as a table of values like so:

c0
c1
c2
c3

r0
0
1
2
3

r1
1
2
3
4

r2
2
3
4
5

r3
3
4
5
6

r4
4
5
6
7

Here we have an array with five rows and four columns. It has twenty total elements. However we [...]

Multidimensional Arrays

You don’t have to stop with two dimensional arrays. Java lets you have arrays of three, four or more dimensions. However chances are pretty good that if you need more than three dimensions in an array, you’re probably using the wrong data structure. Even three dimensional arrays are exceptionally rare outside of [...]

Unbalanced Arrays

Like C Java does not have true multidimensional arrays. Java fakes multidimensional arrays using arrays of arrays. This means that it is possible to have unbalanced arrays. An unbalanced array is a multidimensional array where the dimension isn’t the same for all rows. IN most applications this is a horrible idea and [...]

Searching

One common task is searching an array for a specified value. Sometimes the value may be known in advance. Other times you may want to know the largest or smallest element.
Unless you have some special knowledge of the contents of the array (for instance, that it is sorted) the quickest algorithm for searching [...]

Sorting

All sorting algorithms rely on two fundamental operations, comparison and swapping. Comparison is straight-forward. Swapping is a little more complex. Consider the following problem. We want to swap the value of a and b. Most people propose something like this as the solution:
class Swap1 {

public static void main(String args[]) [...]

Catching Exceptions

Do you remember this code?
// This is the Hello program in Java
class Hello {

public static void main (String args[]) {

/* Now let’s say hello */
System.out.print(”Hello “);
System.out.println(args[0]);
}

}
Do you remember what happened when [...]

File I/O and Streams

Sometimes you write data to a file instead of the computer screen. Under Unix and DOS you can sometimes do this using the redirection operators < and >. However sometimes you need a more fine-grained approach that writes only certain data to a file while still putting other data on the screen. Or you [...]

Interactively communicating with the user

We’ll begin by writing a very simple program that asks the user for their name and then prints a personalized greeting.
import java.io.*;

class PersonalHello {

public static void main (String args[])
{

byte name[] = new byte[100];
int bytesRead = 0;

[...]

Reading Numbers

Often strings aren’t enough. A lot of times you’ll want to ask the user for a number as input. All user input comes in as strings so we need to convert the string into a number.
Next we promised to write a getNextInteger() method that will accept an integer from the user. Here it is:
[...]

Reading Formatted Data

It’s often the case that you want to read not just one number but multiple numbers. Sometimes you may need to read text and numbers on the same line. For this purpose Java provides the StreamTokenizer class.

Writing a text file

Sometimes you want to save your output for posterity rather merely scrolling it across a screen. To do this we’ll need to learn how to write data to a file. rather than create a completely new program we’ll modify the Fahrenheit to Celsius conversion program to output to a file:
// Write the Fahrenheit to [...]

Reading a text file

Now that we know how to write a text file, let’s try reading one. The following code implements the Unix cat utility in Java. That is it accepts a series of file names on the command line and then prints those filenames to the standard output in the order they were listed.
// Imitate the Unix [...]

Summing Up

If you’ve gotten this far, you’re capable of doing a surprising amount of real work in Java. You may not think so since we haven’t yet talked about a lot of the modern features of Java like most of its object orientation, many of the details of working with applets, or threads. However it’s important [...]

Part 3: Applets

The last chapter was rooted solidly in the 1970’s. It used techniques often referred to as “structured” or “procedural programming” which were popular then. (We skipped right over the most popular innovation of the 60’s and the Basic programmer, spaghetti code). Certain programmers are sometimes said to “Write Fortran in any language,” and that’s more [...]

Hello World: The Applet

The reason people are excited about Java as more than just another OOP language is because it allows them to write interactive applets on the web. Hello World isn’t a very interactive program, but let’s look at a webbed version.
import java.applet.Applet;
import java.awt.Graphics;
public class HelloWorldApplet extends Applet {
public void paint(Graphics g) {
[...]

Examining the Hello World Applet

The Hello World Applet adds several constructs to what we saw in the Hello World Application. Moving from top to bottom the first thing you notice is the two lines:
import java.applet.Applet;
import java.awt.Graphics;
The import statement in Java is similar to the #include statement in C or C++. It pulls in the classes that are contained in [...]

The APPLET HTML Tag

Applets are included on web pages using the tag. The tag is perhaps most similar to the tag. Like needs to reference a source file that is not part of the HTML page on which it is embedded. IMG’s do this with the SRC= parameter. APPLET’s do this with the [...]

Passing Parameters to Applets

The area between the opening and closing APPLET tag is also used to pass parameters to applets. This is done through the use of the PARAM HTML tag and the getParameter method of the java.applet.Applet class.
To demonstrate this we’ll convert HelloWorldApplet into a generic string drawing applet. To do this we’ll need to pass the [...]

Event Tutor Applet

# The following applet is designed to give you some feel for just what event driven programming is like and what the various events you’re likely to encounter are. Whenever an event occurs, the applet responds by printing the name of the event at the command line.
import java.applet.Applet;
import java.awt.*;
public class EventTutor extends Applet {
[...]

Making a List

It is extremely bad form to use System.out.println() in an applet. On some systems this may not work at all. However it has the advantage of being familiar and easy. For more serious work you should actually draw your text in the applet window. There are at least three different ways to do this. For [...]

The Events

In this section we’re going to categorize the events your applet should respond to. You may not always need to respond to each one. For some of the events we’ll also include new methods for the EventTutor applet that show a little more information. When we do you should replace the old method with the [...]

Drawing Rectangles

Next we’ll write an applet that fills the screen with lots of randomly sized and positioned rectangles in the style of Piet Mondrian. In the process we’ll learn the basics of applet graphics. We’re going to take this one step at a time, adding a bit as we go.
In the first applet we’ll just draw [...]

Drawing Lines

# The awt contains several graphics primitives. Rectangles are one and we’ve pretty much beaten them into the ground in the previous section. Lines are another. Within a graphics context there is one key line drawing method, drawLine(int x1, int y1, int x2, int y2). This method draws a straight line between the point (x1, [...]

Taking Action: Threads

# Depending on your operating system and Java-enabled browser you may have noticed that the Mondrian and Flying Line programs tended to hog your CPU. On Windows NT HotJava stopped responding to my commands several thousand iterations into Mondrian, and I had to kill it from the Task List.
The paint loops in both Mondrian and [...]

Bozo Sort

Some of the first compelling Java demos were graphical illustrations of several sorting methods including quick sort, bubble sort and bidirectional bubblesort intended to show off the threading capabilities of Java. That’s nice, but those methods eventually succeed within our lifetime. For an applet that truly puts threading to good use consider the following bozo [...]

Interaction: Mouse and Keyboard Input

You now have the tools to draw a lot of really cool animations and images on your web pages. This alone puts you leaps and bounds beyond the average web page designer. Still that’s only half the point of applets. The other half is interaction with the user. Your applets can accept input from the [...]

Mouse Input: Java Doodle

Here’s a simple applet that lets you doodle with the mouse on an applet.
import java.applet.Applet;
import java.awt.*;
import java.util.Vector;
public class JavaDoodle extends Applet {
Vector points = new Vector();
public void paint(Graphics g) {
int x1, y1, x2, y2;
Point tempPoint;
if (points.size() > 1) {
[...]

Keyboard Input: TypeWriter

Here’s a simple applet that uses the keyDown method to let you type some text.
import java.applet.Applet;
import java.awt.Event;
import java.awt.Graphics;
public class typewriter extends Applet {
int numcols = 80;
int numrows = 25;
int row = 0;
int col = 0;
char page[][] = new char[numrows][];
public void init() {
[...]

The History of Programming

Programming has always been guided by various methodologies. In the early days of computers, computer memories were quite small. Programs had to be loaded in by toggling switches on a panel. In these days it was possible for a programmer to keep track of every memory location and every machine instruction in his or her [...]

Classes and Objects

The primary distinguishing feature of OOP languages is the class. A class is a data structure that can associate the methods which act on an object with the object itself. In pre-OOP languages methods and data were separate. In OOP languages they are all part of classes.
Programming languages provide a number of simple data types [...]

Methods

Data types aren’t much use unless you can do things with them. For this purpose classes have methods. Members say what a class is. Methods say what a class does. For instance our website class might have a method to print its data. If so that would look like this:
class website {
String name;
[...]

Some Advocacy

Unfortunately the object oriented language that took hold was C++. Among much fitter contenders for object languages, notably Smalltalk, C++ had the unique advantage of being downward compatible with the C programmers were already familiar with. Unfortunately this advantage had the huge side effect of forcing C++ to accept all of C’s obfuscated macros, pointer [...]

A Non-Trivial Examples: Complex Numbers

As mentioned in Chapter 2 one of the features needed for serious scientific computation is complex numbers. Unfortunately no popular computer language other than Fortran provides them as a built-in data type. (Actually this is such a common and useful example and was used by so many textbooks that it was recently added to the [...]

toString Methods

Our printing in the last program was quite stilted because we needed to break a complex number into its real and imaginary parts, print them, and then put it all back together again. Wouldn’t it be nice if we could just write:
System.out.println(u);
instead? It turns out we can. All objects have a toString method which is [...]

Polymorphism

So far our methods just do arithmetic on two complex numbers. It’s not uncommon to want to multiply a complex number by a real number. To add this capability to our class we’ll add the following method:
public Complex Times (double x) {
return new Complex(u*x, v*x);
}
Here’s a simple [...]

Scope: Calling the Complex Class From External Classes

Until now we’ve stored almost every program in a single file. This becomes unwieldy as programs grow large. It becomes impossible to manage when more than one person is working on a program. It also loses out on one of the key benefits of OOP, code reusability. As long as all the code for a [...]

The Mandelbrot Set

The Mandelbrot set is a classic application of complex arithmetic. It is the example of a fractal set.
Here and in the future we are going to try to separate the mathematical definition of our data from its display on the screen. In fact we won’t even add the screen display till the second iteration of [...]