You are on page 1of 63

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

Having successfully completed this unit you should be able to:

 Understand and use different categories of Java program statement


 Implement Java programs illustrating the use of sequence and selection control
statements
 Understand and use variables
 Understand and use expressions

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:

Disk-based Content: 2¼ hour


Application: 3 hours
Set textbook Content: 1 hour
Reflection (On-line discussions, review questions): 1 hour
Tutorial Work: 1 hour
Related Coursework: ¼ hour
Extension Work: ½ hour

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

Core texts (supplied with module material):

1. Java: how to program. H. M. Deitel and P. J. Deitel, 3rd edition, Prentice-


Hall, ISBN: 0-13-012507-5. Chapter 2 and 4 as indicated
in the content

Supplementary texts (available at LSC).

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

Program statements — Assigned reading

Read Chapter 2 pp.36-42.


Categories of program statements

The simple program below consists of a single class:TicketDiscount.java. Every Java


class is composed of program statements. Some statements, called compound
statements are comprised of more than one statement themselves.

class TicketDiscount
{
public static void main( String args[] )
{
int age;

// assign a random age (0 .. 99) to

// variable 'age'

age = (int) ( 100 * Math.random() );


System.out.println("age is: " + age);
if( age >= 60 )
{
System.out.println( age + "is 60 or over" );
System.out.println("qualifies for discount");
}
}
}

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

class declaration class TicketDiscount { ... }

method public static void main( String args[] ) { ... }


declaration

variable int age;


declaration

comment // assign a random age (0 .. 99) to

// variable 'age'
variable age = (int) ( 100 * Math.random() );
assignment

message sending System.out.println("age is: " + age);

control if( age >= 60 ) {...}

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 class

The second is the declaration of the main() method:


public static void main( String args[] )

// rest of method

The third is the set of statements to be executed if the test of age is true:
if( age >= 60 )

System.out.println( age + "is 60 or over" );

System.out.println("qualifies for discount");

}
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[] )

...

if( age >= 60 )

System.out.println( age + "is 60 or over" );

System.out.println("qualifies for discount");

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.

In terms of the number of keywords, Java is a small language.

In addition to keywords, Java statements are composed of things such as method


names, class names, literals (like 5, and 4.5 and "hello").

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

A comment is a sequence of characters ignored by the Java compiler and interpreter. In


Java, comments have one of these three forms:

// The rest of this line is a comment

/* Everything in this

section is a comment */

/** Everything in this section

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 use of extensive comments in computer programs is becoming less common in


modern practice, although some authorities still recommend it. The number of
comments in Hello1.java is excessive, and one would not normally comment a program
to this extent except for educational purposes. The reason for this is that while
comments can give human readers a good idea of what different parts of a program will
do when executed, what is hard to understand is the overall structure of the program.
This is where techniques like object-oriented design can help, as they document the
large-scale structure of a 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).

Consider the following program:

import java.io.*;

class CommentMe

public static void main( String args[] )


{

// display some text on screen

System.out.println("line 1");

System.out.println("line 2");

System.out.println("line 3");

System.out.println("line 4");

At present there is a single comment in this class:

// display some text on screen

the 4 lines following this comment will display 4 lines of text.

line 1
line 2
line 3
line 4

Press any key to continue ...

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

public static void main( String args[] )

// display some text on screen

// System.out.println("line 1");

System.out.println("line 2");
System.out.println("line 3");

System.out.println("line 4");

The output on screen is now:

line 2
line 3
line 4

Press any key to continue ...

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:

/* any characters between the slash-asterisk and asterisk-slash are ignored,


even on different lines */

For example we can comment out the 3rd and 4th output lines of our program as follows:

class CommentMe

public static void main( String args[] )

// display some text on screen

System.out.println("line 1");

System.out.println("line 2");

/* System.out.println("line 3");

System.out.println("line 4");

*/

}
}

The output on screen is now:

line 1
line 2

Press any key to continue ...

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.

Program statements — Activities and Exercises

Activity 1 – Comments

Activity 2

Exercise 1 – Program statements summary

Exercise 2

Control of execution

Control of execution — Assigned reading

Read Chapter 4 of Deitel & Deitel sections 4.1 - 4.6


(pp 113-122 inclusive)

