0% found this document useful (0 votes)
24 views

Com 121 Intro To Java Prgrming Theory

The document discusses the history and development of the Java programming language. It describes why Java is a popular language and outlines the basic principles of object-oriented programming. It also explains the components of a Java application program like classes, methods, and the main method.

Uploaded by

TIMJAY
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views

Com 121 Intro To Java Prgrming Theory

The document discusses the history and development of the Java programming language. It describes why Java is a popular language and outlines the basic principles of object-oriented programming. It also explains the components of a Java application program like classes, methods, and the main method.

Uploaded by

TIMJAY
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

LANDMARK POLYTECHNIC,

AYETORO/ITELE VIA AYOBO

SCHOOL OF SCIENCE AND TECHNOLOGY

COMPUTER SCIENCE DEPARTMENT

SCIENTIFIC PROGRAMMING USING JAVA


COURSE CODE: COM121

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. Portability: Java is a highly portable programming language because it is not designed


for any specific hardware or software platform. Java programs once written are translated
into an intermediate form called bytecode. The bytecode is then translated by the Java
Virtual Machine (JVM) into the native object code of the processor that the program is
been executed on. JVMs exist for several computer platforms; hence the term Write Once
Run Anywhere (WORA).
b. Memory Management: Java is very conservative with memory; once a resource is no
longer referenced the garbage collector is called to reclaim the resource. This is one of
the elegant features that distinguishes Java from C/C++ where the programmer has to
“manually” reclaim memory.

Scientific Programming Using Java LECTURER : ONI M. S Page 1


c. Extensibility: The basic unit of Java programs is the class. Every program written in
Java is a class that specifies the attributes and behaviors of objects of that class. Java
APIs (Application Programmers Interface) contains a rich set reusable classes that is
made available to the programmers. These classes are grouped together as packages from
which the programmer can build new enhanced classes. One of the key terms of object
oriented programming is reuse.
d. Secure: Java is a very secure programming language. Java codes (applets) may not
access the memory on the local computer that they are downloaded upon. Thus it
provides a secure means of developing internet applications.
e. Simple: Java’s feature makes it a concise programming language that is easy to learn and
understand. It is a serious programming language that easily depicts the skill of the
programmer.
f. Robustness: Java is a strongly typed programming language and encourages the
development of error free applications.

Types of Java Programs


Java programs may be developed in three ways. They will be mentioned briefly here:

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.

Introduction to Java Applications


As earlier described Java applications are stand alone programs that can be executed to solve
specific problems. Before delving into the details of writing Java applications (and applets) we
will consider the concept on which the language is based upon being: Object Oriented
Programming (OOP).

Scientific Programming Using Java LECTURER : ONI M. S Page 2


Object Oriented Programming is a methodology which has greatly revolutionized how programs
are designed and developed as the complexities involved in programming are increasing. The
following are the basic principles of OOP.

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.

Components of a Java Application Program


Every Java application program comprises of a class declaration header, fields (instance
variables – which is optional), the main method and several other methods as required for
solving the problem. The methods and fields are members of the class. In order to explore these
components let us write our first Java program.

Scientific Programming Using Java LECTURER : ONI M. S Page 3


/*
* HelloWorld.java
* Displays Hello world!!! to the output window
*
*/

public class HelloWorld // class definition header


{

public static void main( String[] args )


{
System.out.println( “Hello World!!! “ ); // print text

} // end method main

} // end class HelloWorld

Listing 1.0 HelloWorld.java


The above program is a simple yet complete program containing the basic features of all Java
application programs. We will consider each of these features and explain them accordingly.
The first few lines of the program are comments.
/*

* HelloWorld.java
* Displays Hello world!!! to the output window
*
*/

The comments are enclosed between the /* */ symbols.


Comments are used for documenting a program, that is, for passing across vital information
concerning the program – such as the logic being applied, name of the program and any other
relevant information etc. Comments are not executed by the computer.
Comments may also be created by using the // symbols either at the beginning of a line:
// This is a comment
Or on the same line after with an executable statement. To do this the comment must be written
after the executable statement and not before else the program statement will be ignored by the
computer:
System.out.println( “Hello World!!! “ ); // in-line comment.

Scientific Programming Using Java LECTURER : ONI M. S Page 4


