Chapter 3 - Core Java Programming Concepts
Chapter 3 - Core Java Programming Concepts
Context
The purpose of this unit is to introduce the most fundamental of computer programming
concepts as they are implemented in Java. These core programming concepts are
those of program statements, control of execution, variables and expressions.
Objectives
Study Planning
You should expect to spend approximately 9 hours studying this unit. You may find it
convenient to break up your study as follows:
Equipment/software required
Sun Java 2 Platform (also known as Java Development Kit version 1.3)
TextPad 4.5
A Web browser
Reading material & recourses
Online Resources:
1. Frequently-asked questions
2. Additional Source Code Examples
Introduction
You will find that although this unit is about core Java programming concepts, little of
this unit deals directly with object-orientation concepts. This is because all programming
languages have many core concepts, such as flow of execution and variables, that have
to be understood, before moving on to some of the language's particular features.
You will find that what you learn from this unit will provide the foundations for
implementing the methods, variables and message-passing of classes and objects in
more complex Java programs. Also, you will learn from this unit important aspects about
the arguments and replies that are passed between objects.
It is likely that you will not understand and be able to apply all the concepts in this (or
any other) unit straight away. Programming is something that is learnt by doing. You will
find that you need to re-visit parts of this and other units several times. Use the review
questions and unit test to gauge your progress, and to identify topics you need to return
to for further work.
Although everything you will learn in this unit is important for Java programs, almost all
of it is also relevant to all `procedural' programming languages (`procedural' languages
are those that are based on detailed instructions executed in a specific order, such as
C, C++, Pascal and Java)
Although it is vital that you understand and apply object concepts as early as possible
for this module, you will find that you can learn a lot about Java and programming by
simply working on and extending some of the simple, single-method classes presented
in this unit (i.e. by adapting the main method of some of the examples).
You will find the module core text, Deitel & Deitel, covers the material in the unit (and
most later units) very comprehensively. In addition to following the assigned reading for
each topic, you are strongly advised to work through the exercises and self-review
exercises of each chapter. There are also many software engineering observations and
common programming error sidebars, which collectively a synthesis of the years of
programming experience of the authors.
Program statements
class TicketDiscount
{
public static void main( String args[] )
{
int age;
// variable 'age'
There are several different categories of Java program statement. They include input
and output statements, statements to change the values of variables, statements to
send messages to objects, and statements to determine which statement to execute
next. The table below analyses some of the different categories of statement that make
up the implementation of the class TicketDiscount.java.Although in this module we
have not (yet) introduced each kind of statement, the table should help to illustrate how
even a simple Java program consisting of a single class may be made up of many
different kinds of statement.
Category of
Example of statement from TicketDiscount.java
statement
// variable 'age'
variable age = (int) ( 100 * Math.random() );
assignment
Compound statements
Notice that some statements consist of more than a single line of the source file. For
example the class declaration statement actually consists of the entire contents of the
TicketDiscount.java source file. Likewise, the control statement 'if( age >= 60 )
...' actually includes the statement 'System.out.println("qualifies for
discount");' as well.
A compound statement is one that consists of a group of statements that are preceded
with an open brace "{", and the last statement in the group followed by a close brace "}".
In the example there are 3 compound statements. The first is the class declaration itself:
class TicketDiscount
// rest of method
The third is the set of statements to be executed if the test of age is true:
if( age >= 60 )
}
This example also illustrates how compound statements can be nested, i.e. the if
statement is a statement within the compound statement that is the implementation of
the main() method:
public static void main( String args[] )
...
Semi-colons ";"
With the exception of compound statements, each statement ends with a semi-colon ";"
character. As is discussed later this unit, the Java compiler is not concerned whether
statements occur on the same or different lines, and ignores multiple space characters
too. Thus the semi-colon is a vital part of the Java language indicating the end of a
statement.
Keywords
Many Java statements contain Java keywords (also called reserved words). Keywords
are words that have been reserved by the developers of the Java language to have
special meaning.
Also Java has many libraries of pre-written classes. The learning of these library
classes is a large task. You will be introduced to many important library classes in the
course of the module.
Comments
/* Everything in this
section is a comment */
is a documentation comment */
The computer never gets to process anything marked as a comment, so comments can
say anything you like. Different authorities have different ideas about the amount of
comments to use, but you should use some — rather than none. Comments are what
will make it possible for you to understand your program if you look at it again after you
thought you had finished it. They will also make it easier for another person (e.g., one of
your co-workers) to understand your program.
The difference between a standard comment (//, /*) and a `documentation comment'
(/**) is that the latter is considered to be part of the overall explanation of how a program
works. Software exists that will extract the documentation comments and make them
into a report. The distinction is not that important in the context of this course, but
anyone who is interested in programming professionally should consider finding out
about the standard documentation generation tooljavadoc (which is part of the JDK
package).
import java.io.*;
class CommentMe
System.out.println("line 1");
System.out.println("line 2");
System.out.println("line 3");
System.out.println("line 4");
line 1
line 2
line 3
line 4
One common technique when debugging a program is to comment out lines, to reduce
the number of statements that are compiled and executed. Thus one can isolate parts of
a program to help locate errors. By the phrase 'comment out' it is meant that program
statements are edited with comments so that they are ignored by the compiler and
interpreter. For example, we could comment out the first output statement as follows:
import java.io.*;
class CommentMe
// System.out.println("line 1");
System.out.println("line 2");
System.out.println("line 3");
System.out.println("line 4");
line 2
line 3
line 4
since the first output line has been ignored by the compiler (and so there is no compiled
'line 1' output statement to be interpreted).
Likewise we can comment out larger sections of code using the two-part `slash-asterisk'
comment:
For example we can comment out the 3rd and 4th output lines of our program as follows:
class CommentMe
System.out.println("line 1");
System.out.println("line 2");
/* System.out.println("line 3");
System.out.println("line 4");
*/
}
}
line 1
line 2
since the third and fourth output lines have been ignored by the compiler (and so there
are no compiled 'line 3' or 'line 4' output statements to be interpreted).
However, perhaps the most useful feature of comments is that they facilitate the
recording of ideas and design summaries of those writing programs. Such comments
are an important source of information about a program, since they can be written and
updated at the same time the program is written (as opposed to attempting to keep
written records up to date with a changing program). See the listing for Hello1.java for
an example of a program with an awful lot of description comments in it.
Activity 1 – Comments
Activity 2
Exercise 2
Control of execution
import java.awt.*;
world.show ();
private BallWorld ()
setSize(600, 400);
setTitle("Ball World");
myBall.paint( g );
pause( 2000 );
System.exit(0);
{
try{ Thread.sleep( numMilliseconds ); } catch
(InterruptedException e){}
} // class BallWorld
There are some important questions we need to know the answers to:
How does the Java run-time interpreter decide which statement to execute first?
After executing a statement, how does the interpreter decide which statement to
execute next?
How does the interpreter know when to stop executing statements — i.e. when
does a program terminate ?
Also, most non-trivial Java programs are composed of 2 or more classes. Version 1 of
the unit 2 BallWorld application consisted of 2 classes: BallWorld and Ball. So we have
another question to answer:
How does the interpreter decide from which class to choose a statement to
execute?
All of these questions relate to the control of statement execution by the Java run-time
interpreter. The answer to some of these questions is determined by the design of the
Java programming language, and the answer to others is that we can design programs
to choose statements according to the rules we wish the program to follow.
The answer to these questions is different for Java applications and Java applets.
A main method is show in full in the abbreviated version of the BallWorld class below:
// BallWorld.java
import java.awt.*;
public class BallWorld extends Frame
world.show ();
private BallWorld ()
} // class BallWorld
The first statement inside this class's main method will be the first statement of the
application to be executed, i.e.:
Although all classes that comprise an application need to be compiled, we only tell the
interpreter the name of the main class. The class Ball does not contain the method
main, it is used by BallWorld. We can using Kawa run the BallWorld class.
For an applet, the main class is the one referred to in the <applet> tag of the HTML file,
e.g.,
</applet>
As we shall see later, a constructor is the method that is executed when an instance of
a class is created. The constructor method always has the same identifier (name) as the
class itself. So the first statement to be executed for the applet MyClass will be the first
statement of the constructor method MyClass.
Example:
//AppletGreetings.java
import java.awt.*;
import java.applet.Applet;
</applet>
You can then run the HTML file from TextPad using clicking Tools and selecting Run
Java Applet.
A complex Java program may have multiple threads of execution, that is, different parts
of the program that appear to be executing at the same time. This is a sophisticated
topic, which you should be ready to learn about by the time you complete this module.
For the discussion in this unit we will consider only simple Java programs which do not
have multiple threads.
A Java application stops when the main method has finished executing.
A Java applet stops when it is instructed to do so by the Web browser or applet viewer.
Normally the programmer does not have to worry too much about this.
An applet is embedded in another program, usually a Web browser. If the user of the
browser changes to another Web page, for example, the applet must be able to stop
immediately. The browser will signal to the applet that it is about to be stopped, by
calling, among others, its stop method. The programmer only needs to do anything about
this if there are certain actions that the applet must carry out before it is stopped.
Event-driven programming
With a graphical user interface, Java makes use of a technique called event-driven
programming. This means that when certain events occur (e.g., the user clicks on a
button, the mouse is moved, etc) then a corresponding method is executed. You will
already have seen this in the BallWorld application, which had a method called paint.
The program did not indicate when to execute this method; it is executed whenever a
repaint event occurs. The Java system knows when the display needs to be updated,
and generates this event automatically — for example when a window is resized or
revealed by the minimizing of another window. Events, and event-driven programming,
will be investigated later this module.
Flow of execution
Once the run-time interpreter has chosen to execute a method, it will execute the first
statement in the method. Depending on the category of statement, there are two
fundamental ways that the run-time interpreter decides how to choose the next
statement to execute:
Execution in sequence
Unless specified otherwise, when the program has finished executing one statement, it
will go on to the next one it encounters. It's as simple as that. For example, the
statements below would be executed in just the order they occur:
age = 21;
ageNextBirthday = ( age + 1 );
age = 21;
ageNextBirthday = ( age + 1 );
Branching of execution
The result was the development of structured programming principles limit the
programmer to a small number of branch types. Java enforces these principles strictly,
except in error conditions (we will investigate the way Java implements error handling
through exceptions in a later unit).
subroutine calling
selection
iteration
Since all three kinds of statement control the flow of execution, they are often referred to
as control statements.
Subroutine calling is implemented via method invocation. It is the process of getting the
interpreter to execute a method of an object. It consists of instructing the interpreter to
remember where it is at present, and to send a message to an object, resulting in a
(possibly inherited) method of that object being executed. When that method has
completed its execution, control of execution will return to the original statement where
the message was sent.
Selection is another word for 'choice'. It is the process of selecting one of a number of
different statements, according to some condition. In Java, selections are implemented
using the if, if .. else and switch .. case statements.
Iteration is another word for 'looping'. This simply means repeating some program
statements a particular number of times. In Java, iteration is implemented using the
while, do .. while and for statements.
When we write a statement that sends a message to an object, the run-time interpreter
has to work out if the message is in the object's protocol, and if so, where in the class
hierarchy the appropriate implementation of the corresponding method can be found.
Once found, the run-time interpreter will execute the instructions of the method, and
then return execution to the line following the one where the original message was sent.
Unlike selection and iteration there is no testing taking place to decide whether on not
the message will be sent. Thus this kind of branching is called unconditional branching.
In the example programs you have met already, you have already seen many examples
of message sending, resulting in the invocation of methods. The class System and its
corresponding println method is one of the (many) built-in messages/methods on the
Java language. When a program sends a println message it must indicate what to
print, and to which object to send the message:
System.out.println ("hello")
or
System.out.println (2 + 2)
In these examples "hello" and "2 + 2" are arguments that form part of the message, and
that become inputs to the invoked println method. When this method was
implemented, by the Java development team, they defined how that arguments are
processed. When you define methods in your programs, you will have to do the same.
A note on 'built-in' methods
In fact methods such as println are not really built-in to the language itself.
Technically they are built into the standard class library. However, that distinction is not
important here.
Method: example
You will have gained experience and understanding of the sending of messages
between objects, and the invocation of methods corresponding to received messages.
What you may have not realised is that an object can send a message to itself, simply
by a statement that consists of a message, but no explicit object to send the message
to.
We shall investigate such issues in detail in a later unit, however, for illustration we shall
give a simple example to show the deviation from the default, sequential flow of
statement execution.
class UnconditionalBranch
method2()
statementM1;
statementM2;
method1()
{
statementA;
method2();
statementB;
// other methods
...
When method1 is being executed, the order that statements will be executed will be as
follows:
statementA;
statementM1;
statementM2;
statementB;
since statementA is executed first, followed by the sending of the message method2().
Since no object is specified for the object to be sent to, this message will be sent to the
object that is the instance of the class currently having its method2() method executed.
The run-time interpreter will see that this class defines a method2() that corresponds to
the. The run-time interpreter then transfers control of execution by invoking method
method2() — i.e. method2() will now have its statements executed. Next statementM1 is
executed, followed by statementM2. That ends execution of method2(), so control of
execution returns to the place where the message was sent in method1(). Next
statementB is executed. Then method2() completes its execution (and control of
execution returns to whatever happened before method1() was invoked.
Selection in Java
A selection can result in a statement being executed once or not at all. What determines
whether the statement will be executed or not is the result of a test If the result of the
test is true then the statement will be executed, if the result is false it will not be
executed.
There are three forms of selection statement implemented in Java:
if
if...else
switch...case
In this module we shall concentrate on the first two of these selection statements. They
are all technically equivalent; the choice as to which form of selection statement to
implement in a program is made by each programmer on the grounds of style or
convenience.
In this unit we shall examine just the first (simpler) if selection statement. In the next
unit we will examine the extended if...else selection statement and an iteration
statement
Selection: `if'
Using pseudocode code we can illustrate how an if statement works. Consider the
following pseudocode for a system to operate fire alarms in an office building:
if <test>
To implement our fire alarm pseudocode as a valid Java statement we could write the
following:
soundAlarm();
(of course we are assuming the class has a variable called temperature and a method
soundAlarm())
The way an if statement can cause deviation from the default sequential flow of
execution can be illustrated as follows. Consider this pseudocode design:
statementA;
statementB;
statementC;
If the variable age has a value over 60, say 65, then the test ( age > 60 ) will be true,
and the therefore statementB will be executed. So the statements to be executed will
be:
statementA
statementB
statementC
However, if the variable age has a value of 60 or less, say 21, then the test ( age > 60 )
will be false, and statementB will not be executed. So the statements executed will be:
statementA
statementC
Thus the result of a selection statement means that some statements may not be
executed, or may be executed once.
Selection: `if'
Using pseudocode code we can illustrate how an if statement works. Consider the
following pseudocode for a system to operate fire alarms in an office building:
if <test>
To implement our fire alarm pseudocode as a valid Java statement we could write the
following:
soundAlarm();
(of course we are assuming the class has a variable called temperature and a method
soundAlarm())
The way an if statement can cause deviation from the default sequential flow of
execution can be illustrated as follows. Consider this pseudocode design:
statementA;
statementB;
statementC;
If the variable age has a value over 60, say 65, then the test ( age > 60 ) will be true,
and the therefore statementB will be executed. So the statements to be executed will
be:
statementA
statementB
statementC
However, if the variable age has a value of 60 or less, say 21, then the test ( age > 60 )
will be false, and statementB will not be executed. So the statements executed will be:
statementA
statementC
Thus the result of a selection statement means that some statements may not be
executed, or may be executed once.
The statement that is to be executed if the test is true can either be a single statement
such as soundAlarm() above, or it can be a compound statement (one or more
statements blocked with the open and close braces "{" "}"). For example, we might wish
to perform more than one action if the temperature is too high:
soundAlarm();
displayFlashingLight( red );
triggerAlarmAtFireStation();
As with the concept map from the earlier units, you can use the map below as a way
retrieve glossary entries. Some of the concept nodes below are not introduced fully in
this unit, and you might wish to re-visit this concept map (and perhaps create / extend it
for yourself on paper) as you progress through the module.
Please note that some of the more complex selection and iteration control concepts are
not introduced until the next unit. As you work through Unit 4 you may wish to refer back
to this concept may, to see the relationships between those control statements and
what you learn about statements in this unit.
Read Chapter 4 of Deitel & Deitel chapter 2 section 2.4 (pages 52,53) and
chapter 4 section 4.13
We need to store and process data values when writing computer programs. For object-
oriented programming languages like Java, we need to be able to define and set the
values for the variables required to implement classes and their instance objects.
A variable is any named piece of data that can change during the execution of a
program. A non-trivial program will use many variables — perhaps thousands of them.
There are times when we wish to name some value, but not have that value ever
change. For example, we might wish to define some mathematical constant, such as pi.
Or perhaps decide what the width and height of an application window will be, and not
allow it to change. The term for a named value that should never changes is a constant.
When we wish to refer to a constant value itself (rather than a name for the value), we
simply write a literal in our Java program. Examples of literals include:
5
10.5
't'
"hello there"
true
-23.34555
Types
Each variable or constant in a Java program can only store values of a certain
type which is determined by the programmer.
We shall thoroughly investigate Java object variables, and arrays in later units.
In this unit we shall mainly concentrate on variables that can store values of the
primitive types.
int: an integer.
float, double: approximate real numbers.
char: a single character.
byte: a byte.
boolean: true or false.
A quick recap of some high school mathematics: an integer is a whole number (e.g., 3,
0, -1000) and a real number is one that can have a fractional component (e.g., 3.1, -
32.6)
Each shall be briefly covered in this section (and is covered in detail in the Deitel &
Deitel chapters).
int
byte
short
long
For most of your programs you will probably find that the int type is sufficient.
A real number can have values that are in between integers. The informal way to
describe such number in English is as 'decimal' numbers.
Java offers two ways to represent and work with different types of real number. The
difference between them are both the range and precision of values they can represent.
By precision, it is mean the number of decimal places that numbers can be stored to.
float
double
Real numbers are only approximated by float and double, because they have limited
precision. For example, there is no way to represent the result of '1 divided by 3' exactly
as a decimal number, as it requires indefinite precision (0.333333333….). The double
type gives about 17 digits precision, which is enough for most purposes.
Since most mathematical operations are now done by the computer's hardware, there is
little to be gained by using the float data type rather than double.
In fact, if you don't indicate otherwise, the Java compiler will assume that you want
double and not float precision. For example if you write:
2.1 + 3.4
Unless you are writing quite sophisticated mathematical programs, you probably don't
need to worry too much about these issues.
Character types
There is only one primitive Java type for working with individual characters — the char
type.
'm'
' ' (space)
'='
'5'
'A'
Notice the use of single quotation marks for char literal values. This becomes important
when working with strings of characters that defined using double quotation marks.
A related concept to the char type, is that of the String class. The relationship between
characters and strings is described in the next unit.
Boolean types
The primitive type boolean is for values that are either true or false.
if( holdsDriversLicence )
processCarHire();
else
Boolean types, as can be seen above, are very useful for forming part of the conditions
for selection and iteration statements, or storing the results of tests to be referred to
later.
int numberOfRecords;
double temperature;
char firstInitial;
Note that each of these has a type (int, double, char) and an identifier
(numberOfRecords, temperature, firstInitial).
It is also possible to give a variable an initial value (which can be overwritten with a
different value elsewhere in the program). This is done by using the assignment
operator = after the identifer, and provide the initial value:
As you might expect, the Java compiler will complain if you try to assign an initial value
that is not compatible with the variables declared type. For example, compiling the
program below results in an error message:
class TypeError
What is interesting about this error message is that is tells us one way we could solve
the type incompatibility problem! Being offered a solution, and in fact receiving an
informative error message is, unfortunately, not always the case with Java. The solution
offered is:
It is possible to covert a value from one type to another by a technique called casting.
The way to assign a value to a variable is the same way as giving it an initial value —
i.e. by the use of the assignment operator =. When we assign a value to a variable, this
new value overwrites any previous value. Examples of assigning values to variables
include:
age = 21;
sum = (2 + 2);
stockLevel = 100;
carLockCode = Math.random();
As you may have inferred from these examples, there is a required format for variable
assignment statements. On the left hand side is the variable identifier, followed by the
assignment symbol =, and on the right hand side is an expression, that must evaluate to
a type that can be stored in the variable.
The format of the expression can be simple or complex. Expressions are investigated
later this unit. A summary of the different expressions in the example above is as
follows:
expression evaluates to expression type
21 21 any integer or real type
(2 + 2) 4 any integer or real type
(age + 1) 22 (21 + 1) any integer or real type
Math.random() a pseudo-random double (since the random()
number from 0.0 up to method defines its reply type
but not include 1.0 as double)
Casting
When we instruct Java to convert a value from one type to anther it is called casting (or
type casting).
It is often the case when casting between types that some values are lost / changed due
to the different ways types are represented. So, for example, if we cast from a double
value to an int, we will lose all of the fractional part of the number.
If we can imagine a computer system for a car production factory, we wish to know both
the precise number of cars produced as a real value (e.g. 200,271.5 cars), and also the
number of complete cars we can actually ship out to customers — customers are
unlikely to wish to received incomplete cars! This is illustrated in the program below:
class Cast
int completeCars;
}
When compiled and run this program produces the following output:
As can be seen, when a double is casted into an intonly the whole number part of the
double value is retained.
Constants
The keyword final is used to indicate that something is a constant. For example:
The use of constants can make a program much easier to understand, and prevent the
programmer making errors which, although trivial, are rather difficult to trace.
We have seen examples of constants used in the BallWorld application from the
previous unit. Constants were introduced to define the width and height of the window
the balls bounced within:
In fact, as they appeared in the application, these constants were declared with two
more keywords:
however, we shall leave investigation of the keywords public and static until later
units.
The name given to a variable, operation, attribute, or class is called its identifier. Java
has certain rules about identifiers, which must be followed. There are also certain
conventions, which ought to be followed.
Identifier really means the same thing as name, but identifier is the term normally used
by programmers. All variables and classes must have an identifier. The most important
of Java's rules about identifiers are that:
We cannot have a variable called 'class', since class is a keyword. However, we can
have one called 'Class', since Java is case sensitive so 'class' and 'Class' are
considered different.
Warning: You are likely to make many simple mistakes of using upper and lower case
first letters the wrong way round. Don't worry about this, just check the case of your
identifiers when you encounter an error you don't understand.
Conventions have evolved to reduce the chance of errors, and to use case to help us
distinguish Class identifiers from variable and method identifiers. The most important
conventions are that
For example, we cannot define a variable called number of seconds because spaces
are not allowed. We can define a variable called number_of_seconds (since one of the
few punctuation symbols permitted in identifiers is the underscore). However, in Java
programming the convention is to write such a composite identifier as numberOfSeconds .
Of course you don't have to follow the conventions; the compiler won't object if you
don't. However, there are lot of Java programmers in the World, and they are nearly all
following these conventions. It will make your programs easier to understand if you do
too. Also, if you use the same conventions as everyone else, you'll find their programs
easier to understand!
You may be wondering how we can distinguish between variable and method
identifiers, if they both start with a lower case letter. In fact this is not a problem, since a
method must always be followed with parentheses "(" ")" even if it has no arguments.
Thus we know, for example, that length is a variable identifier, and length() is a
method identifier.
Variables — Exercises
Expressions
Read Chapter 4 of Deitel & Deitel sections 2.5 and 2.6 pages 53-57 inclusively,
and 60-62 Common programming errors, Good programming practice and
Chapter 4 sections 4.11-4.12
Introduction to expressions
which involves:
Each of the Java types has associated with it a set of operators (such as '+', '/', '&&')
that can be arranged with operands to create expressions to be evaluated.
Numeric expressions
2 + 2
age + 1
25 / 5
2.5 * 4
15 % 4
The implementation of the most common numeric operators in Java are as follows:
addition + 2+2 4
subtraction - 5-2 3
modulus % 15 % 10 1
(integer
division)
As can be seen, some of these operations can be used with, and result in either whole
numbers or floating point numbers.
You should explore the range of numeric expressions as presented in Deitel & Deitel.
Boolean expressions
There are several operators that return a boolean result. These operators are generally
from two categories:
comparison operators — such as those for less than '<' and greater than '>', and
test for equality '=='
logical operators — such as those for logical AND '&&' and logical OR '||'
For example, we might want to define a loop that continues while one number is less
than 10, and also another is greater than 100. If the numbers are stored in variables
called x and y, then in Java this would be written:
while( (x < 10) && (y > 100) )
A question frequently asked is why the symbols used for comparisons are so arcane.
For example, it is possible to envisage a programming language where the statement
above could be written:
while (x isLessThan 10) and (y isGreaterThan 100)
However, this would not make sense to Java. Moreover, in Java the symbols & and &&
are both read as `and', but they are different kinds of 'and'!
The reason these symbols are used is that the Java developers wanted to use the same
symbols as C++, so that C++ programmers could learn Java easily. The reason that
C++ uses these symbols is that the C++ developers wanted to use the same symbols
as C, so that C programmers could learn C++ easily.
It is especially important to note that the equal sign = is not used for comparing whether
two things are equal; you need ==. These are a major source of confusion for
beginners.
For example, if one wanted to define a loop that repeated while x was equal to `false', it
would be wrong to write:
while (x = false)
{
//...
Since what (x = false) does is to assign the value `false' to the variable x. It is not
comparing the value inside variable x with the value `false'.
The annoying thing about this is that the compiler will accept it, as it is perfectly valid
Java syntax. It will simply give totally wrong and confusing results. This is because an
assignment statement evaluates to a value itself. That is, writing
while (x = false)
is equivalent to:
while (false)
The code should be written as follows (i.e. using the test for equality operator ==):
while (x == false)
//...
It is almost certain that you will make this mistake, more than once, during this module.
Many people who have been programming professionally for years still make this
mistake all the time. It is a poorly designed feature of the language, but retained to keep
compatibility with C++ and C syntax.
char
boolean
numeric (int, byte, short, long, float, double)
array
object
When a variable identifier appears in a program it evaluates to a value of its type
(primitive, array or object). Likewise, a message sent to an object, whose corresponding
method returns a value will evaluate to the type of the value of the reply (for example,
the method Math.random() returns a reply value of type double).
Each time you assign a value to a variable, perform a test for a selection or iteration
statement, pass arguments with messages, and write statements to process the replies
from methods you will be dealing with expressions. They are an invaluable feature of
the Java programming language.
As with the concept map from the earlier units, you can use the map below as a way
retrieve glossary entries. Some of the concept nodes below are not introduced fully in
this unit, and you might wish to re-visit this concept map (and perhaps create / extend it
for yourself on paper) as you progress through the module.
Exercise 8
Java has a large number of classes organised into packages which are called the Java
class library or the Java Applications Programming Interface (API). We have already
usedio, applet in the first examples. The recommended text Deitel and Deitel uses
thejavax.swing package in the introductory chapters. The classJOptionPane from
thejavax.swing package is useful for its Graphical User Interface (GUI) components that
make the task of data entry into a program or formatting (organising the display) of the
output easier.The Java GUI and event handling will be examined in greater detail in Unit
8.
Line 1 is animport statement. This statement tells the compiler to load the classes
required for compiling the program. In this case the compiler will load theJOptionPane
class from thejavax.swing package
Line 3 is the method main part of every Java application. Every Java application must
have one method calledmain. The body of the method is enclosed within the braces{}.
This includes the lines 4 and 5.
Line 5 is another static method of theSystem class used to terminate the application.
TheSystem class is part of thejava.lang package which is always imported by default.
For example if we wish to change the TicketDiscount program so that instead of the age
being randomly generated, the user is expected to enter the age after which the
relevant message is displayed.
We will first examine the TicketDiscount.java listed below and decide on the changes
needed to produce the new version TicketDiscountVersion2.java.
2 class TicketDiscount {
Line 5 would need to be replaced with code what will obtain input from the user. A
prompt should be displayed on the screen telling the user that input is expected e.g.
“Enter age: “.
Line 6 will no longer be necessary because the user input will be shown on the screen.
Another change would be to display a message even if there is no discount "Sorry no
discount" because with interactive programs users expect a response from the
program. For this reason the else branch of the selection will be added.
In Java all data displayed on the screen or input from the keyboard is in the form of
Strings. Strings are a series of characters treated as a single entity and as text.
If we need to use data in a different form, other than text e.g. numbers the String data
needs to be converted. Java has a range of parse methods, which convert strings into
a variety of types. parse methods that convert Strings to simple/scalar/built-in data
belong to wrapper classes such as:Integer, Float, Double, Long, Boolean, Character. To
convert a String sto anintwe use the methodparseInt, a metod of wrapper classInteger.
2 class TicketDiscountVersion2 {
9 s = in.readLine();
10 age = Integer.parseInt(s);
else
The changes made to the program lines 3, 5, 6, 7, 8, 9, 13, 14 are shown in boldface
font.
Enter age: 54
Sorry no discount
String s;
else
JOptionPane.showMessageDialog(null, "Sorry no
discount");
System.exit(0);
Activity 1 – Comments
(3) Now modify the file (and recompile and run) to create the following different outputs,
only through the use of comments :
(a) line 1
line 2
line 3
(b) line 2
line 3
(c) line1
line4
Discussion of Activity 1
(1) you should have saved a file with the name CommentMe.java
(3) You need to insert comments to prevent certain lines of the code from being
executed.
(a) You could change the listing to the following:
class CommentMe
System.out.println("line 1");
System.out.println("line 2");
System.out.println("line 3");
// System.out.println("line 4");
or you could use one of the other types of comment, such as:
class CommentMe
System.out.println("line 1");
System.out.println("line 2");
System.out.println("line 3");
/* System.out.println("line 4");
*/
However, since only a single line (line 4) needs to be 'commended out', probably the //
comment is most appropriate.
(b) You need to comment out line 1 and line 4, since these lines are not together, again
use of the // comment is most appropriate:
class CommentMe
// System.out.println("line 1");
System.out.println("line 2");
System.out.println("line 3");
// System.out.println("line 4");
(c) Since you need to comment out lines 2 and 3, and these lines are next to each
other, you could either comment out each line separately using //:
class CommentMe
System.out.println("line 1");
// System.out.println("line 2");
// System.out.println("line 3");
System.out.println("line 4");
or you could comment out both lines together with the /* … */ form of comment:
class CommentMe
System.out.println("line 1");
/* System.out.println("line 2");
System.out.println("line 3");
*/
System.out.println("line 4");
Note the use of indentation, and blank lines, to make it clear which lines are being
commented out in each example above.
Activity 2
This program works out 2+2. Make sure that you see the result on the screen.
(b) In this program the result of the addition was assigned to a variable called `result'.
While this is a sensible name for something that store the result of a calculation, the
choice of variable names is entirely at the discretion of the programmer. Modify the
program Add1.java, so that the variable is called `fred'. Note that you will have to
change more than one line.
(c) In (b) I suggested changing the variable name from `result' to `fred'. While this
works, why is this a silly thing to do?
(d) Enter, and try to run the program ` Add1_bad.java '. It won't work. What is the error
message, and what does it mean?
(e) Using `Add1.java' as an example, write a Java applet that works out 1234 x 4321. In
Java, as in most programming languages, we can't use the letter `x' to mean
multiplication (because it might be the name of a variable). So we use an asterisk `*'
instead.
(f) Using `Add1.java' as an example, write a Java applet that works out 2 / 5 (two
divided by 5).
And the answer is NOT zero. If you get zero, try to figure out why and put it right.
(b) The variable result appears in two places, and you need to change both of them.
(c) Because fred is not a useful name for a mathematical result. Variable names
should reflect their purposes. Otherwise the program will be difficult to understand.
(d) “Incompatible type for method. Can't convert int to java.lang.String” The
problem is that the drawString method is expecting a text string in the first position, and
instead it gets '2+2'. Now the result of adding 2+2 is an integer, not a text string, hence
the message. This is an example of what computer scientists call strong typing. This
means that a piece of data is not automatically converted from one form to another. The
use of strong typing is thought to reduce the likelihood that the programming will make
trivial errors (but it doesn't do much to prevent major errors!)
(a) final indicates that tableNumber is a constant. It will not stop the program working if
'w' is omitted. However, it does give a clue to someone reading the program that
tableNumber is not expected to change during execution of the program. Also, if the
programmer accidentally mistyped a statement so that it came out (for example):
tableNumber = 1;
the compiler would be able to indicate that this was an error (because we can't change
the value of tableNumber). In summary, the use of `final' here provides a small but
definite increase in the quality of the program.
(b) paint is called automatically when the applet's display needs to be re-drawn. This
will happen when the applet is first loaded, and again any time the applet is concealed
and uncovered. For example, if I move a different program so that it's display is `on top
of' the applet, then bring the applet to the `top' again, then paint will be called
automatically. The programmer does not have to worry about how this is organized; on
a Windows system the Windows operating system detects which parts of the screen
need to be re-drawn and interacts with the Java system to handle this correctly. What
the programmer needs to know is that, to ensure that the applet's display is always
correct, a paint method must be provided.
(c) `i' takes values from 1 to 12 inclusive. The middle section of the `for' statement says
i <= 12
meaning `continue while i is less than or equal to 12'. When i becomes 13, the loop
stops.
(d) the two 20s in this statement control the position where the text is to be placed. In
the first iteration (repetition) of the loop, `i' is 1, so the position is 20, 20 (20 pixels
across, 20 down). In the next iteration, `i' is 2, so the position is 20, 40 (20 pixels across,
20 down). This positions the text of the display in a column on the screen, with each
new value below the preceding one.
Change the Add1.java from Activity 3 so that it adds two numbers input by the user. You
may use the text screen input facilities or use the Javax.swing.JOptionPan
Exercise 1 – Program statements summary
Complete the following statements that summarize the concepts explored in the
'Program statements' section of this unit.
Discussion of Exercise 1
Exercise 2
A Java ___________ will begin execution with the first statement of the ____ method of
the class provided as an argument to the interpreter (i.e. the 'main' class).
A Java ______ will begin execution with the first statement of the ___________ method
of the class named in the <APPLET> tag.
The computer executes in an order determined by the program statements. Unless
otherwise specified, statements will be executed in ________, i.e. one instruction after
another in the order they occur.
Discussion of Exercise 3
A Java application will begin execution with the first statement of the main method of the
class provided as an argument to the interpreter (i.e. the 'main' class).
A Java applet will begin execution with the first statement of the constructor method of
the class named in the <APPLET> tag.
There are three different categories of branching: selection, iteration, and unconditional
branching.
(1) List the four whole number numeric primitive types in increasing order of memory
required (i.e. number of bits to represent each type of variable).
(2) List the two decimal numeric primitive types in increasing order of memory required
(i.e. number of bits to represent each type of variable).
(3) State the remaining two primitive types, and the number of bits to represent each.
Discussion of Exercise 4
The answers to the exercise steps are as follows:
(1) byte (8 bits), short (16 bits), int (32 bits), long (64 bits)
Complete the following statements that summarize the concepts explored in the
'Variables' section of this unit.
A variable is any named piece of data that can change during the execution of a
program.
an identifier
a ____
a ____
Discussion of Exercise 5
A variable is any named piece of data that can change during the execution of a
program.
an identifier
a type
a value
Complete the following statements that summarize the concepts explored in the
'Expressions' section of this unit.
Control of loops and branches is made on the basis of __________ between variables
or constants.
The symbols for some of the comparison operators available in Java include:
equals __
___ _____ !=
less than _
___ &&
or __
Discussion of Exercise 6
Control of loops and branches is made on the basis of comparison between variables or
constants.
The symbols for some of the comparison operators available in Java include:
equals ==
not equal !=
and &&
or ||
The program statements needed to carry out a simple addition are surprisingly
complicated. Suggest why the Java programming language does not allow a pair of
additions to be written simply:
2+2 3+3
rather than
Exercise 8
8 complete exercises 2.13, 2.14, 2.15 from chapter 2 of Deitel and Deitel
Review Question 1
// System.out.println ("Hello");
Review Question 2
For A Java application the first statement of the first method of a Java class is the first
statement that is executed.
This is not necessarily true. A Java application may be may up of more than one class,
one of which contain a method main, which must be provided to the Java run-time
interpreter. The first statement inside this main method is the first statement to be
executed, regardless of the order in which the methods appear in the Java source file.
Review Question 3
For Java applets, the first statement of the first method in a class is the first statement
that is executed.
This is not necessarily true. A Java applet is formed by creating a new class that is a
subclass of the Applet class. This new class must have a constructor method (of the
same name as the class). The
The first statement of this constructor method is the first statement to be executed,
regardless of the order in which the methods appear in the Java source file.
Review Question 4
Review Question 5
The double variable allows greater precision (about 17 decimal places) than the float
(about 11 decimal places)
Review Question 6
In what crucial way is a String variable different from an int variable, apart from storing a
different kind of data?
int is a primitive type, it is part of the Java language. The word int itself is a keyword,
and can't used for anything else. String, on the other hand, is the name of a class.
String is not a keyword. Instructions on how to process Strings are not built into the
Java language, they are an extension to the language written in Java. An important use
of classes in Java is to provide ways of representing data that are not catered for with
the primitive data types. This is a moderately advanced topic, and not really part of this
course. However, the fact that String is a class and not a fundamental data type has
implications for all Java programmers. The way that strings are manipulated is slightly
different from the fundamental types, as you will see in a later unit.
Review Question 7
The < is a comparison operator. Like all comparison operators it will evaluate to a
boolean value of true or false. In the example given, if the variable age has a numeric
value less than 21, then the expression will evaluate to true, otherwise it will evaluate to
false.
Of course, if the variable age is not a type for which the < operator has been defined,
then the javac compiler will present a type error message, such as the following (in this
case age was declared as a reference to an instance of the Object class):
C:\CMT4120\unit03\comments>javac CommentMe.java
1 error
C:\CMT4120\unit03\comments>
Review Question 8
"1 + 2" + 3 + 4
The general rule with a String (i.e. "1 + 1") followed by the operator + is that what
follows the + will be converted into a string itself and appended. Thus the String "1 + 1"
has a String of "3" appended to it, and another "4" appended to it, so the result is a
String with the contents "1 + 234".
If we wanted the result of the addition 3 + 4 (i.e. 7) to be converted into a String and
appended, then we could place the expression (3 + 4) in parentheses, to ensure that
this addition is carried out first, and then the result of this addition (i.e. 7) then becomes
the operand for other parts of the larger expression. So we could write the Java code:
1 + 27
here are many new concepts in this unit. If you want to discuss with your colleagues or
make comments about the concepts to them, use the on-line facilities.
Complete exercises 4.21 and 4.22 from Chapter 4 of Deitel and Deitel and prepare for
discussion at the next tutorial session.
It is important that the compiler always associates an else with the previous if unless
told otherwise by using braces {}. Read pages 121 and 122 of Section 4.6 of chapter 4
of Deitel and Deitel
During the activities you should have learned that it is up to the programmer to decide
how data is to be represented, even for numbers.
What is the advantage of working this way? After all, with a pocket calculator, if one
wants to work out 2 divided by 5 it just gets on with it!
It isn't smart enough to understand that all the zeros don't matter to the result.
Clearly this is a much `bigger' (that is, longer) calculation than 2/5.
In summary, if there is a possibility that a result may not be a whole number, you need
to ensure that the Java compiler knows what to do.
Why does the programmer have to worry about this? As usual, the compiler doesn't
know anything about the logic of the program. Only you, the programmer, know that. If
you know that a number can only ever be an integer (for example, in the program
MultiplicationTable.java, we know that we are only interested in whole numbers. The
use of integer variables is quite appropriate here. However, if I was working with
calculations that might have fractional parts to the numbers, this would be a mistake. In
general, the designer of the Java language have assumed that in all cases the
programmer is smarter than the computer, and will be able to make better decisions
about this sort of thing.
Where the precision of variables is discussed during the module units, we have always
been careful to say, for example, ` about 17 decimal places'. Why can one not same
exactly how many decimal places a number can be represent as in Java?
(This question is kind of technical. Don't lose too much sleep if you can't figure it out)
Modern computers do not use the decimal numbering system internally. That is, their
number representation is not based on the number 10 as most human numbering
system are. Instead computers use the binary system, which has only two digits: zero
and one. I know exactly how many binary digits (bits) a double variable uses (it's 64, if
you're interested). But this does not correspond exactly to a fixed number of decimal
digits.
In your Learning Journal write up your experience of your learning on this unit. Say
what you thought was good or bad, what you had difficulty understanding, and how you
resolved your problems.
End of Unit Review
Before proceeding to the next unit you should work through this set of review questions.
When you have completed the questions you will be able to obtain the answers for
future reference.
Your performance with these questions will not affect your grade for the module, but
may be monitored so that your tutor can be alerted if you are having difficulty.
Please contact your tutor if you feel you have not done as well as you expected.
Code Listing
Listing of CommentMe.java
class CommentMe
System.out.println("line 1");
System.out.println("line 2");
System.out.println("line 3");
System.out.println("line 4");
Listing of Hello1.java
// does
// Hello1.java
// statement
import java.applet.Applet;
import java.awt.*;
// The open brace below denotes that all the statements that
// anything at all.
// This final brace denotes the end of the class `Hello1' and,
Listing of UnconditionalBranch.java
class UnconditionalBranch
void method2()
System.out.println("statementM1");
System.out.println("statementM2");
void method1()
System.out.println("statementA");
method2();
System.out.println("statementB");
}
///// don't worry too much about these next 2 methods
UnconditionalBranch()
method1();