- •Lecture 1 Programs and algorithms
- •1.1. How a computer operates?
- •1.2. Algorithms and programming languages
- •If (condition) then ... Or if (condition) then ... Else ...
- •1.3. Summary
- •1.4. Exercises
- •Lecture 2 Fundamentals of programming I
- •2.1. The language
- •2.2. Quick start: first program and basics of syntax
- •2.3. Data in a program (variables and literals)
- •2.4. Operations on data (operators and expressions)
- •2.5. Summary
- •2.6. Exercises
- •Lecture 3 Fundamentals of programming II
- •3.1. Making decisions
- •3.2. Iterations
- •3.3. Arrays
- •3.4. Functions
- •3.5. Summary
- •3.6. Exercises
- •Lecture 4 Java and object-oriented methodology
- •4.1. What is Java
- •4.1.1 Java as a universal programming language
- •4.1.2. Java as a cross-platform language
- •4.1.3. Java as a universal environment for gui programming
- •4.1.4. Java as a universal environment for accessing data bases
- •4.1.5. Java as a universal multimedia programming environment
- •4.1.6. Java as a universal means for client-server programming
- •4.1.7. Java in a distributed environment
- •4.1.8. Java as an environment for building applications from ready-to-use components.
- •4.1.9. Java as the environment for xml processing
- •4.1.10. Micro Java
- •4.1.11. Why is Java worth learning?
- •4.2. Introduction to objects
- •4.4. The first program
- •5.2. Literals
- •5.3. Types of variables. Declarations.
- •Type_name variable_name;
- •Identifiers
- •Naming conventions:
- •5.4. More on operators and expressions
- •5.5. Numeric promotions
- •5.6. Summary
- •5.7. Exercises
- •Lecture 6 Objects
- •6.1. Objects and references
- •6.2. The class String
- •6.3. Useful examples
- •6.4. Summary
- •7.2. Defining attributes of objects
- •7.3. Defining operations on objects (methods)
- •7.4 Defining methods of object creation (constructors)
- •7.5. Example
- •7.6. Inheritance
- •7.7. Summary
- •7.8. Exercises
- •Lecture 8 Classes II
- •8.1. Accessing class members. The variable this.
- •8.2. Static members
- •AClassName.AFieldName
- •8.3. Explicit initialization
- •8.4. Packages and imports
- •8.5. Scope of an identifier. Local variables. Access control.
- •8.6. Structure of a program. Running an application.
- •8.7. Summary
- •8.8. Exercises
- •Lecture 9 Decisions
- •9.1. A brief survey of control statements.
- •9.2. Comparison operators and expressions
- •9.3. Logical operators and expressions
- •9.4. Making decisions: the if and if-else statements.
- •9.5. Multivariant selections done with the switch statement.
- •9.6. The conditional operator ?:
- •9.7. Summary
- •9.8. Exercises
5.6. Summary
The lecture introduced:
the notion of type
types in Java, especially the primitive types
literals
declarations of variables
identifiers and Java naming conventions
basic operators, particularly arithmetical operators
expressions and operator precedence
numeric promotions
This knowledge enables us to write simple programs performing various calculations correctly. However, proper declarations of variables and use of literals will become important later when our programs become more complex.
5.7. Exercises
Write in Java a program converting temperatures given in Fahrenheit degrees to Celsius. Input data (temperature given in Fahrenheit) should be stored in some variable.
Write a program calculating the cost of purchase of some articles. It should display the overall cost of all articles and each article's share in this cost. An article is characterized by its price and quantity (for example, apples - 1 kg, price for 1 kg - 3 EUR).
Write a program printing Unicode values of characters of some language.
Lecture 6 Objects
Programming in Java deals with objects. The notion of object was introduced in lecture 4. Now we want to describe how objects are represented in Java.
6.1. Objects and references
Except for operations on numbers, programming in Java consists in using objects. Objects are instances of classes. For example, strings (sequences of characters) are objects of the class String, which defines common properties of objects of this type. The class String is one of many ready-to-use standard classes included in the Java 2 SDK environment. A programmer may define his or her own classes (soon we will see how to do this). He or she may also use classes defined by other programmers (not necessarily included in Java 2 SDK). Recall that we use objects to call (invoke) their methods (in other words: to send messages to objects) which are a special kind of functions. Let us assume that someone has created a class called Pair. Its objects represent pairs of integers - each object is made up of two elements which are integer numbers (first and second component of a pair). What we can do with objects of the class Pair is specified by the set of methods of this class. Assume further that the following methods are defined in the class Pair (i.e. its objects understand the following messages):
set - setting the value of the pair (both components)
show - printing the pair (displaying its components to the command prompt)
This information is enough to use objects of the class Pair (we will learn its definition in the following lectures). What should we do to set the value of a pair and print it to the command prompt? Firstly, we must create a variable referencing an object which represents a pair. Secondly, we must create an object of the class Pair. Thirdly, we must send messages (set and show) to this object. Here is the program:
public class PairSetAndShow {
public static void main(String[] args) {
Pair pair1 = new Pair(); // 1
pair1.set( 1, 2 ); // 2
pair1.show(); // 3
}
}
and its output:
( 1 , 2 )
What is going on here:
In the line denoted by 1 we declare the variable pair1 and we create an object of the class Pair with the help of the new expression. As can be easily seen, the new expression consists of the keyword new and the name of a class with braces appended. Between the braces the information needed for creating an object may be added (as arguments). Here we do not pass any information. After the next lecture we will understand why the new expression has such a form.
Now we have the object and the variable pair1 which enables operations on this object.
In the line 2 we send the message set to the object referenced by the variable pair1. To send a message we have to select an object which will receive it. For this purpose the dot (.) character is used, called selector in this context. The name after the string "pair1." is the name of the message ("set") sent to the object referenced by the variable pair1. Between the braces arguments to the message are specified. The first is the value which will be assigned to the first component of the pair. Similarly, the second argument will initialize the second component. Thus, the expression pair1.set(1,2); sets value of the first component of the object (pair of integers) referenced by the variable pair1 to 1 and sets value of the second to 2.
In the line 3 the object denoted by pair1 receives the message show. As result the pair is printed to the command prompt in the format: (value_of_the_first_component, value_of_the_second_component) - it this case it gives: (1, 2).
What
does the expression "object referenced by the variable pair1"
mean? Why don't we say "an object pair1" although we do say
"an integer number x"? What really is the variable pair1?
As we have seen, it was declared. But there appeared some
strange formula creating an object.
What happens if we simply
write:
Pair pair1;
pair1.set( 1, 2 );
pair1.show();
As stated earlier, declarations of
variables referencing objects are noted analogously to declarations
of variables of primitive types.
int x; // declaration of
a variable of type int
Pair p; // declaration of a variable p
which holds a reference to an object of the class Pair
However,
there is a subtle semantic distinction between these two
declarations.
The declaration of the variable x allocates
memory to storing an integer (4 bytes). Thus x is a synonym for a
data unit - an integer number.
After the assignment x = 4; to
the location in memory denoted by x the value 4 is stored. This
situation is depicted on the figure:
A
declaration of a numeric variable x creates an "object" in
memory - an integer number (before its value is explicitly set, it
has some default value - mostly 0).
By the declaration of
a variable holding reference to an object of some class the situation
is completely different. Such a declaration does not create any
object (it does not allocate memory for storing the object).
The
object must be created using the expression new.
Its application results in the allocation of memory space for
objects. The memory is allocated in its dynamic part (changing during
the execution of a program) called heap.
The value of the new
expression is the location in memory of the created object. This
location can be stored in the variable, which is then used to
manipulate object.
Thus, the declaration:
Pair
p;
does not create
any object of the class Pair.
And if there is no object,
we cannot send any messages to it. That is why p.set(...) and
p.show() are incorrect calls.
The variable p does not
store any object.
However it may hold its location called also
a reference
to an object.
A reference is a value denoting location of an object in memory.
An
object of the class Pair may be created using the expression new
Pair(). By storing its value to the variable p, we gain the
possibility to manipulate this object:
Pair p;
p =
new Pair();
It may be noted simpler using the
initializer:
Pair p = new Pair();
The
following figure explains the problem:
where:
Allocation of memory space for the variable p storing a reference to an object. The value of the reference is null which means it does not refer to any existing object.
Evaluation of the expression new results in allocation of heap storage for the object of the class Pair (using some available address, here: 1304). The size of the allocated space is big enough to store two integer numbers (the components of the pair). Now both components have values 0.
The value of the expression new is reference (or address 1304 in other words). It is stored in the memory space allocated for the variable p.
The variable p has the value of the reference to the object of the class Pair. In step 2 this object was allocated on the heap under the address 1304.
Thus, the variable p holds a reference to the object of the class Pair. As it was noted earlier, a variable p may refer to an object of the class Pair. But it does not always hold a reference to an existing object. After a declaration, but before its initialization, a variable does not hold any reference because no object has been created yet. Now the question arises: what is the type of the variable p? In general: what is the type of variables denoting objects? In Java, besides numeric types and boolean type there is just one more type: the reference type.
All variables declared with a class name in place of a type name are of reference type. Such variables may hold references to existing objects or they hold no reference at all.
If a variable of the reference type does not hold any reference to an object its value is null which is a keyword of the language. Thus, acceptable values for variables of reference type are references to objects or null. Similarly to 1 which is a literal of type int - null is the literal of reference type. References are comparable:
== is test for equality
!= is test for inequality
To a variable of reference type value of another reference or null can be assigned. One must remember that the above operations carried out on variables denoting objects (references) act on references themselves, not objects they refer to. Operations on objects are carried out by means of method invocations (using the dot operator). Assume we want to carry out similar operations on two data elements being integer numbers and another two being objects of the class Pair:
set the value of the first data element and set the value of the second data element
assign to the variable denoting the second data element the value of the variable denoting the first data element.
modify the value of the second data element
compare variables denoting both data elements
Additionally (in both cases) we introduce the third data element whose value will be set to the value of the second data element. Then we compare the variables denoting these data elements (the second and the third). Here is the program:
public class Difference {
public static void main(String[] args) {
// Operations on variables of primitive types
int x, y, z;
x = 3;
y = 4;
x = y;
y = 5;
z = 5;
System.out.println("x = " + x);
System.out.println("y = " + y);
System.out.println("z = " + z);
if (x == y) System.out.println ("x and y are equal.");
else System.out.println ("x and y are not equal.");
if (y == z) System.out.println ("y and z are equal.");
else System.out.println ("y and z are not equal.");
// Analogous operations on variables of reference type
Pair px = new Pair(), py = new Pair(), pz = new Pair();
px.set( 3, 3 );
py.set( 4, 4 );
pz.set( 5, 5 );
px = py;
py.set( 5, 5 );
System.out.print("Pair px: "); px.show();
System.out.print("Pair py: "); py.show();
System.out.print("Pair pz: "); pz.show();
if (px == py) System.out.println ("px and py equal.");
else System.out.println ("px and py are not equal.");
if (py == pz) System.out.println ("py and pz equal.");
else System.out.println ("py and pz are not equal.");
}
}
x = 4 y = 5 z = 5 x and y are not equal. y and z are equal. Para px: ( 5 , 5 ) Para py: ( 5 , 5 ) Para pz: ( 5 , 5 ) px and py are equal. py and pz are not equal.
The output of the program may be a surprise for those, who do not understand the differences between operations on variables of primitive types and of the reference type. The following observations clarify the program's output:
The expression new Pair() is a reference to a newly created object of the class Pair. Such references are stored in variables of type Pair (which is a reference type).
Invocation of the method set() sets values of data elements in an object of the class Pair. Such an object is accessed using a reference to it (px.set(...)).
The assignment py = px results in copying a reference py (the value referring to the object with elements [3,3]) to the variable px (which referred to the object with elements [4,4] to that moment). Following the assignment, px and py refer to the same object (which is the pair with elements [3,3]). The pair with elements [4,4] is no longer accessible.
New values for elements of the pair denoted by py are set using the reference py (py.set(5,5)). But both py and px denote the same pair (object), so invocations of the method show() print identical output (the elements of the pair [5,5]).
The result of comparison of the references px and py is true, because both variables refer to the same object (not because they refer to distinct objects with the same values of elements).
The comparison of py and pz proves the above fact: py and pz refer to distinct objects (values of these variables are different), so the result of the comparison is false, although the values of the elements of both objects are equal [5,5].
What has happened to the object with the values of elements [4,4] which was initially referenced by the variable py? This object was allocated on the heap with the expression py = new Pair(), so it occupies some space in memory. Afterwards values of its elements were modified (py.set(4,4)), so these values were stored into that memory space. Then to the variable py the value of the variable px was assigned. Thus there are no references to this object left in the program. Because objects can be accessed only using references, this object is no longer accessible. However, it occupies some space. Should we worry about it? If there appeared more such objects in memory, would it cause memory overflow? Fortunately it would not.
Unused objects (which are not referenced by any variable) are removed from the memory automatically by the garbage collector.
Let us sum up:
Objects are created using the expression new ...
Objects are manipulated using references and calling methods.
References are not objects - they refer to objects.
Variables of reference type must be declared before they are used in the program.
Declaration of reference does not create any object.