This type of comment is termed as an in-line comment.
The rest of the program is the class declaration, starting with the class definition header:
public class HelloWorld, followed by a pair of opening and closing curly brackets.
{
}
The class definition header class definition header starts with the access modifier public
followed by the keyword class then the name of the class HelloWorld. The access modifier tells
the Java compiler that the class can be accessed outside the program file that it is declared in.
The keyword class tells Java that we want to define a class using the name HelloWorld.

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.

Scientific Programming Using Java LECTURER : ONI M. S Page 5


This is an array of objects of type String. (Arrays are collections of similar objects.) Objects of
type String store sequences of characters. In this case, args receives any command-line
arguments present when the program is executed. Note that the parameters could have been
written as String args[]. This is perfectly correct.
The instructions (statements) enclosed within the curly braces will be executed once the main
method is run. The above program contains the instruction that tells Java to display the output
“Hello World!!!” followed by a carriage return. This instruction is:
System.out.println( “Hello World!!!” ); //print text

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

Scientific Programming Using Java LECTURER : ONI M. S Page 6


preceding program will be incorrect. Furthermore, although the Java compiler will compile
classes that do not contain a main( ) method, it has no way to execute them. So, if you had
mistyped main, the compiler would still compile your program. However, the Java interpreter
would report an error because it would be unable to find the main( ) method.
In the above program some lines where left blank, this was done in order to make the program
readable. Furthermore, tabs (indentation) were used to within the body of a class or methods as
appropriate to spate characters and symbols. The blank spaces, tabs, and newline characters are
referred to as white spaces.

Compilation and Execution of Java Programs


As earlier mentioned in this text we will create only two types of Java programs – applications
and applets. In the next few paragraphs the steps for editing, compiling and executing a Java
programs. The procedures for Java application and Java applets are basically the same. The major
difference is that Java applets are executed within a browser.
The basic steps for compiling and executing a Java program are:

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)

Scientific Programming Using Java LECTURER : ONI M. S Page 7


Figure 1.0 Java Compilation and execution process.

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.

Scientific Programming Using Java LECTURER : ONI M. S Page 8


Using Simple Graphical Interface

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:

Figure 2.1 HelloWorldGUI.java


1 /*
2 * HelloWolrdGUI.java
3 *
4 */
5
6
7 import javax.swing.JOptionPane;
8
9 public class HelloWorldGUI {
10 public static void main(String[] args) {
11 String msg = "Hello Wolrd";
12 String ans ="";
13
14 JOptionPane.showMessageDialog(null, msg );
15
16 // accept the users name
17 ans = JOptionPane.showInputDialog( null, "Enter your Name Please"
);
18
19 // say hello to the user
20 JOptionPane.showMessageDialog(null, "Hello " + ans );
21
22 } // end method main
23
24 } // end of class HelloWorldGUI

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

Scientific Programming Using Java LECTURER : ONI M. S Page 9


displayed with “Hello World” and a command button labeled ok shown. The user is requested to
enter his/her name (line 17) and a hello message with the name enter is displayed –(line 20).

The outputs of the program are presented below.

Figure 2.2 sample output of HelloWorldGUI.java program.

Scientific Programming Using Java LECTURER : ONI M. S Page 11


CHAPTER THREE
JAVA DATA TYPES,IDENTIFIERS AND RESERVED WORDS

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:

a. Primitive Data Types


b. Reference Data Types (or Non-Primitives)

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.

Primitive Data Types


The term primitive is used here to indicate that these types are not objects in an object-oriented
sense, but rather, normal binary values. These primitive types are not objects because of
efficiency concerns. All of Java’s other data types are constructed from these primitive types.

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.

Scientific Programming Using Java LECTURER : ONI M. S Page 12


Integers and Floating Points
Java has two basic kinds of numeric values: integers, which have no fractional part, and floating
points, which do. There are four integer data types (byte, short, int, and long) and two floating
point data types (float and double). All of the numeric types differ by the amount of memory
space used to store a value of that type, which determines the range of values that can be
represented. The size of each data type is the same for all hardware platforms. All numeric types
are signed, meaning that both positive and negative values can be stored in them. Figure 3.0
summarizes the numeric primitive types.

Type Storage Minimum Value Maximum Value


byte 8 bits -128 127
short 16 bits –32,768 32,767
int 32 bits –2,147,483,648 2,147,483,647
long 64 bits –9,223,372,036,854,775,808 9,223,372,036,854,775,807
float 32 bits Approximately –3.4E+38 Approximately 3.4E+38
with 7 significant digits with 7 significant digits
double 64 bits Approximately –1.7E+308 Approximately 1.7E+308
with 15 significant digits with 15 significant digits

Table 3.0 List of Java’s in-built numeric primitive data types.


When designing a program, we sometimes need to be careful about picking variables of
appropriate size so that memory space is not wasted. For example, if a value will not vary
outside of a range of 1 to 1000, then a two-byte integer (short) is large enough to accommodate
it. On the other hand, when it’s not clear what the range of a particular variable will be, we
should provide a reasonable, even generous, amount of space. In most situations memory space
is not a serious restriction, and we can usually afford generous assumptions. Note that even
though a float value supports very large (and very small) numbers, it only has seven significant
digits. Therefore if it is important to accurately maintain a value such as 50341.2077, we need
to use a double.
A literal is an explicit data value used in a program. The various numbers used in programs
such as Facts and Addition and Piano Keys are all integer literals.

Scientific Programming Using Java LECTURER : ONI M. S Page 13


Java assumes all integer literals are of type int, unless an L or l is appended to the end of the
value to indicate that it should be considered a literal of type long, such as 45L.
Likewise, Java assumes that all floating point literals are of type double. If we need to treat a
floating point literal as a float, we append an F or f to the end of the value, as in 2.718F or
23.45f. Numeric literals of type double can be followed by a D or d if desired.
The following are examples of numeric variable declarations in Java:
int marks = 100;
byte smallNo1, smallNo2;
long totalStars = 86827263927L;
float ratio = 0.2363F;
double mega = 453.523311903;

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.

Scientific Programming Using Java LECTURER : ONI M. S Page 14


Order of Algebraic Java
Precedence Operator Symbol Expression Expression Association
Multiplication * axc a*c Left to Right
Division / x/y or x ÷ y or x/y Left to Right
First

Modulus or % w mod 3 w%3 Left to Right


Remainder
Addition + d+ p d+p Right to Left
Second
Subtraction - j–2 j-2 Right to Left
Table 3.1 Operators, precedence and association of operators.

Precedence of Arithmetic Operators


The order in which arithmetic operators are applied on data values (operand) is termed rules of
operator precedence. These rules are similar to that of algebra. They enable Java to evaluate
arithmetic expressions consistently and correctly.
The rules can be summarized thus:
a. Multiplication, division and modulus are applied first. Arithmetic expressions with
several of these operators are evaluated from the left to the right.
b. Addition and subtraction are applied next. In the situation that an expression contains
several of these operators they are evaluated from right to left.
The order in which the expressions are evaluated is referred to as their association. Now let us
consider some examples in the light of the rules of operator precedence; we will list both the
algebraic expression and the equivalent java expression.

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

Scientific Programming Using Java LECTURER : ONI M. S Page 15


Java: y = m * x + c;
In this case the parentheses is not required because multiplication has higher precedence over
addition.
Algebra: z = pr % q + w/x – y
Java: z = p * r % q + w/x – y;
In this example, the expression contains the operators *, % followed by +, / and -. The order of
execution is listed below:

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

Reference (Non-primitive Data Types)


Reference or non-primitive type data is used to represent objects. An object is defined by a
class, which can be thought of as the data type of the object. The operations that can be

Scientific Programming Using Java LECTURER : ONI M. S Page 16


performed on the object are defined by the methods in the class. The attributes or qualities of
the objects of a class are defined by the fields – which in essence are primitive type data values.
Every object belongs to a class and can be referenced using identifiers. An identifier is a name
which is used to identify programming elements such as memory location, names of classes,
Java statements and so on. The names used for identifying memory locations are commonly
referred to as memory variables or variables for short.
Variable names are created by the programmer for representing values to be stored in the
computer memory. Each memory location is associated with a type, a value, and a name.
primitive data such as int (integer) can hold a single value and that value must correspond to the
data type specified by the programmer. Reference data types on the other hand contain not the
objects in memory but the addresses of where the objects (their method and fields etc) are stored
in memory. Examples of reference data types include arrays, strings and objects of any class
declared by the programmer.

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.

Scientific Programming Using Java LECTURER : ONI M. S Page 17


It is a good programming practice to use names that indicate the meaning of the value it
represents. For amountPaid, or amt_paid can be easily remembered that it represent an amount
paid value. Though if the programmer had used x or y as the variable name it would still have
been valid.
Java is a case sensitive programming language thus the programmer must be very careful and
consistent when giving and using variable names. Java distinguishes between upper case
(capital) letters and lower case letters (small letters) hence ‘a’ is different from ‘A’ as far as Java
is concerned.

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.

