Programming in Java

Compiling and Running Java

This section shows you how to download and install the Java compiler from Sun Microsystems, and some tips on configuring the editor TextPad.
(read more)

Hello World!

It is a simple program to check for proper installation of your compiler, and your execution script. It simply displays the famous greeting "Hello World!" on the screen.

(read code)

GUI: JTextArea with scrolling

This example uses an output text area that is scroll-bars enabled, so that voluminous text may be viewed in a small area/window.

(read code)

GUI: JLabel, JTextField and JButton

A typical applet requires the input of information to be processed, and the output of results. This example does just that, using two text fields and a button.

(read code)

Exception handling in Java

A short explanation of how Java handles exceptions, with an illustrative example.

(read code)

Matrix Multiplication

It presents a matrix multiplication function and provides an example of the multiplication of a 4x3 matrix by a 3x4 matrix to give a 3x3 matrix as the displayed result.

(read code)

Tax Calculation

(courtesy of Yvonne Cheng)

This Java program calculates Goods and Services Tax (GST at 7%), Provincial Sales Tax (PST 7.5% on the subtotal), and the total amount. Two cases are implemented: GST only or GST+PST.

(read code)

The Knight's Tour

This is a rather well-known problem suggested by the mathematician Euler. The process is to put a Knight on a particular square of an 8x8 chessboard and let it wander, land on each square once and only once. The object is to have the knight land on everyone of the 64 squares.

(read code)

Shapes

An example demonstrating inheritance, polymorphism, graphics and components.
(read code)

A dictionary

A lookup Java applet that demonstrates the use of String comparisons, binary search, opening and reading of disk files, array of Strings, etc.
(read code)

Palindromes

A program that uses many of the String manipulation functions to test if a given sentence is a palindrome.
(read code)

Word Puzzles

Someone asked you to solve math problems like:

SEND+MORE=MONEY

where each letter represents a digit, and the resulting numbers add up!

Now you can surprise your friends with solutions from here.If multiple solutions exist, they will be all listed. Note that each digit may be used once and only once in a solution.

If you'd like to have the source program, write me at the address at the bottom of the page, and I will gladly send you the Java code without obligations.

An excellent site on the subject, including a puzzle generator, can be found at the following address: Alphametics

Java GUI

Java has a very rich set of Graphics User-Interfaces (GUI) that allows the developer to handle most cases of user-interaction. Most of the interfaces have been stored as predefined classes, with the appropriate methods and constructors. As a developer, we need to master with these tools, first by getting familiar with the documentation (Java API documentation), the constructors and methods.
Many of us find that it is far easier to work with standard examples, which shows us how to approach each particular tool, and thus shorten the learning curve. This example will do just that: provide an example for each major GUI. Just click the following link.

The File class

The File class helps the user to manage the multitude of files or directories used in a Java application. The constructor does not verify the existence of the file or directory.

The constructors are:
File(String path);
File(String dir, String path);
File(File dir, String path);

Here are some examples:
File f1=new File("/tmp","abc"); // on a Unix OS
File f2=new File("C: \\temp"); // Windows platform

Once the file object is created, numerous methods are available to help manage the files and directories. The purpose of the methods are self-explanatory, with certain exceptions.
boolean exists();
String getAbsolutePath();
String getCanonicalPath(); // . and .. are resolved
String getName();
String getParent();
boolean isDirectory();
boolean isFile();
String[] list(); // lists file/dir. in the dir. represented by the object
boolean canRead();
boolean canWrite();
boolean delete(); // attempts to delete the file/dir
long length(); // returns length of the file
boolean mkdir(); // creates directory described by the object
boolean renameTo(File newname);

Using these methods, it would be relatively easy to create a routine to recurse through all files subdirectories to take any appropriate actions required.


BigInteger class

Since version 1.4, Java has a BigInteger class that computes elementary arithmetic integral operations with arbitrary precision. The number of digits of precision is determined automatically, so there is no overflow.
The constructor takes a String argument, and the toString() method converts a BigInteger back into a String.
Methods for the four arithmetic operations are provided. Two methods are provided for division, namely divide() for simple truncation (I1/I2), and divideAndRemainder() for quotient and remainder (I1/I2, I1%I2). Other methods include signum(), abs(), bit manipulations, comparison, max(), min(), mod(), pow(), negate(), as well as a full set of conversion to other types.
Example code: BigInteger Calculator

BigDecimal class

Similar to the BigInteger class, Java has a BigDecimal class that performs decimal calculations with arbitrary precision. Internally, most calculations are done in integers, with an appropriate scale factor to revert to a decimal value.
One of the constructors takes a String argument, and in addition to the toString() method, the toPlainString() and toEngineeringString() are available.
Methods for the four arithmetic operations are provided. The division method requires a predetermination of the precision using the setScale() method, which also specifies one of the eight rounding options available. Other methods include signum(), abs(), bit manipulations, comparison, max(), min(), mod(), pow(), negate(), as well as a full set of conversion to other types.
The example code includes a square root method using the Newton's algorithm.BigDecimal Calculator

Weigh the balls

Suppose there are 12 identical looking balls one of which is different in weight. It can be lighter or heavier that the normal balls.
Given a balance that can only compare the weight of the balls (heavier, lighter or equal), can you locate the defective ball from the lot (numbered 1 to 12) with just three weighings?
You can try your hand with this applet, the answer is in the comments of the source code.

Checking ISBN

ISBN is a unique number assigned to each book for identification purposes. If we mistakenly write a wrong number, it will cause a lot of trouble. Fortunately there is a mechanism built-in to the number to enable validation of the number.
For more details and an example Java applet source code , or to simply execute theapplet.

updated 2007-03-11