How does the interpreter decide which statement to execute next?


Consider the Java application BallWorld (version 1 from unit 2, with comments removed
to make listing shorter):

import java.awt.*;

public class BallWorld extends Frame

////////// variables ///////////

private Ball myBall;

///////////// methods //////////

static public void main (String [] args)

BallWorld world = new BallWorld ();

world.show ();

private BallWorld ()

setSize(600, 400);

setTitle("Ball World");

myBall = new Ball(100, 100, 50, 4, 5);

public void paint(Graphics g)

myBall.paint( g );

pause( 2000 );

System.exit(0);

private void pause(int numMilliseconds)

{
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.

.Where does my program start?

The answer to these questions is different for Java applications and Java applets.

Where does a Java application start?

A Java application is composed of 1 or more classes. When the Java run-time


interpreter is instructed to begin executing a Java application, it must be provided with a
class that contains a method called 'main'. The first statement to be executed for a
Java application is the first statement inside this main class's method main.

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

private Ball myBall;

static public void main (String [] args)

BallWorld world = new BallWorld ();

world.show ();

private BallWorld ()

{ // implementation of BallWorld constructor class }

public void paint(Graphics g)

{ // implementation of paint method }

private void pause(int numMilliseconds)

{ // implementation of pause method }

} // class BallWorld

The first statement inside this class's main method will be the first statement of the
application to be executed, i.e.:

BallWorld world = new BallWorld ();

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.

Where does a Java applet start?

For an applet, the main class is the one referred to in the <applet> tag of the HTML file,
e.g.,

<applet code=MyClass width = 300 height=300>

</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:

The following applet will display a message on the screen.

//AppletGreetings.java

import java.awt.*;

import java.applet.Applet;

public class AppletGreetings extends Applet {

public void paint (Graphics g){

g.drawString(" Welcome to CMT4120", 50,50);

You first compile the AppletGreetings.java using TextPad:

The HTML file is:

<applet code="AppletGreetings.class" width=300 height=50>

</applet>

You can then run the HTML file from TextPad using clicking Tools and selecting Run
Java Applet.

When does my program stop?

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.

When does a Java application stop?

A Java application stops when the main method has finished executing.

When does a Java applet stop?

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:

 it executes the statements of the method in the sequence they occur


 it encounters a control statement, which results in a branch of execution out of
sequence

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 );

ageInDecades = (age % 10);

The first statement to be executed will be:

age = 21;

The second statement to be executed will be:

ageNextBirthday = ( age + 1 );

The third statement to be executed will be:

ageInDecades = (age % 10);

Branching of execution

There is some history associated with the branching of control in computer


programming. Your computer's hardware probably provides supports for arbitrary
branching, i.e., from any point in the program to any other. However, it was found in the
1960s that arbitrary branching was difficult to understand and test.

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).

Java offers 3 kinds of branch of execution flow:

 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.

Method invocation (subroutines) in Java

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.

A note on methods and subroutines

In programming languages that are not object-oriented something similar to method


invocation is achieved through subroutines. A subroutine is a mechanism for the
execution of a series of instructions elsewhere in a program, then returning to the
original point. The whole idea of subroutines is considered rather old-fashioned these
days, although some, usually much more sophisticated, equivalent can be found is the
majority of modern programming languages.

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.

Consider this pseudocode design for part of a class:

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.

A program listing of a class UncontionalBranch (the listing is UnconditionalBranch.java)


is available to examine, compile, modify etc. if you wish to explore these issues now.
Although a later unit will present a more detailed investigation of the relationship
between messages, classes, objects and methods.

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 ( temperature too high )

sound the alarm

This illustrates the general form of an if statement, i.e.:

if <test>

action to perform if test is true

To implement our fire alarm pseudocode as a valid Java statement we could write the
following:

if (temperature > 78)

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;

if( age > 60 )

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 ( temperature too high )

sound the alarm

This illustrates the general form of an if statement, i.e.:

if <test>

action to perform if test is true

To implement our fire alarm pseudocode as a valid Java statement we could write the
following:

if (temperature > 78)

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;

if( age > 60 )

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' with compound statement

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:

if (temperature > 78)

soundAlarm();

displayFlashingLight( red );
triggerAlarmAtFireStation();

program statements and control of execution concept map

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.

Control of execution — Exercises

Exercise 3 – Control of execution summary


Variables

Variables — Assigned reading

Read Chapter 4 of Deitel & Deitel chapter 2 section 2.4 (pages 52,53) and
chapter 4 section 4.13

Variables, constants and literals

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.

In the implementation of methods, as well as class and instance variables, temporary


(local) variables are often needed (for counting, or storing the intermediate results of
calculations etc.).

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.

Java offers three categories of variable types:


 objects
 primitive types
 arrays (ordered collections of variables)

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.

Some primitive data types available in Java

As well as having an identifier (name), variables have a type. We have already


encountered `int' (an integer). Below is a list of the most important primitive types. By
primitive it is meant 'built into the language'.

 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)

Categories of primitive type

There are 4 categories of primitive type:

 whole number types


 real (decimal) number types
 characters
 boolean (true or false)

Each shall be briefly covered in this section (and is covered in detail in the Deitel &
Deitel chapters).

Whole number types


Java offer ways to represent and work with 4 different types of whole number. The only
difference between them is the range of values they can represent.

The four whole number types are:

 int
 byte
 short
 long

For most of your programs you will probably find that the int type is sufficient.

Real number types

A real number can have values that are in between integers. The informal way to
describe such number in English is as 'decimal' numbers.

Examples of real numbers include: 0.0, 34.6, 99.2, -0.002 etc.

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.

The two floating point number types are:

 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

Java will evaluate this expression to a value of type double.

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.

Examples of char values include:

 'm'
 ' ' (space)
 '='
 '5'
 'A'

An example of some code declaring and initialising a char variable is as follows:

char carYearLetter = '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.

Examples of code that might use such a variable include:

boolean holdsDriversLicence = true;

if( holdsDriversLicence )

processCarHire();

else

displayMessage("You cannot hire a car without a licence!");

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.

Declaring and assigning values to variables


Java is called a 'strongly typed' language because the Java compiler will not allow a
variable to be referred to in a program unless it has been declared. In addition, values
cannot be assigned to variables if the value and variable have different types. A variable
declaration is a statement that defines the identifier (name) and type of a variable.

Examples of variable declarations include:

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:

int numberOfRecords = 20;


double temperature = 0;

char firstInitial = 'm';

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

public static void main( String args[] )

int age = 0.05;

the output from the compiler was:

A:\Unit3\TypeError.java:15: possible loss of precision


found : double
required: int
int age = 0.05;
^
1 error
This error message occurs because, of course, a real value of 0.05 cannot be stored
inside a variable of type int. Notice how the compiler has assumed that 0.05 is of type
double automatically (rather than of type float).

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:

Explicit cast needed to convert double to int.

It is possible to covert a value from one type to another by a technique called casting.

Assigning values to variables

Although it is possible to assign an initial value to a variable when it is first declared,


variables will usually have their value changed one or more times during the execution
of the program. This makes sense, since variables by their nature are designed to have
their values changed (i.e. vary) — if the value is not to change one should define a
constant instead.

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);

nextAge = (age + 1);

stockLevel = 100;

stockLevel = (stockLevel + deliverySize);

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

public static void main( String args[] )

int completeCars;

double carsProduced = 200271.5 ;

completeCars = (int) carsProduced;

System.out.println("value in completeCars is: " + completeCars);

}
When compiled and run this program produces the following output:

value in completeCars is: 200271

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:

final double pi = 3.1415926;

final int numberOfSidesInATriangle = 3;

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:

final int frameWidth = 600;

final int frameHeight = 400;

In fact, as they appeared in the application, these constants were declared with two
more keywords:

public static final int frameWidth = 600;

public static final int frameHeight = 400;

however, we shall leave investigation of the keywords public and static until later
units.

Naming things in Java (identifiers)

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:

 identifiers cannot be the same as a keyword


 identifiers are case-sensitive
 identifiers cannot contain spaces or most punctuation characters

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

 names of classes start with a capital letter


 names of everything else start with a lower-case letter
 if name is a phrase rather than a word, then capital letters are used to separate
the words

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!

What about confusion between variable and method identifiers?

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

Exercise 4 – Bit size of primitive types

Exercise 5 – Variables summary

Expressions

Expressions — Assigned reading

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

An expression is a mathematical term, describing a part of a program statement that


evaluates to a single value. Of course, in Java the type of value can be an object, an
array or a primitive type.

Expressions are composed of operators and operands.

Expressions may be simple, such as:

which simply evaluates to itself, i.e. the integer constant 7.

Expressions can be complex, such as:

netTax = (float) 35.75 * ( grossEarnings + operatingProfit( 1999 ) )

which involves:

 floating point constants — 37.75


 conversion between types — casting using (float)
 variables — grossEarnings
 message passing (with arguments) and replies — operatingProfit( 1999 )

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

There are several operators provided by Java for numeric expressions.

Examples of numeric expressions include the following:

2 + 2

age + 1

25 / 5

2.5 * 4

15 % 4

The implementation of the most common numeric operators in Java are as follows:

Operation Java example evaluates


symbol to

addition + 2+2 4

subtraction - 5-2 3

multiplication * 2.5 * 4 10.0

division / 5/2 2.5

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

A boolean expression is one that evaluates to a result of either true or false.

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) )

//... more statements here

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)

//... more statements here

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.

The similarity of the assignment and equality comparison operators

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:

x = false; while (x)

which 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.

Other kinds of expression

An expression can evaluate to any of the types Java supports — i.e.:

 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.

Variables and Expressions concept map

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.

Expressions — Activities and Exercises

Activity 3 – Addition applet

Activity 4 – example program 'MultiplicationTable.java'

Exercise 6 – Expressions summary

Exercise 7 – Addition expression

Exercise 8

Writing Interactive Programs - Activities

A note on displaying applications using Windows rather than a text screen

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.

The following isGreetings.javaexample written using thejavax.swing.JOptionPane

line Source code statements of the application GreetingsVersion2.java


1 import javax.swing.JOptionPane;

2 public class GreetingsVersion2{

public static void main(String[] args)


3
{
4
JOptionPane.showMessageDialog(null, "Good afternoon ");
5
System.exit(0);

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 2 begins the class definition forclass GreetingsVersion2.It is important to remember


that the file in which the program is saved has to have the same name
i.e.GreetingsVersion2.java

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 4 sends a message showMessageDialog toJOptionPane. TheshowMessageDialog is


a method with two arguments, the first of which is alwaysnull, and the second a String to
be displayed. The method is static, which means that it is called using class name ‘.’
method name, rather than object name ‘.’ method name.

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.

Writing Interactive Programs


The first examples only had output, and data was either ‘hardcoded’ (fixed) or
generated by the programs. We are more accustomed to interactive work, which means
input of data to a program usually from the keyboard and – output from the program
usually on the screen.

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.

line Source code statements of the application TicketDiscount.java


1 import java.io.*;

2 class TicketDiscount {

public static void main( String args[] )


3
{
4
int age;
5
age = (int) ( 100 * Math.random() );
6
System.out.println("age is: " + age);
7
if( age >= 60 )
8 {

9 System.out.println( age + "is 60 or over" );

System.out.println("qualifies for discount");

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.

A note on Java input and output

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.

Line 8 reads a line of input.

Line 9 converts the input String to an integer.

line Source code statements of the application TicketDiscountVersion2.java


1 import java.io.*;

2 class TicketDiscountVersion2 {

public static void main( String args[] ) throws IOException


3
{
4
int age;
5
String s;
6
BufferedReader in =new BufferedReader(new
7
InputStreamReader(System.in));

8 System.out.print("Enter age: ");

9 s = in.readLine();

10 age = Integer.parseInt(s);

11 if( age >= 60 )


12 {

System.out.println( age + " is 60 or over" );


13
System.out.println("qualifies for discount");
14
}

else

System.out.println( "Sorry no discount");

The changes made to the program lines 3, 5, 6, 7, 8, 9, 13, 14 are shown in boldface
font.

If the user enter 54 the output will be:

Enter age: 54
Sorry no discount

Using the JOptionPane dialog box

Source code statements of the application TicketDiscountVersion3.java


import javax.swing.JOptionPane;

public class TicketDiscountVersion3{

public static void main(String[] args)

String s;

s = JOptionPane.showInputDialog("Enter age: ");

int age = Integer.parseInt(s);

if( age >= 60 )

JOptionPane.showMessageDialog( null, age + " is 60


or over\n qualifies for discount");

else

JOptionPane.showMessageDialog(null, "Sorry no

discount");

System.exit(0);

The output would be as follows:

When user inputs the number 60 and presses OK,

the message is displayed is :

Activity 5Interactive AdditionApplet

Activity 1 – Comments

(1) Create and save a file based on the listing CommentMe.java .

(2) Compile and execute this application.

(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

(2) your screen should look similar to the following:

(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

public static void main( String args[] )

// display some text on screen

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

public static void main( String args[] )

// display some text on screen

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

public static void main( String args[] )

// display some text on screen

// 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

public static void main( String args[] )

// display some text on screen

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

public static void main( String args[] )

// display some text on screen

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

Complete exercise 2.20 from chapter 2 of Deitel and Deitel.

Activity 3 – Addition applet

(1) Compile and run the applet Add1.java.

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.

Discussion/Suggested solution to Activity 3

(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!)

(e) Please refer to Mult1.java

(f) Please refer to Div1.java

Activity 4 – example program 'MultiplicationTable.java'

Look at the program MultiplicationTable.java and answer

the questions in it.


Discussion/Suggested solution to Activity 4

(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.

Activity 5 – Interactive AdditionApplet

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.

A Java class consists of a sequence of __________.

A group of statements can be treated as a single statement by placing an open _____


before the group, and a close _____ character after the group. Such a group of
statements is called a ________ statement.

With the exception of compound statements, a ____-_____ character should be placed


at the end of every statement.

Discussion of Exercise 1

Suggested completed summary statements are as follows:

A Java class consists of a sequence of statements.

A group of statements can be treated as a single statement by placing an open brace


before the group, and a close brace character after the group. Such a group of
statements is called a compound statement.

With the exception of compound statements, a semi-colon character should be placed


at the end of every statement.

Exercise 2

Complete exercises 2.22 – 2.24 from chapter 2 of Deitel and Deitel.

Exercise 3 – Control of execution summary

Fill in the blanks for this summary of flow of execution:

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.

A deviation from execution in sequence is called a ______.

There are three different categories of branching: selection, iteration, and


_____________ branching.

Discussion of Exercise 3

Suggested completed summary statements are as follows:

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.

The computer executes in an order determined by the program statements. Unless


otherwise specified, statements will be executed in sequence, i.e. one instruction after
another in the order they occur.

A deviation from execution in sequence is called a branch.

There are three different categories of branching: selection, iteration, and unconditional
branching.

Exercise 4 – Bit size of primitive types

(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)

(2) float (32 bits), double (64 bits)

(3) boolean (1 bit), char (16 bits)

Exercise 5 – Variables summary

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.

A constant is any named piece of data that cannot change.

A literal is like a constant without a name, for example 2 or "Hello" .

The term for the name of a variable or constant is '__________'.

Variables and constants have:

an identifier

a ____

a ____

Discussion of Exercise 5

Suggested completed summary statements are as follows:

A variable is any named piece of data that can change during the execution of a
program.

A constant is any named piece of data that cannot change.

A literal is like a constant without a name, for example 2 or "Hello".

The term for the name of a variable or constant is 'identifier'.


Variables and constants have:

an identifier

a type

a value

Exercise 6 – Expressions summary

Complete the following statements that summarize the concepts explored in the
'Expressions' section of this unit.

Fill in the blanks for this summary of expressions:

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 _

_______ than >

Comparisons can be combined using the _______ operations of:

___ &&

or __

Discussion of Exercise 6

Suggested completed summary statements are as follows:

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 !=

less than <

greater than >

Comparisons can be combined using the logical operations of:

and &&

or ||

Exercise 7 – Addition expression

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

System.out.println( "2+2 is" );


System.out.println( 2+2 );
System.out.println( "3+3 is" );
System.out.println( 3+3);

Exercise 8

8 complete exercises 2.13, 2.14, 2.15 from chapter 2 of Deitel and Deitel

Review Question 1

What would be displayed on execution of the following section of Java:

// System.out.println ("Hello");

Discussion of Review Question 1


Nothing. This is marked as a comment (using //)

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.

Discussion of Review Question 2

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.

Discussion of Review Question 3

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

Fill in the blanks for this summary of unconditional branching of execution:

_______ often involve an exchange of data as well as a branch. In a method, execution


returns to the statement _________ the method invocation call (except in certain _____
conditions).
Discussion of Review Question 4

Methods often involve an exchange of data as well as a branch. In a method, execution


returns to the statement following the method invocation call (except in certain error
conditions).

Review Question 5

What is the difference between a float variable and a double variable?

Discussion of 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?

Discussion of Review Question 6

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

To what type would the following expression evaluate:


(age < 21)

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

CommentMe.java:7: Incompatible type for <. Can't convert java.lang.Object to


int.

System.out.println( (age < 21) );

1 error

C:\CMT4120\unit03\comments>

Review Question 8

To what would the following expression evaluate:

"1 + 2" + 3 + 4

Discussion of Review Question 8

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:

System.out.println( "1 + 2" + (3 + 4) );


and we would get the output of:

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.

Discussion Topic 1 – The Dangling-Else Problem

Complete exercises 4.21 and 4.22 from Chapter 4 of Deitel and Deitel and prepare for
discussion at the next tutorial session.

Contribution for Discussion Topic 1

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

Discussion Topic 2 – Programmer's choice of numeric data type

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!

Contribution for Discussion Topic 2

It's all down to efficiency.

The computer represents numbers internally to a precision of about 17 decimal places


(this is an oversimplification, but it's close enough for now).

So when we work out `2.0/5.0', the computer is really working out


`2.00000000000000000/5.00000000000000000'.

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.

Discussion Topic 3 – Java representation of decimal places

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)

Contribution for Discussion Topic 3

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.

Reflection on Learning Experience

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

public static void main( String args[] )

/ / display some text on screen

System.out.println("line 1");

System.out.println("line 2");

System.out.println("line 3");

System.out.println("line 4");

Listing of Hello1.java

/ / This is a `comment'. You can tell because the


// lines start with `//'. These lines are all

// ignored by the Java compiler, so you can write

// whatever you like. At the very least you should

// start with a comment saying what the program

// does

// Note that this program has far more comments than

// real program statements; this would probably not

// be the case in most real programs.

// Hello1.java

// A program that displays a message

// Kevin Boone, May 1999

// The first real (i.e., non-comment) line of the program is `import'

// This tells the compiler what classes to use apart

// from any defined in this program. In this case

// I tell the compiler to consider using any of the

// classes that are part of the `package' java.awt.

// and the class `Applet'

// I have to do that because the program uses the

// Class `Applet' to do most of the work, and this

// class is defined in the java.applet package and

// the java.awt package.

// Most Java programs will start with an `import'

// statement

import java.applet.Applet;

import java.awt.*;

// So now down to work. Define a class. All java programs


// have at least one class. In this case we are writing an

// applet, so the new class is a type of applet. `extends'

// means, essentially, `is a type of'.

// Note that Java rules stipulate that a `public' class

// must be defined in a file of the same

// name, i.e., Hello1 must be defined in `Hello1.java'

public class Hello1 extends Applet

// The open brace below denotes that all the statements that

// follow are part of the class Hello1, until the matching

// closing brace at the end of the program

// Now we define an method called `paint'. Providing this

// method ensures that when the program starts up,

// something useful will happen.

// If we do not provide a `paint' method, then the program

// will compile and run correctly, but it won't display

// anything at all.

// The concept of an `method' will be covered in more detail

// later in the course

public void paint (Graphics g)

// Now the program text is `indented', this is,

// all the lines start a few spaces from the

// left margin. Doing this makes it easy for the

// (human) reader to identify all the lines that

// are part of `paint'. The computer does not


// care about this, but people will find the

// program easier to understand

// `drawString' is an method in the class called

// Graphics. Its job is simply to display text in

// an area of the screen. In this case the text is

// positioned 20 pixels across, and 20 pixels down

g.drawString ("Welcome to INT4120", 20, 20);

// This final brace denotes the end of the class `Hello1' and,

// in this case, the end of the program

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

///// just explore how the sending of messages can influence

///// the flow of execution of statements in method1()

UnconditionalBranch()

method1();

public static void main( String args[])

UnconditionalBranch app = new UnconditionalBranch();

You might also like