Java stands as one of the leading programming languages in the tech world. Image courtesy of funky-data / Getty ImagesEver been curious about how computer programs function? Or have you thought about creating your own programs? Whether you're a 14-year-old aspiring game developer or a 70-year-old who's had a lifelong interest in programming, this guide is for you. In this special edition of Mytour, I'll walk you through the workings of computer programs by teaching you how to write them using the Java programming language.
To help you grasp the basics of computer programming, I'll be making a few assumptions from the outset:
- For this guide, I'll assume you're starting from scratch with computer programming. If you're already familiar with the basics, feel free to skip ahead until you encounter something new.
- I'll also assume you're comfortable with your computer. Specifically, you should know how to edit, copy, delete, and rename files, as well as navigate your system to find information.
- For simplicity's sake, let's assume you're working on a system with Windows 95, 98, 2000, NT, or XP. If you're using a different operating system, you'll still be able to understand the concepts and apply them to your system.
- Lastly, I’m assuming that you have the drive and curiosity to learn.
The necessary tools to start coding in Java are readily accessible online for free. There is a wealth of educational resources available as well, so once you finish reading this article, you can easily continue your learning journey. Java programming can be learned at no cost, with free compilers, development tools, and tutorials. Once you grasp Java, picking up other programming languages becomes much easier, making this a great place to begin.
With all that said, we're ready to dive in. Let's begin our journey!
Understanding Key Terms
As we move forward, remember that I'm assuming you're new to programming. Here are some key terms that will help you understand the concepts we'll cover:
- Computer Program - A computer program consists of a series of commands that instruct a computer on what actions to take. These commands could instruct the computer to perform mathematical calculations, make decisions based on certain conditions, or execute any number of other tasks. Essentially, a computer program is a set of precise directions for the computer, much like a recipe guides a cook or musical notes guide a musician. The computer follows your commands exactly, allowing it to accomplish useful tasks such as managing finances, running a game, or processing documents.
- Programming Language - For a computer to understand the instructions you provide, those instructions must be written in a language that the computer can comprehend -- a programming language. There are various programming languages available, such as Fortran, Cobol, Basic, Pascal, C, C++, Java, Perl, similar to how there are many spoken languages. Although these languages express similar ideas, they do so in distinct ways.
- Compiler - A compiler converts a program written in a human-readable programming language (like Java) into machine-readable code that a computer can execute. You may be familiar with EXE files on your computer, which are the result of compilation. These files contain executables—programs that are ready for the computer to run, having been translated from human-readable code.
To begin programming in Java, you'll need a compiler for the language. The following section will guide you through the steps to download and install the Java compiler. Be prepared, as this process may take several hours, mainly due to the time required to download several large files. You'll also need approximately 40 megabytes of free disk space, so ensure you have the available space before you begin.
Getting the Java Compiler
To set up a Java development environment on your machine (where you'll write computer programs), you need to follow these steps:
- Download a large file containing the Java development environment (including the compiler and other tools).
- Download a separate large file with the Java documentation.
- If you don't already have WinZip (or a similar tool), download and install a file containing WinZip.
- Install the Java development environment on your system.
- Install the documentation.
- Set up a few environment variables.
- Verify that everything is functioning correctly by testing it out.
Before you begin, it's a good idea to create a new folder in your temp directory where we will store the files we'll be downloading. Let's name this folder the download directory.
Step 1 - Download the Java Development Kit (JDK)
Visit the page at http://java.sun.com/j2se/1.4.2/download.html. Click on the "Download J2SE SDK" link to download the SDK software. You'll be prompted with a licensing agreement – click Accept. Next, choose your operating system and save the file to your download directory. This file is quite large and may take several hours to download, especially with a standard phone-line modem. The next two downloads will also be sizable.
Step 2 - Download the Java Documentation
To download the documentation, select your operating system and click the SDK 1.4.1 documentation link.
Step 3 - Download and Install WinZip
If you don't already have WinZip or a similar tool installed on your computer, head to http://www.winzip.com/ to download a trial version of WinZip. Once downloaded, run the EXE file to complete the installation. This will be useful in the next steps for installing the documentation.
Step 4 - Install the Development Kit
Run the j2sdk-1_4_1-*.exe file you downloaded in step 1. The installer will automatically extract and set up the development kit on your system.
Step 5 - Install the Documentation
Follow the instructions for the documentation installation. These will guide you to move the documentation file into the same directory where you installed the development kit. Once you unzip the documentation, it will be placed in the correct location automatically.
Step 6 - Configure Your Environment
As explained on this page, you'll need to modify your path variable. The easiest way to do this is by opening an MS-DOS prompt and typing PATH to check your current path setting. Then, open the autoexec.bat file in Notepad and make the necessary changes to the PATH as outlined in the instructions.
Step 7 - Verify the Setup
At this point, you should be able to open a new MS-DOS window and type javac. If everything is set up correctly, you should see a two-line text output that explains how to use javac. This means you're ready to proceed. If you see the message "Bad Command or File Name", it indicates something isn't set up right. Revisit the installation instructions and check the PATH settings to ensure they are correct. Stay persistent, and as stated in the Programmer's Creed, keep going until you resolve the issue.
Congratulations, you now own a machine capable of compiling Java programs! You're all set to begin creating software!
By the way, among the files you just unpacked is a demo folder filled with interesting examples. Each one is ready to run, so take a look and experiment with them. Many of these examples play sounds, so be sure to have your speakers turned on. To run them, simply find pages named like example1.html and open them in your preferred web browser.
Your First Program

Your first program will be simple and straightforward. It will set up a drawing area and draw a diagonal line across it. To create this program, you will need to:
- Open Notepad and type (or copy and paste) the program code
- Save the file
- Compile the program with the Java compiler to create a Java applet
- Resolve any issues that come up
- Create an HTML page to host the Java Applet you just made
- Run the Java applet
Here is the program that we will use for this demonstration:
import java.awt.Graphics;
public class FirstApplet extends java.applet.Applet
{
public void paint(Graphics g)
{
g.drawLine(0, 0, 200, 200);
}
}Step 1 - Type in the program
Create a new directory where your program will be stored. Open Notepad (or any other text editor that can create .TXT files) and type or paste the program into the Notepad window. Pay attention to this detail: case sensitivity matters. This means that you need to type both uppercase and lowercase characters exactly as they appear in the program. Remember the programmer's creed above. If you don’t type it precisely as shown, the program won’t work.
Step 2 - Save the file
Save the file with the name FirstApplet.java in the folder you created in step 1. Remember, case matters when naming the file. Ensure the 'F' and 'A' are capitalized, while the remaining characters are lowercase, as shown.
Step 3 - Compile the program
Launch an MS-DOS window. Use the 'cd' command to navigate to the directory where FirstApplet.java is stored. Then type the following command:
javac FirstApplet.java
Case matters! If the compilation is successful, the window will remain empty. Otherwise, errors will appear. If there are no errors, a new file named FirstApplet.class will be created in the same directory as FirstApplet.java.
(Ensure the file is saved as FirstApplet.java, not FirstApplet.java.txt. You can easily check this by typing dir in the MS-DOS window to see the file name. If it shows a .txt extension, rename the file to remove it. Alternatively, open Windows Explorer, go to the View menu, select Options, and make sure "Hide MD-DOS File Extensions for registered file types" is unchecked. Then, check the filename in Explorer and rename it if needed.)
Step 4 - Fix any problems
If any errors appear, correct them by comparing your program with the example provided. Ensure they match exactly, and continue compiling until no errors are present. If javac doesn't work, revisit the previous section to troubleshoot your installation.
Step 5 - Create an HTML Page
Now, create an HTML file to display the applet. Open a new Notepad window and input the following code:
<html> <body> <applet code=FirstApplet.class width=200 height=200> </applet> </body> </html>
Save this file in the same directory with the name applet.htm.
[If you're new to HTML, you may want to check out How a Web Page Works. The applet tag is used to embed a Java applet within a web page.]
Step 6 - Run the Applet
In the MS-DOS window, type the following command:
appletviewer applet.htm
You should now see a diagonal line drawn from the top-left corner to the bottom-right corner.
Resize the applet viewer slightly to view the entire line. You can also open the HTML page in any modern browser like Netscape Navigator or Microsoft Internet Explorer to see something similar.
Congratulations, you've successfully created your first program!!!
Understanding What Just Happened

So, what just happened?
To begin with, you wrote a simple piece of code for a Java applet. An applet is a Java program that runs within a Web browser, while a Java application is a standalone program running on your local computer. Java applications are a bit more complex and less common, so we’ll start with applets. After that, we compiled the applet using javac, then created a basic web page to 'contain' the applet. Finally, we ran the applet using appletviewer, but you can also run it directly in a browser.
The program itself consists of about 10 lines:
import java.awt.Graphics;
public class FirstApplet extends java.applet.Applet
{
public void paint(Graphics g)
{
g.drawLine(0, 0, 200, 200);
}
}This is one of the simplest Java applets you can create. To fully grasp its meaning, you'll need to learn a fair amount, especially about object-oriented programming. But for now, since you might be new to programming, I recommend focusing on just one line in this program for the time being:
g.drawLine(0, 0, 200, 200);
This line of code is the heart of the program. It draws the diagonal line. The other parts of the code are just there to support this key line, so we can ignore the supporting code for now. Essentially, we instructed the computer to draw a line from the top left corner (0, 0) to the bottom right corner (200, 200). The computer followed our instructions precisely. That’s the core of programming!
(Note that in the HTML file, we specified the applet's window dimensions in step 5 above, setting both width and height to 200.)
In this code, we called a method (also known as a function) called drawLine and passed it four parameters: (0, 0, 200, 200). The line ends with a semicolon, which functions like a period at the end of a sentence. The method starts with g., indicating that we’re calling the drawLine method on the object named g (which, as you saw a line earlier, is of the class Graphics – we’ll delve deeper into classes and methods in future sections of this article).
A method is simply a command that tells the computer to perform an action. In this case, drawLine instructs the computer to draw a line between the specified points: (0, 0) and (200, 200). Picture the window as having its origin (0, 0) in the upper left corner, with the positive X and Y axes extending to the right and downward. Each dot on the screen (each pixel) corresponds to one increment along the scale.
Try changing the values of the four parameters and experiment. Alter one or more numbers, save your file, recompile it using javac, and then rerun the applet with appletviewer after each modification to see what happens.
What other functions are available aside from drawLine? To find out, check the documentation for the Graphics class. When you installed the Java development kit and unpacked the documentation, one of the files that got extracted is called java.awt.Graphics.html, and it’s stored on your machine. The path to this file on my machine is D:\jdk1.1.7\docs\api\java.awt.Graphics.html. The path on your machine might be a little different, but it will be similar, depending on where you installed everything. Locate and open this file. Near the top of the page, you'll find a section called "Method Index." This section lists all the methods supported by this class. The drawLine method is just one of them, but you'll see many more available.
- Lines
- Arcs
- Ovals
- Polygons
- Rectangles
- Strings
- Characters
Take some time to read through and experiment with these different methods to see what they can do. For instance, try the following code:
g.drawLine(0, 0, 200, 200);
g.drawRect(0, 0, 200, 200);
g.drawLine(200, 0, 0, 200);It will create a box with two diagonals. Be sure to enlarge the window enough to see the entire shape. Experiment with drawing other figures. Also, explore altering the color using the setColor method. Here's an example:
import java.awt.Graphics;
import java.awt.Color;
public class FirstApplet extends java.applet.Applet
{
public void paint(Graphics g)
{
g.setColor(Color.red);
g.fillRect(0, 0, 200, 200);
g.setColor(Color.black);
g.drawLine(0, 0, 200, 200);
g.drawLine(200, 0, 0, 200);
}
}Notice the new import line added on the second line of the program. The output of this code will appear like this:

You may be wondering, "Why did he use Color.red instead of just red, and how did he know to include that second import line?" You learn these things by example. After showing you how to use the setColor method, you now understand that whenever you want to change colors, you need to use Color. followed by the desired color name and include the corresponding import line at the top of your program. If you search for setColor, you'll find a link leading you to the Color class, where you can explore a list of all available color names along with instructions for creating custom colors. This is how programming works—you learn techniques and apply them to future projects, either by reviewing examples, reading documentation, or exploring demo code. If you enjoy discovering and remembering new things, you'll love programming!
In this section, you've learned how to write linear, sequential code—blocks of code that execute method calls starting at the top and progressing down (try drawing one of the lines before the red rectangle, and notice that it gets covered by the rectangle and disappears. This shows the importance of code order). Sequential code is the foundation of any computer program. Experiment with the various drawing methods and see what you can uncover.
Bugs and Debugging
As you start learning programming, you'll soon notice that making mistakes and assumptions is a normal part of the process. These errors often lead to issues like 1) your program not compiling, or 2) generating unexpected results when it runs. These problems are called bugs, and the process of fixing them is known as debugging. In fact, a significant portion of a programmer's time is spent on debugging.
You'll have plenty of chances to create your own bugs, but to get comfortable with them, let's intentionally introduce a few. In your program, try removing a semicolon at the end of a line and then compile it using javac. The compiler will return an error message. This is known as a compiler error, and you must address all such errors before the program can run. Try misspelling a function, omitting a "{" symbol, or leaving out one of the import lines to experience different types of compiler errors. While encountering certain compiler errors for the first time can be frustrating, experimenting with known errors like these will help you become familiar with common issues.
A bug, also called a runtime (or execution) error, occurs when your program compiles successfully and runs, but doesn't produce the expected results. For instance, the following code generates a red rectangle with two diagonal lines across it:
g.setColor(Color.red);
g.fillRect(0, 0, 200, 200);
g.setColor(Color.black);
g.drawLine(0, 0, 200, 200);
g.drawLine(200, 0, 0, 200);In contrast, the following code will only display the red rectangle, which ends up covering the two diagonal lines:
g.setColor(Color.black);
g.drawLine(0, 0, 200, 200);
g.drawLine(200, 0, 0, 200);
g.setColor(Color.red);
g.fillRect(0, 0, 200, 200);The code is nearly identical to the previous one, but it results in a completely different visual output. If your expectation was to see two diagonal lines, then this version has a bug.
Let’s look at another example:
g.drawLine(0, 0, 200, 200);
g.drawRect(0, 0, 200, 200);
g.drawLine(200, 0, 0, 200);This code generates a black-framed box with two diagonal lines, while the following example only produces a single diagonal line:
g.drawLine(0, 0, 200, 200);
g.drawRect(0, 0, 200, 200);
g.drawLine(0, 200, 0, 200);Once more, if you were expecting two diagonal lines, you'll notice that the second code snippet contains a bug (examine the second code carefully to identify what went wrong). This type of bug can be difficult to detect due to its subtlety.
You'll have many opportunities to practice debugging. The average programmer spends about half of their time identifying, tracking down, and fixing bugs. Don't get discouraged when they appear — they're an inevitable part of the programming journey.
Variables
In every program, variables are used to temporarily store pieces of data. For instance, when you prompt a user for a number, you'll store it in a variable so that you can access it later in your program.
Before using variables in a program, they must first be defined (or declared), and each variable needs to be assigned a specific type. For instance, one variable might be declared to hold numbers, while another might hold names. Java is considered a strongly typed language because it requires you to declare variables and specify their types before using them. Some languages don't enforce this. Strong typing helps minimize errors in large programs.
import java.awt.Graphics;
import java.awt.Color;
public class FirstApplet extends java.applet.Applet
{
public void paint(Graphics g)
{
int width = 200;
int height = 200;
g.drawRect(0, 0, width, height);
g.drawLine(0, 0, width, height);
g.drawLine(width, 0, 0, height);
}
}In the program above, we have declared two variables, width and height, both of type int. An int variable can hold integer values like 1, 2, 3, etc. Both variables are initialized to 200, which means they've been given the value 200 right from the start. Alternatively, we could have done this:
int width;
width = 200;
int height;
height = 200;The first approach is simply faster to write.
When you assign a value to a variable for the first time, this is called initializing the variable. A common programming error happens when you forget to initialize a variable. To observe this error, try removing the initialization part of the code (the "= 200" part), and then recompile the program. You'll notice that the compiler will alert you to this issue, which is a great feature. It can save you plenty of time.
Java has two main types of variables -- simple (primitive) variables and classes.
The int type is simple, meaning the variable can store a number and only a number. You declare an int, assign it a value, and use it. On the other hand, classes can hold multiple parts and include methods that make them easier to work with. A prime example of a basic class is the Rectangle class, so let's start with that.
One limitation of the program we've been working on so far is its assumption that the window is always 200 by 200 pixels. What if we wanted to ask the window, "How big are you?" and adjust our rectangle and diagonals accordingly? If you revisit the documentation for the Graphics class (java.awt.Graphics.html), you will see that one of its functions is called getClipBounds. Clicking on the function name will show you the full description. This function doesn’t take any parameters, but it returns a value of type Rectangle. This rectangle contains the width and height of the available drawing area. If you click on Rectangle in the documentation, you'll be directed to the Rectangle class documentation (java.awt.Graphics.html). Looking at the Variable Index section at the top of the page, you’ll find four variables in this class: x, y, width, and height. To solve our problem, we’ll use getClipBounds to get the clip boundary rectangle, then extract the width and height from it and store those values in the width and height variables we defined earlier, like this:
import java.awt.Graphics;
import java.awt.Color;
import java.awt.Rectangle;
public class FirstApplet extends java.applet.Applet
{
public void paint(Graphics g)
{
int width;
int height;
Rectangle r;
r = g.getClipBounds();
width = r.width - 1;
height = r.height - 1;
g.drawRect(0, 0, width, height);
g.drawLine(0, 0, width, height);
g.drawLine(width, 0, 0, height);
}
}When you run this code, you'll notice that the rectangle and diagonals fit perfectly within the drawing area. Additionally, if you change the window's size, the rectangle and diagonals will automatically adjust to the new dimensions. This code introduces five new concepts, which we'll examine now:
- To begin, because we're using the Rectangle class, we need to import java.awt.Rectangle on the third line of the program.
- In this program, we declare three variables. Two (width and height) are of type int, while one (r) is of type Rectangle.
- We call the getClipBounds function to obtain the size of the drawing area. Since it doesn't take any parameters, we don't pass any to it. It returns a Rectangle, so we assign it to the variable r with the line, "r = g.getClipBounds();"
- The variable r contains four parts -- x, y, width, and height, as detailed in the Rectangle class documentation. To access these values, we use the dot operator. So, "r.width" accesses the width value in the Rectangle object r. We store this value in the local variable width. The subtraction of 1 adjusts the dimensions. Try removing the subtraction and see what happens. Alternatively, try subtracting five and observe the difference.
- Finally, we use width and height in the drawing functions.
A frequent question at this point is, "Did we really need to declare separate variables for width and height?" The answer is, "No." You could have directly used r.width - 1 within the drawing functions. However, defining variables helps improve readability, making the code easier to follow. It's a useful habit to adopt.
Java offers several basic variable types. Here are three of the most commonly used ones:
- int - for whole numbers like (1, 2, 3...)
- float - for numbers with decimal points, such as 3.14159
- char - for individual character values like 'a', 'b', 'c...'
You can perform basic math operations on simple data types. Java understands operators like + (addition), - (subtraction), * (multiplication), / (division), and others. For example, if you wanted to calculate the volume of a sphere with a diameter of 10 feet, you could use this code:
float diameter = 10; float radius; float volume; radius = diameter / 2.0; volume = 4.0 / 3.0 * 3.14159 * radius * radius * radius;
The first part of the calculation says, "Take the value in the diameter variable, divide it by 2.0, and store the result in the radius variable." Notice how the "=" symbol means, "Store the result of the expression on the right in the variable on the left."
Looping

Computers excel at handling repetitive tasks, such as performing calculations or executing operations over and over. We've previously learned how to write "sequential blocks of code," and now it's time to explore ways to make a block of code run multiple times.
For instance, imagine I ask you to recreate the grid shown at the top of this page.
A logical first step would be to begin by drawing the horizontal lines of the grid.
One approach to achieve this is by writing a sequential block of code like so:
import java.awt.Graphics;
public class FirstApplet extends java.applet.Applet
{
public void paint(Graphics g)
{
int y;
y = 10;
g.drawLine(10, y, 210, y);
y = y + 25;
g.drawLine(10, y, 210, y);
y = y + 25;
g.drawLine(10, y, 210, y);
y = y + 25;
g.drawLine(10, y, 210, y);
y = y + 25;
g.drawLine(10, y, 210, y);
y = y + 25;
g.drawLine(10, y, 210, y);
y = y + 25;
g.drawLine(10, y, 210, y);
y = y + 25;
g.drawLine(10, y, 210, y);
}
}(For some beginner programmers, the expression "y = y + 25;" may seem strange at first glance. What it does is take the current value stored in the variable y, adds 25 to it, and then stores the result back in y. For example, if y starts at 10, after this line is executed, y will become 35.)
When reviewing this code, most people quickly spot the repetition of the same two lines over and over again. While this isn't too problematic here, imagine how tedious it would become if you needed to create a grid with thousands of rows and columns. To avoid this redundancy, we can use a loop, as demonstrated below:
import java.awt.Graphics;
public class FirstApplet extends java.applet.Applet
{
public void paint(Graphics g)
{
int y;
y = 10;
while (y <= 210)
{
g.drawLine(10, y, 210, y);
y = y + 25;
}
}
}Upon running this program, you will observe that it draws nine horizontal lines, each 200 pixels in length.
The while loop in Java functions by evaluating the condition within the parentheses. It asks, "Is y less than or equal to 210?" If the condition is true, it repeats the actions inside the loop.
- If the answer is yes, Java enters the block of code enclosed within curly braces - "{" and "}". The repetition occurs at the end of the block. Once Java reaches the closing brace, it loops back to the while statement and asks the question once more. This process can repeat several times.
- If the answer is no, Java skips over the block of code within the braces and continues with the rest of the program.
When you run this program, you'll notice that initially y is set to 10. Since 10 is less than 210, Java enters the block, draws a line from (10, 10) to (210, 10), updates y to 35, and loops back to the while statement. Since 35 is still less than 210, it repeats the process, drawing another line from (10, 35) to (210, 35), updating y to 60, and continuing. This repeats until y exceeds 210, at which point the program terminates.
To complete the grid, we can introduce a second loop into the program, like this:
import java.awt.Graphics;
public class FirstApplet extends java.applet.Applet
{
public void paint(Graphics g)
{
int x, y;
y = 10;
while (y <= 210)
{
g.drawLine(10, y, 210, y);
y = y + 25;
}
x = 10;
while (x <= 210)
{
g.drawLine(x, 10, x, 210);
x = x + 25;
}
}
}The while loop in Java consists of three main parts:
- There is an initialization step where y is set to 10.
- Next, an evaluation step occurs inside the parentheses of the while loop.
- Finally, there is an increment step within the loop that increases the value of y.
Java offers a more concise way to achieve the same result using a for loop, which is often more compact than a while loop. If you have a while loop like this:
y = 10;
while (y <= 210)
{
g.drawLine(10, y, 210, y);
y = y + 25;
}The equivalent for loop would look like this:
for (y = 10; y <= 210; y = y + 25)
{
g.drawLine(10, y, 210, y);
}The for loop primarily helps by simplifying your code. It condenses the initialization, condition evaluation, and increment steps into one line, making the program more concise without changing the functionality. It’s essentially about writing shorter programs.
Now, while we’re discussing loops, here are two quick observations to keep in mind:
- In many situations, you could start by initializing y to 210 and then reduce it by 25 with each loop iteration. The condition would check if y is greater than or equal to 10. It's all up to you. While most people find it simpler to add than subtract mentally, you might prefer the opposite approach.
- Pay attention to the increment step. If you were to accidentally omit the statement "y = y + 25;" in the loop, the value of y would stay fixed at 10, never reaching 210, and causing an endless loop. This situation is known as an infinite loop, a fairly common programming error.
For some hands-on experience with loops, try creating programs that draw the following shapes:

