Download as pdf or txt
Download as pdf or txt
You are on page 1of 16

Fundamentals of the Java Programming Language

Lesson II
Lesson II: Development and Testing of a Java Program

The focus of this lesson is to provide you with an understanding of the basic structure of a
Java program. We will introduce you to the elementary concepts that will not only allow you
to understand simple programs but also create your very own programs.

Objectives of Lesson II

❖ To write and run a simple Java program


❖ To understand the basic structure of a program
❖ To define the structure of a class
❖ To demonstrate some of the basic naming conventions

Getting Started

To create, compile and run Java programs, you will need to download and install a few tools
for your computer. Specifically, you will need to download two pieces of software. The first is
called the Java Development Kit (JDK) and the second is an Integrated Development
Environment (IDE) called NetBeans.

The JDK is available for download by any developer on ​Oracle’s website​. Oracle is the
software company that owns Java. The JDK essentially comes with two main tools: the Java
Runtime Environment (JRE) and a Java Compiler (usually called javac).

The JRE is responsible for all the variable types and built-in functions (such as the ​println​()
function). The JRE also includes a Java Virtual Machine (JVM) which allows Java code to
run on any device/platform, such as, Windows, Mac, Android etc. Most computers already
have the JRE installed as it is needed to run Java applications that appear on websites,
however, to develop our own programs and Java applications, we need a second tool, the
Java Compiler, commonly referred to as javac.

As previously mentioned, a compiler is a special type of program that translates


programming language code into code that a computer can understand and execute.
Computers, at their most basic level, only react to electronic signals, therefore, seeing
functions, such as the Java p​ rintln​() function, doesn’t mean anything to them. The code that
we write needs to be translated into machine code that computer circuitry can interpret and
execute.
Figure 1: How Java code is compiled

As indicated by Figure 1, our Java code is passed to the Java compiler, which translates our
Java program into to bytecode. This in turn is passed to the JVM which does the translation
of bytecode to machine code. Machine code is the code that your computer understands,
hence, your computer can now execute your code and display the output (if any) to your
computer screen.

Installing the Java Development Kit

Before downloading and installing the JDK from Oracle, you may want to verify if it’s already
installed on your system. To do this, open a command window (which you can find by typing
cmd​ in the Windows search bar) and type in the following (hit ENTER afterwards):

java ​-​version
If you have the Java Development Kit installed on your computer, you should see the
following (along with some additional information):

java version ​"​1.8​.​0_121"

This means that the JDK version 8 is installed. The version number comes after the initial
“1.” If you receive a “java version not found” or “. . . is not recognized as an internal or
external command, operable program or batch file” message, then it means you probably do
not have the JDK installed.

Visit the following URL to download the Java Development Kit:

http://www.oracle.com/technetwork/java/javase/downloads/index.html

Select the Java download button. Be sure to download the JDK only and not Netbeans on
the right.
Click the download button for the JDK, and you should be redirected to the next page where
you can choose the appropriate build to download - according to your computer
specifications. For example, if you have a 64-bit Windows OS, then choose “Windows x64”
and if you have a 32-bit operating system then choose "Windows x86."

You will need to accept the license agreement before your download can begin. Be sure to
download the full version. There will be a “Demos and Samples” version, which you can
ignore. Once the download has been completed, proceed to install it - as you would install
any other application i.e. double-click on the downloaded application and follow the prompts.
At this point, you’re already ready to start writing and running Java programs (see the
Executing Java Programs from CMD document for more information), however, for ease and
simplicity, we will be downloading an Integrated Development Environment (IDE) called
NetBeans. An IDE is a software application that has utilities that help programmers to edit
and run code. You can read up on IDEs​ ​by clicking here​.

Installing the NetBeans IDE

NetBeans is a software development environment created by the Apache Software


Foundation. It was created specifically to provide automatic generation of software
visualizations to improve the comprehensibility of software. Many learning institutions
ranging from high schools to universities utilize this IDE for its simplistic design and excellent
performance.

The following steps outlines the download and installation steps for the NetBeans IDE:

1. Download the NetBeans IDE 8.2 from this link: ​NetBeans 8.2​. The installation
package is 92 MB. Once the download is complete, double-click and open the
netbeans-8.2-javase-windows.exe installation file. The installation package will
display the logo shown in Figure 2.

Figure 2: NetBeans 8.2 installation file


2. Windows will prompt for user permission to open the installation file; click the “​Y​es”
button when you receive this prompt
3. The NetBeans IDE installer will begin configuration of the installer; this is shown in
Figure 3.

Figure 3: Configuration of the NetBeans installer

4. After the configuration of the installer is complete, the first window of the installation
​ xt” button to begin the installation process
process will be displayed. Click the “​Ne
5. A license agreement will be displayed. Click the checkbox and press the “​Ne ​ xt>”
button.
6. You will be prompted to choose the installation folder and JDK for the NetBeans IDE
as shown in Figure 4. A default option will already be selected; simply press the
“​N​ext>” button.