accessModifier dataType variableList


Where:
accessModifier determines the visibility of the variable to other part of the program e.g. public
or private.

Scientific Programming Using Java LECTURER : ONI M. S Page 18


dataType represents either primitive (int, char, float) or reference type data (array, String).
variableList is one or more valid variables separated using commas.
Examples:
a. private int x, y, z;
In this example the access modifier is private, the data type is int and the variables that are
permitted to hold integer values are the identifiers x, y and z. similar pattern is applied in other
examples below.

b. private float balance, initTemperature;


c. private boolean alreadyPaid;
d. public long population;

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:

accessModifier dataType variable1= value1, variable2 = value2, … , variable = valuen;


We will illustrate with examples.
private int x = 10;
private int a = 0, b= 0, c = 0;
public double amountLoaned = 100;

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.

Scientific Programming Using Java LECTURER : ONI M. S Page 19


CHAPTER FOUR

PROGRAM DEVELOPMENT STAGES

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.

Scientific Programming Using Java LECTURER : ONI M. S Page 20


After we thoroughly understand the problem, we then break the problem into manageable pieces
and design a solution. These steps go hand in hand. A solution to any problem can rarely be
expressed as one big activity. Instead, it is a series of small cooperating tasks that interact to
perform a larger task. When developing software, we don’t write one big program. We design
separate pieces that are responsible for certain parts of the solution, subsequently integrating
them with the other parts.

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:

Scientific Programming Using Java LECTURER : ONI M. S Page 21


a. First we must be able to accept any three numbers from the user.
b. Calculate the average.
c. Display average.

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:

i. Add up the three numbers to calculate their sum.

ii. Divide the sum by three to calculate the average.

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.

The entire processing steps (algorithm) are rewritten as:

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.

Scientific Programming Using Java LECTURER : ONI M. S Page 22


Now we proceed to write the Java program, correct any errors and test with sample data. The
source code for the program is presented below:

/*
* AverageThreeIntegers
* Calculates the sum and average of any three integer numbers
*/

import javax.swing.JOptionPane;

public class AverageThreeIntegers


{
public static void main( String args[] )
{
int firstNumber; // first integer number
int secondNumber; // second integer number
int thirdNumber; // third integer number
int sum; // sum of the three numbers

double average; // average of the three numbers

String input; // input values


String result; // output generating string

// Accept inteher numbers from he user


input = JOptionPane.showInputDialog( null, "Enter first number: " );
firstNumber = Integer.parseInt( input ); // wrap input to integer

input = JOptionPane.showInputDialog( null, "Enter second number: " );


secondNumber = Integer.parseInt( input ); // wrap input to integer

input = JOptionPane.showInputDialog( null, "Enter third number: " );


thirdNumber = Integer.parseInt( input ); // wrap input to integer

// Calculate sum
sum = firstNumber + secondNumber + thirdNumber;

// Calculate average
average = sum/3.0;

// Build output string and display output


result = "Average of " + firstNumber + ", " + secondNumber + " and " +
thirdNumber + " is = " + average;

JOptionPane.showMessageDialog( null, result, "Average of 3 Integers",


JOptionPane.INFORMATION_MESSAGE );

Scientific Programming Using Java LECTURER : ONI M. S Page 23


} // end method main

} // end class AverageThreeIntegers


Listing 4.1 AverageThreeIntegers.java

Figure 4.1

Figure 4.2

Scientific Programming Using Java LECTURER : ONI M. S Page 24


CHAPTER FIVE
CLASSES,OBJECTS, METHODS AND INSTANCE VARIABLES

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

Scientific Programming Using Java LECTURER : ONI M. S Page 25


describes how to do. That is one reason Java is known as an object-oriented programming
language.

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

Scientific Programming Using Java LECTURER : ONI M. S Page 26


or any other class. Variables declared inside a method are not visible to any other member of that
class or outside that class. Such variables are termed local variables. Instance variables are
visible to all members of the class, but not to members of another class. To enable other classes
to access instance variables in order to reflect a change in the state of the objects we use public
service methods – set and get – methods to facilitate this through a well defined mechanism. The
set methods enables changes while get methods gives the current state of the object.

Declaring a Class with a Method and Instantiating an Object of a 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.

Scientific Programming Using Java LECTURER : ONI M. S Page 27

You might also like