Com 121 Intro To Java Prgrming Theory
Com 121 Intro To Java Prgrming Theory
LECTURER :
ONI M. S
CHAPTER ONE
HISTORY OF JAVA
Java is an Object Oriented Programming language developed by the team of James Gosling,
Patrick Naughton, Chris Warth, Ed Frank, and Mike Sheridan at Sun Microsystems in 1991. This
language was initially called “Oak” but was renamed “Java” in 1995. The name Java came about
when some Suns people went for a cup of coffee and the name Java was suggested and it struck.
Java was developed out of the rich experiences of the professionals who came together to design
the programming language thus, it is an excellent programming language. It has similar syntax to
C/C++ programming languages but without it complexities. Java is an elegant programming
language.
Java was initially developed for programming intelligent electronic devices such as TVs, cell
phones, pagers, smart cards etc. Unfortunately the expectations of the Suns team in this area did
not develop as they envisaged. With the advent of the in the boom of the Internet and the World
Wide Web (WWW), the team changed their focus and Java was developed for developing web
based applications. It is currently being used to develop a variety of applications.
Why Java?
Thousands of programmers are embracing Java as the programming language of choice and
several hundred more will joining before the end of the decade. Why is this so? The basic
reasons for these are highlighted below:
a. Java Applications: These are stand-alone applications such word processors, inventory
control systems etc.
b. Java Applets: These programs that are executed within a browser. They are executed on
the client computer.
c. Java Serverlets: These are server side programs that are executed within a browser.
In this course we will limit ourselves to only the first two mentioned types of Java programs –
applications and applets.
a. Encapsulation: Encapsulation is a methodology that binds together data and the codes
that it manipulates thus keeping it safe from external interference and misuse. An object
oriented program contains codes that may have private members that are directly
accessible to only the members of that program. Also it may have program codes
(methods) that will enable other programs to access these data is a uniform and controlled
fashion.
b. Polymorphism: Polymorphism is a concept whereby a particular “thing” may be
employed in many forms and the exact implementation is determined by the specific
nature of the situation (or problem). As an example, consider how a frog, lizard and a fish
move (“the interface”) from one place to another. A frog may leap ten centimeters, a
lizard in a single movement moves two centimeters and a shark may swim three meters in
a single movement. All these animals exhibit a common ability – movement – expressed
differently.
c. Inheritance: Inheritance is the process of building new classes based on existing classes.
The new class inherits the properties and attributes of the existing class. Object oriented
programs models real world concepts of inheritance. For example children inherit
attributes and behaviors from their parents. The attributes such as color of eyes,
complexion, facial features etc represent the fields in an java. Behaviors such as being a
good dancer, having a good sense of humor etc represent the methods. The child may
have other attributes and behaviors that differentiate them from the parents.
* HelloWorld.java
* Displays Hello world!!! to the output window
*
*/
Note: The file containing this class must be saved using the name HelloWorld.java. The name of
the file and the class name must be the same both in capitalization and sequence. Java is very
case sensitive thus HelloWorld is different from helloworld and also different from
HELLOWORLD.
The next part of the program is the declaration of the main method. Methods are used for
carrying out the desired tasks in a Java program, they are akin to functions used in C/C++
programming languages. The listing:
public static void main( String[] args )
{
is the main method definition header. It starts with the access modifier public, followed by the
keyword static which implies that the method main( ) may be called before an object of the class
has been created. The keyword void implies that the method will not return any value on
completion of its task. These keywords public, static, and void should always be placed in the
sequenced shown.
Any information that you need to pass to a method is received by variables specified within the
set of parentheses that follow the name of the method. These variables are called parameters. If
no parameters are required for a given method, you still need to include the empty parentheses.
In main( ) there is only one parameter, String[] args, which declares a parameter named args.
This line outputs the string "Java drives the Web." followed by a new line on the screen.
Output is actually accomplished by the built-in println( ) method. In this case, println( )
displays the string which is passed to it. As you will see, println( ) can be used to display
other types of information, too. The line begins with System.out. While too complicated to
explain in detail at this time, briefly, System is a predefined class that provides access to the
system, and out is the output stream that is connected to the console. Thus, System.out is an
object that encapsulates console output. The fact that Java uses an object to define console
output is further evidence of its object-oriented nature.
As you have probably guessed, console output (and input) is not used frequently in
real-world Java programs and applets. Since most modern computing environments are
windowed and graphical in nature, console I/O is used mostly for simple utility programs and for
demonstration programs. Later you will learn other ways to generate output using Java, but for
now, we will continue to use the console I/O methods. Notice that the println( ) statement ends
with a semicolon. All statements in Java end with a semicolon. The reason that the other lines in
the program do not end in a semicolon is that they are not, technically, statements.
The first closing brace -}- in the program ends main( ), and the last } ends the HelloWorld
class definition; it is a good practice to place a comment after the closing curly brace. The
opening and close brace are referred to as a block of code.
One last point: Java is case sensitive. Forgetting this can cause you serious problems. For
example, if you accidentally type Main instead of main, or PrintLn instead of println, the
a. Enter the source code using a text editor. He file must be saved using the file extension .java.
b. Use the Java compiler to convert the source code to its bytecode equivalent. The byte code
will be saved in a file having the same name as the program file with an extension .class. To
compile our HelloWorld.java program, type the following instructions at the Windows
command prompt (c:\>): javac HelloWorld.java
The bytecodes (.class file) will be created only if there are no compilation errors.
c. Finally use the Java interpreter to execute the application, to do this at the Windows command
prompt (c:\>) type: java HelloWorld. (You need not type the .class extension)
Note: Other programs, called Integrated Development Environments (IDEs), have been created
to support the development of Java programs. IDEs combine an editor, compiler, and other Java
support tools into a single application. The specific tools you will use to develop your programs
depend on your environment. Examples of IDEs include NetBeans, Eclipse, BlueJ etc.
We will employ simple graphical classes – JOptionPane to repeat the same programs which we
implemented in week one. In the program presented in week one the output was presented to
the windows command prompt.
The JOptionPane class (javax.swing package) enables the user to use its static methods
showInputDialog and showMessageDialog to accept data and display information graphically.
The HelloWorldGUI.java which implements JOptionPane static methods for displaying hello
world to the user is presented below:
Line 7 we imported he JOptionPane class so that the JVM will ensure that we use it promperly.
The class definition header is presented in line 9. This is followed by the main method header
which must be mus be written this way it is presented in line 10. Two string variables are used,
one for displaying output – msg – and the other for input –ans-. The Graphical message is
A data type defines a set of values and the operations that can be defined on those values.
Data types in Java can be divided into two groups:
Data types are especially important in Java because it is a strongly typed language. This means
that all operations are type checked by the compiler for type compatibility. Illegal operations
will not be compiled. Thus, strong type checking helps prevent errors and enhances reliability.
To enable strong type checking, all variables, expressions, and values have a type. There is no
concept of a “type-less” variable, for example. Furthermore, the type of a value determines what
operations are allowed on it. An operation allowed on one type might not be allowed on another.
Java strictly specifies a range and behavior for each primitive type, which all implementations
of the Java Virtual Machine must support. Because of Java’s portability requirement, Java is
uncompromising on this account. For example, an int is the same in all execution environments.
This allows programs to be fully portable. There is no need to rewrite code to fit a specific
platform. Although strictly specifying the size of the primitive types may cause a small loss of
performance in some environments, it is necessary in order to achieve portability.
There are eight primitive data types in Java: four subsets of integers, two subsets of floating
point numbers, a character data type, and a boolean data type. Everything else is represented
using objects. Let’s examine these eight primitive data types in some detail.
Arithmetic Operators
Arithmetic operators are special symbols for carrying out calculations. These operators enable
programmers to write arithmetic expressions. An expression is an algebraic like term that
evaluates to a value; it comprises of one or more operands (values) joined together by one or
more operators. Below is a summary of Java arithmetic operators in their order of precedence,
that is, the order in which the arithmetic expression are evaluated.
Algebra :
Java: (x + y + z)/3;
This expression calculates the average of three values. The parentheses is required so that the
values represented by x, y and z will be added and the result divided by three. If the parentheses
is omitted only z will be divided by three because division has a higher precedence over
addition.
Algebra: y = mx + c
Note: the order of precedence may be overwritten by using parentheses, that is to say if we
desire addition before multiplication or division for example we can include the that part of the
expression in parentheses. In the above expression, if x - y is written as (x – y), then the value
represented by the y will be subtracted from that of x then the result will be divided by w.
Exercises
Show the order of execution the following arithmetic expressions and write their Java
equivalents:
i.
ii.
iii.
iv.
v. T= 4r + d mod 4
Pertinent data about any object can be gathered and used to represent attributes (fields) and
tasks the objects can perform (methods) by using a well defined interface. Once a class has been
declared several objects can be created from it. The objects protect their own data and it cannot
be directly accessed by other objects.
In the next section we will summarized the rules for creating variables in Java.
a. Variables names may start with and alphabet (a-z / A-Z) and he remaining characters may
be, an underscore (_) or a dollar sign, or a number for example sum, counter, firstName, bar2x
amount_Paid are all valid variable names. 9x, 0value are invalid.
b. Embedded blank spaces may not be included in variable names though an underscore
may be used to join variable names that comprises of compound words. Example x 10 is not
valid, it could be written as x_10 or x10.
c. Reserved words (words defined for specific use in Java) may not be employed as
variables names. Example loop, do, for, while, switch are reserved.
d. Special symbols such as arithmetic operators, comma (,), ?, /, ! are not allowed.
e. Variable name may be of any length.
Exercises: Study the variable names below and indicate whether they are valid or not. If invalid
give reasons.
a. &maxium ____________________________
b. X ___________________________________
c. Absolute temperature ___________________
d. Money _______________________________
e. 30yearold ______________________________
f. initVolume _____________________________
Variable Declaration
Variable may represent values that are expected to change or not during the execution of a
computer program. When declaring variable names the scope (visibility) of variables from other
part of the program may be specified, the type of data that should be stored in the area of
memory.
Variable names may also represent either primitive data or reference data. The general form for
creating or declaring variable is presented below.
Alternatively the initial values to be stored in the memory may be specified when declaring the
variables. The general form for declaring and initializing the variables is presented below:
Note: we declaring variables in a method (e.g. main method) do not include the access
modifiers because all variables declared in methods are implicitly private hence localized to that
method. The examples given above can be used to create instance variables.
Programming in any programming language is not a task that should be trivialized as mere entry of code into
the computer. In order to develop robust and efficient applications the
developer/programmer must follow certain steps. Most beginning programmers simply start keying in code,
for simple applications this may be ok, for most real life applications that may include hundreds of classes
and codes spanning thousands of line such an approach to programming is as good as a Mission Impossible.
In this chapter we will introduce the basic steps that are to be employed when developing a Java program.
Programming basically involves problem solving – that is we write programs to efficiently and effectively
meet the needs of the users.
Problem solving
The purpose of writing a program is to solve a problem. Problem solving, in general, consists of
multiple steps:
a. Understanding the problem.
b. Breaking the problem into manageable pieces.
c. Designing a solution.
d. Considering alternatives to the solution and refining the solution.
e. Implementing the solution.
f. Testing the solution and fixing any problems that exist.
The first step, understanding the problem, may sound obvious, but a lack of attention to this
step has been the cause of many misguided efforts. If we attempt to solve a problem we don’t
completely understand, we often end up solving the wrong problem or at least going off on
improper tangents. We must understand the needs of the people who will use the solution.
These needs often include subtle nuances that will affect our overall approach to the solution.
Our first inclination toward a solution may not be the best one. We must always consider
alternatives and refine the solution as necessary. The earlier we consider alternatives, the easier it
is to modify our approach.
Implementing the solution is the act of taking the design and putting it in a usable form. When
developing a software solution to a problem, the implementation stage is the process of actually
writing the program. Too often programming is thought of as writing code. But in most cases,
the final implementation of the solution is one of the last and easiest steps. The act of designing
the program should be more interesting and creative than the process of implementing the design
in a particular programming language.
Finally, we test our solution to find any errors that exist so that we can fix them and improve the
quality of the software. Testing efforts attempt to verify that the program correctly represents the
design, which in turn provides a solution to the problem.
Throughout this text we explore programming techniques that allow us to elegantly design and
implement solutions to problems. Although we will often delve into these specific techniques in
detail, we should not forget that they are just tools to help us solve problems.
Let us consider a simple problem and use it to explain these concepts in some detail. Let us
design and write a program to calculate the sum of any three integer numbers and calculate their
average.
The task before us is quite simple enough to understand. To know what we are to do we can
begin by asking ourselves the ‘what’ question. What are we (or in effect the program) expected
to do? What are the major processes involved in calculating the sum and average of any three
numbers? These could be summarized as follows:
Next, we look at each of these steps and see if we break them and refine them as necessary; from
there onwards we plan how we will implement our solution. This is sometimes described as
asking the how question. How can we achieve the tasks we have identified and if necessary
refine the step.
Considering step ‘a’ we do not need to break it down. Let us implement this in our program
using dialog boxes.
Then step ‘b’ - calculate the average – how do we calculate average of three integer numbers?
This can be broken down into two steps that is:
The resulting value – average – may be an integer value or a floating point value. This being the
case we would declare average as double.
Finally, we consider the step c, that is, displaying the result. We will display the numbers added
and then the average using dialog boxes also.
a. First we must be able to accept any three numbers from the user.
b. Calculate the average.
i. Add up the three numbers to calculate their sum.
ii. Divide the sum by three to calculate the average.
c. Display average.
/*
* AverageThreeIntegers
* Calculates the sum and average of any three integer numbers
*/
import javax.swing.JOptionPane;
// Calculate sum
sum = firstNumber + secondNumber + thirdNumber;
// Calculate average
average = sum/3.0;
Figure 4.1
Figure 4.2
Let's begin with a simple analogy to help you understand classes and their contents. Suppose you want
to drive a car and make it go faster by pressing down on its accelerator pedal. What must happen
before you can do this? Well, before you can drive a car, someone has to design the car. A car
typically begins as engineering drawings, similar to the blueprints used to design a house. These
engineering drawings include the design for an accelerator pedal to make the car go faster. The pedal
"hides" the complex mechanisms that actually make the car go faster, just as the brake pedal "hides"
the mechanisms that slow the car and the steering wheel "hides" the mechanisms that turn the car.
This enables people with little or no knowledge of how engines work to drive a car easily.
Unfortunately, you cannot drive the engineering drawings of a car. Before you can drive a car, the car
must be built from the engineering drawings that describe it. A completed car will have an actual
accelerator pedal to make the car go faster, but even that's not enough the car will not accelerate on its
own, so the driver must press the accelerator pedal.
Now let's use our car example to introduce the key programming concepts of this section. Performing
a task in a program requires a method. The method describes the mechanisms that actually perform its
tasks. The method hides from its user the complex tasks that it performs, just as the accelerator pedal
of a car hides from the driver the complex mechanisms of making the car go faster. In Java, we begin
by creating a program unit called a class to house a method, just as a car's engineering drawings house
the design of an accelerator pedal. In a class, you provide one or more methods that are designed to
perform the class's tasks. For example, a class that represents a bank account might contain one
method to deposit money to an account, another to withdraw money from an account and a third to
inquire what the current balance is.
Just as you cannot drive an engineering drawing of a car, you cannot "drive" a class. Just as someone
has to build a car from its engineering drawings before you can actually drive a car, you must build an
object of a class before you can get a program to perform the tasks the class
When you drive a car, pressing its gas pedal sends a message to the car to perform a taskthat is,
make the car go faster. Similarly, you send messages to an object each message is known as a
method call and tells a method of the object to perform its task.
Thus far, we have used the car analogy to introduce classes, objects and methods. In addition to
the capabilities a car provides, it also has many attributes, such as its color, the number of doors,
the amount of gas in its tank, its current speed and its total miles driven (i.e., its odometer
reading). Like the car's capabilities, these attributes are represented as part of a car's design in its
engineering diagrams. As you drive a car, these attributes are always associated with the car.
Every car maintains its own attributes. For example, each car knows how much gas is in its own
gas tank, but not how much is in the tanks of other cars. Similarly, an object has attributes that
are carried with the object as it is used in a program. These attributes are specified as part of the
object's class. For example, a bank account object has a balance attribute that represents the
amount of money in the account. Each bank account object knows the balance in the account it
represents, but not the balances of the other accounts in the bank. Attributes are specified by the
class's instance variables.
The remainder of this chapter presents examples that demonstrate the concepts we introduced in
the context of the car analogy.
Insatiable Classes
Insatiable classes can be permits users to create instances – objects of the class. Each object of
the class will have its own set of variables – instance variables that represent the current state of
the object and methods that defines the task that object can perform. Technically each method
should perform only a single task, and it is permitted to call other methods to assist it.
Instance variables are declared outside any method inside the class and usually immediately after
the class definition header. See line 8 of figure 5.1. the access modifier is used to ensure that
each object maintains it own set of variables and thus not visible to any other object of the class
We begin with an example that consists of classes Circle (Fig. 5.1) and CircleTest (Fig. 5.2).
Class Circle (declared in file Circle.java) will be used to define the properties of a Circle
object and tasks which each object of the class will be able to perform – in this case calculate the
area of a Circle instance. Class CircleTest (declared in file CircleTest.java) is an
application class in which the main method will use class Circle. Each class declaration that
begins with keyword public must be stored in a file that has the same name as the class and
ends with the .java file-name extension. Thus, classes Circle and CircleTest must be
declared in separate files, because each class is declared public.