Figure 4: Installation folder and JDK option

7. A short summary of your installation options will be displayed. Click the “​I​nstall”
button.
8. The NetBeans package will now begin installing; this will take approximately 18
minutes to complete.
9. Once the installation is complete, click the “​F​inish” button.

Your First NetBeans Project

This section will provide you with an elementary and quick introduction to the NetBeans IDE
environment by walking you through the development of a simple "Hello World" Java console
application. You will first set up the Java project and then move on to coding.

NetBeans Project Setup

A NetBeans project setup consists of the following five steps:

1. Start NetBeans IDE on your computer.


2. In the IDE, choose File > New Project, as shown in Figure 5 below.
Figure 5: Creating a New Project

3. In the New Project wizard, select the “Java” category and select “Java Application” as
shown in Figure 6 below. Then click “Next.”

Figure 6: Creating a Java Application

4. You will now be taken to the “Name and Location” page. On this page, do the
following as shown in Figure 7.
a. In the “Project Name” field, type the name “HelloWorld.”
b. Leave the “Use Dedicated Folder for Storing Libraries” checkbox unselected.

Figure 7: : “Name and Location” window

5. Click Finish.

Your project is now created and opened in the IDE. As highlighted on Figure 8, you should
see the following components in the NetBeans coding environment:

A. The “Projects” window, which contains a tree view of the components of the project.
B. The “Source Editor” window with a file called “HelloWorld” open.
C. The “Navigator” window, which you can use to quickly navigate between elements
within a selected class.
Figure 8: The NetBeans coding environment

Now that you have been introduced to the NetBeans environment, it’s time to write your first
program.

Printing “Hello World!”

Since you have left the “Create Main Class” checkbox selected in the “New Project” setup
wizard, the NetBeans IDE has created a skeleton main class for you by default. You can
now add the "Hello World!" message to the skeleton code by replacing the line: “​// TODO code
application logic here” ​with the following line of Java code:
System.out.println("Hello World!");

Your file should now look similar to the code sample in Figure 9.

Figure 9: Printing out the text “Hello World!”


Because of the NetBeans IDE's “Compile on Save” feature, you do not have to manually
compile your project in order to run it in the IDE. Once you save a Java source file, the IDE
automatically compiles it. Simply press the combionation Ctrl+S to save and compile the
code. Then press the F6 button of your keyboard to run the code. You can alternatively
select “Run > Run Project” from the NetBeans menu.

Once you have run your code, the line “Hello World!” will be printed on the NetBeans Output
tab - this is displayed in Figure 10.

Figure 10: Successful printing of the text “Hello World!”

Congratulations! You have successfully written your first Java program.

Components of A Java Class

As discussed in the previous lesson, to construct a house, you will first need a blueprint.
Similarly, the logic follows for classes and objects i.e. once you have a class (or blueprint),
you can create as many objects as you need. For example, we can use our house blueprint
to make a house that is blue with a red roof or a house that is green with a white roof. Each
variation is an instance of our class (blueprint).

In Java, there are four major components of a class:

1. The ​class declaration (​required)​ . A class is the blueprint from which individual
objects are created. The convention in Java is to begin the class name with a capital
letter. The class in Java takes the following form:

class​ ​Example{
/* Class body to be place between the curly braces. The body can include
variables, methods, comments etc.*/
}

As you can see by the code, a class declaration in Java isn’t that complex. All that is
needed is the ​class k​ eyword and an identifier for the class. The identifier (​Example ​in
this case) is basically the name of the class, and as stated, the filename is usually
named after this identifier.

The other important concept to note about the class declaration is that it can be
preceded by a modifier, such as, public, abstract, or final:

public​ ​class​ Example{


// A class modifier affects the runtime behaviour of the class
}
In most cases, you will use the public modifier. This modifier allows the methods,
blocks etc. declared inside the public class to be accessed from any other class in
the same program/package.

Note: If several words are compounded to form the class name, then the class name
is camel-cased i.e. the first letter of each word should be in upper case:

public​ ​class​ ​CamelCasedExample{

2. Attributes/Fields​ (​optional​)

Attributes (more generally referred to as variables) represent the state of the object
because they store the information about the object. For our example, of the clothing
store, our shirt object will have the attributes of price, size, colour etc.

3. Methods ​(​optional)​

Methods (also referred to as functions in other programming languages) are a


collection of statements that perform functions/operations. An object’s behaviour is
defined methods. For example, if we have a Cat class, then the behaviour, such as
scratching, eating, jumping etc. of each individual cat produced from the Cat class
would be implemented as methods.

Together, methods and fields are referred to as the ​members ​of the class. The fields
hold the state of the program, and the methods operate on that state.

Methods are optional in classes. However, you need to have a method named ​main
in at least one class. The following is what must appear in a Java program:

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

This method must appear within a class:

public​ ​class​ ​HelloWorld​ ​{​ ​// class declaration

public​ ​static​ ​void​ main​(​String​[]​ args​)​ ​{​ ​// main method

// Code to be executed is inserted here

}
}

The reason for the main( ) method in at least one Java class is because the Java
compiler begins processing from the main( ) method when the program is executed.

Note: The convention for naming methods in Java is to begin with a lower case letter.
If several words are compounded to form the name of the method, then the
camel-casing style applies, with the first letter of each word, starting from the second
word, being in uppercase:

public​ ​static​ ​void​ methodCompoundExample(){

4. Comments

Comments are inserted for developers to understand the code. They do not affect the
execution of the program and can be inserted anywhere in a program. The Java
compiler will simply ignore them when the program is executed. Comments come in
two forms - either in single or multiple lines:

// This is a single line comment.

/* This is a multi-line comment. Multi-line comments can span over multiple lines.
Any​ text placed between ​/* and * / will be ignored by the program at execution */

Executing Java Programs from The Command Line

To compile and execute Java technology programs from the command line, you will need to
change your environment variables so that your computer knows where to find your Java
Development Kit. To change your environment variables, navigate to your ​System ​window
by right-clicking on your start menu and selecting ​System​. Next, select ​Advanced system
settings​. This will bring up your ​System Properties ​window and from here, you can select
the ​Environment Variables ​button. Environment Variables are a set of dynamic named
values that can affect the way certain processes on your computer will behave.

Figure 11: The Windows Command Prompt

The ​Environment Variables ​button will open a window that shows all the variables that your
computer recognises. We’re interested in the ​PATH ​variable, so select the ​PATH ​variable
and click edit. We’re going to be adding a new path variable for the Java Development Kit.
But, before you may proceed, make sure you’ve followed the ​Getting Started ​guide and
have downloaded and installed the relevant programs.

With the JDK installed, you can go ahead and select the ​New ​button in the ​Edit
environment variable ​window. You can name the variable whatever you like for now and
press ​Enter ​on your keyboard. With the variable you’ve just created still selected, click the
Browse ​button. You will need to navigate to the ​bin ​folder in your JDK. This path should be
similar to the following:

C​:​\Program ​Files​ ​(​x86​)​\Java\jdk1​.​8.0​_121\b​in

With the ​bin ​folder selected, you can press ​OK and the full path to the ​bin ​folder should
appear in your ​Edit environment variable ​window list. If this is so, then you’re all set. Select
OK ​save your changes and also select ​OK ​on your ​Environment Variables ​window.

Java code can be written in any text editor or IDE. We’re going to be writing some code and
compiling and executing it from the command line. So, you may copy and paste the following
code into your text editor or an IDE of your choice (the IDE you would have is IntelliJ if
you’ve followed the ​Setup Guide​):

public​ ​class​ ​HelloWorld​ ​{​ ​// class declaration

​public​ ​static​ ​void​ main​(​String​[]​ args​)​ ​{​ ​// main method


​System​.​out​.​println​(​"Hello world!"​);

}
Save the file as a Java program. The file should be called ​HelloWorld.java​. Our filename
has to match our class name. If you look at the code, our Java class is named HelloWorld.
Our program will not compile if the filename does not match the class. Note that Java
programs have the .java extension.

With the code above saved as a Java program, open a command window in the same
location as the Java program. To open a command prompt window in the same location as
the Java program, you can simply hold down the Shift key and right-click on an empty space.
You should see the option to ​Open command window here​.

With the command window opened, we’re ready to compile and execute our program.
Firstly, to compile, you can type in the following and press ​Enter​:

javac ​HelloWorld​.​java

If the compilation is successful, your cursor in the command line will simply move on to the
next line. If you receive any errors, it probably means that your computer cannot find the
Java compiler, hence, make sure you’ve correctly followed the steps above to install a
compiler.

Next, you can execute your program using the following command and you should see
“Hello world!” printed out:

java ​HelloWorld

Lesson Summary

❖ Identifiers are names for naming elements such as variables, methods and classes.
❖ Class declaration is essential!
❖ Remember to name your classes and methods according to the naming convention
i.e. camel case.
❖ You can use comments to make your program more understandable especially for
others who read it.
❖ The name of a class must correspond exactly to the name of the file you save it in
​Formative Assessment

To progress to the next lesson, you are required to complete the following:

1. Name the four components of a class.


2. What is the purpose of methods in a class, with respect to objects?
3. What is the convention for naming of the following:
a. A Java class
b. A Java method
4. Create a new Java class called ​GoodbyeWorld. ​Insert the main method and add a
println( ) statement that prints out the text “Goodbye, World!”
a. Compile the class on the command line
b. Execute the class on the command line
5. What are the commands for compiling and running a Java program from the
command line?

You might also like