Escolar Documentos
Profissional Documentos
Cultura Documentos
www.cscourses.com
Lesson 10 POLYMORPHISM
File: JavaL1.doc
INTRODUCTION
This manual introduces the Java programming language techniques and concepts. Java is a new
language designed for Internet programming. When you connect to a WEB page a Java applet may
be downloaded to your browser to start a special effect on your screen. An applet is a program
written in Java. The Java language has built in interfaces to the Internet. The Java language has now
found it way into the University environment. It is a great teaching language, it is rich in graphics
and good language constructs. Java uses the Object Oriented Programming (OOP) approach. This
approach uses a programming language to describe an object. What is an Object? An Object is an
everyday thing, a car, house, table or even a person. Every object has an appearance and does
something. A car has a shape, a color and moves. The object oriented programming approach,
wants to represent everyday objects in a programming language. How can it do this? A
programming language can store the appearance of an object as a value in the computer memory. A
programming language also has programming statements that are instructions telling the
computer what the object does. When a computer stores information about an object, the stored
information is known as data. The data is information that describes the objects and is stored in the
computer memory. The location where the data is stored is represented by a variable having a
name. A programming statement is used to describe what an object does and is translated into
code. Code is used to run on the computer to perform some action or operation for the object. The
code is the translated instructions telling the computer what to do. The programming language
groups programming statements together into what is known as a method. A method is a collection
of programming statements that get translated into code and runs on your computer. Before you
can have an object you need a definition of the object. A class is used to define an object. The class
lists all the methods and variables needed by the object. A class defines the variables for the object
and the code used to access the data in the object. The same code can be used for many of the
same objects. Think that a class is the drawings or a plan to build a house. When the house is made
then it is an object. When you class runs on the computer it is an object. An object is allocated
memory for the data variables defined in the class.
Variables Data
(storage for variables
Objects are created in the computer memory from the class definitions. The class definitions tell
what data and methods your object needs. Memory in the computer is allocated for the variables
defined in the class definition. It is these created objects that use computer memory for data when
you run your Java program. The Object Oriented Programming approach will enable you to organize
your programs so that your programming tasks will be much easier to accomplish. Answer this
question: What is the difference between a class and an object?
This manual teaches by using the analogy approach. This approach makes it easier for you to
understand new concepts by comparing the operation to common known principles. We also use the
seeing approach, the words we use, are carefully chosen so that you get a picture of what is
happening. Visualization is a very powerful concept to understanding programming. Once you get
the picture of what is happening then the programming concept is much easier to understand and
accomplish. It is very important to visualize and see things as a picture rather than trying to
understand by reading and memorizing textbooks. Pictures are made up of words. This document
does not cover all details of Java programming but acts as a guide so that you can get started right
away with Java programming. The main purpose of this document is to introduce, and teach you
Java and Object Oriented Programming techniques. You should have a textbook as a companion to
look up important terms for clarification or for more in depth study. Good textbooks are:
Core Java Volume 1 Gary Cornell, Cay s. Horstmahn SunSoft Press http://www.horstmann.com/corejava.html
The purpose of a programming language is to direct a computer to do what you want it to do. In
most cases of beginners the computer tells the programmer what to do. Good programmers are in
control of the computer operation. A computer program lets the user enter data from the keyboard,
perform some calculation to solve some problem and then displays the results on the computer
screen. The user can store input and output data on a data file for future use.
You may use these lessons as a study guide or to learn java programming. There are 14 lessons in
the Java course, where the last lesson is a java project. Each lesson consists of exercises that you
can send in for marking. You should understand all the material and do all the exercises in each
lesson before proceeding to the next lesson. There is a marking charge of $15 for each lesson.
Additional java tutoring is available from $15 and up. Grading is based on the assignments. (P) Pass,
(G) Good and (E) Excellent. Excellent is awarded to students with outstanding programs that involve
creativity and works of genius. Good is awarded to students that have exceptional working
programs. Pass is awarded to students that have minimal working programs. Important concepts
and Java keywords are introduced in bold. Keywords are the words a programming language is
made up of. Language definitions are in purple italics and statements are in blue and comments in
green.
Java tutoring by email or telephone is also available from $15 per hour.
Send all programming questions and the Java code you have started to students@cstutoring.com
for a quote (tutoring starts from $15)
Package (optional)
group of Classes
contain classes
Comments
describe what the Class
program does variables shared between all
methods in class
Import Statements
include packages Variables
Classes collection of
contain variables and Methods
methods
Methods
package collection of statements
class
Temporary
variables Variables
methods Programming
Statements
programming
statements
temporary
Programming Statements
variables
instructions telling the
and
computer what to do
operators
Variables
and
Operators
We will study each component individually. You do not need to understand every thing right now.
The most important thing is that you are introduced to all the terminology and the components
that make up a Java program. Analogy to a Java program is what cities and towns are made up of.
Towns are made up of neighborhoods, neighborhoods are made up of streets, streets are made up
of homes, homes are made up of people etc. A minimal Java program has only one class. A Java
program may be written as an applet or a non-applet. Applets are Java programs that run on your
web browser. Non-applet programs are known as standalone applications that run directly on your
computer. In the first few lessons, we will deal with non-applet programs. We will deal with applets
in future lessons. For a non-applet Java program a minimal class has one method called the main
method. The main method is the first method to run in a Java standalone program. When a Java
program runs it means it is executing programming statements contained in a method. You run a
Java program by executing a class file that contains a main method. I call this class the "running
class", the class that starts your Java program. The Java program that you type in is stored in a file
having the java extension. The file that has the class with the main program in it should have the
same name as the class name. Each class is usually kept in a separate file having the same name as
the class. The file name and class name is case sensitive meaning upper and lower case characters
are considered different. Before a Java program can run it must be compiled to an intermediate
execution file made up of byte codes having the extension " *.class ". If your Java program has
been written as an applet then it is this class file that runs on your internet browser. Java programs
not written as an applet are run on your computer using the Sun Microsystems JDK. The JDK
interprets the byte code. The interpreter is known as a virtual machine (VM). This means Java can
run on any computer machine that has the JDK.
The JDK is used to compile a Java source program into an execution class file so that your program
can run. The class file is run directly on your computer using the JDK. You can run applets on your
computer without a web browser by using the JDK applet viewer. When your program is running
the byte codes are interpreted by the JDK. An Integrated Development Environment (IDE) is a
complete Java development system. Most IDE'S have the JDK built into them. There are many Java
Integrated Development Environments on the market from IBM, Sun Microsystems, JCreater, and
Borland.
Java source file --> compiler --> class execution file Running
*.java JDK *.class Web Browser
MyClass.java javac MyClass.java java MyClass (applet)
The typed in Java Translates the Java Contains execution The JDK calls the main
program that contains source code into code (Byte Code) or init method from the
all the packages, execution byte code and reserved execution class file and
classes variables and memory locations the program runs
methods. for data variables
Downloading JDK
To run java programs you should download the JDK from Sun Microsystems. They named the JDK
J2SE 5.0 this is the newest version.. It is best to use the newest version. You can download the J2SE
5.0 from
http://java.sun.com/j2se/1.5.0/download.jsp
You have many choices here just select JDK 5.0 Update 6. To install down load the exe file then
run. Java will be installed and automatically set up for you.
We will write, compile and run our first java program soon. But before we do this you will need the
following background information.
Compile time is the time when the compiler is compiling your program into an execution file.
During compile time the compiler is checking your program for errors. If you have errors in your
program you have to fix them and then re-compile. During compile time the compiler will convert
your Java programming statements into execution code and reserve memory locations for your
data variables and compiled code. When the compiler reserves memory locations for your data
variables and compiled code and places them inside the class execution file. When your program
runs, the class execution file is loaded into your computer running the JDK. The JDK gives you some
memory to run your program. The size of the memory depends on the size of your class execution
file. We call this memory program or class memory and is said to be reserved memory. It is at a
fixed size and never changes. Some methods are static meaning they can be used directly from the
class execution code. When your program is running it may need additional memory for objects
called object memory. The additional memory comes from your computer memory in run time and
is allocated memory. Objects are created in computer memory during run time from the class
definitions defined in your program. What is the difference between compile time and run time ?
What is the difference between a class and an object ?
memory allocated
additional memory memory for
for objects when
requested OBJECTS
your program is
by running program (always changing)
running
Why do we need additional memory when a program is running ? A good example is a telephone
book program. When someone writes the program they do not know how many telephones entries
the book is going to have. For every person needed in the telephone book there must be enough
memory for the persons name, address and telephone number. When the program first runs it will
ask the person how many entries the telephone book will have. As soon as the person enters the
number the program must go to the computer memory and get enough memory for 100 entries.
Alternatively you could just add additional memory when you add entries to your telephone book.
You allocate memory in run time when you do not know how much memory you need. You reserve
memory in compile time when you know how much memory you need. If you knew how many
people you have in your telephone book then you could of reserve memory in compile time. You will
soon learn how to reserve memory in compile time and allocate memory in run time.
We will now discuss in depth all the components of a Java program. In Java you will see curly
brackets like these { } all the time. They are used to group statements together in a method or
methods in a class. Classes are made up of methods, methods are made up of statements, and
statements are made up of variables and operators. Operators perform operations on variables like
adding or equating.
Comments
All programs need comments to explain to the user how the program works, what the variables
represent and to define the purpose of classes and methods etc. You may place comments anywhere
in your Java program. The compiler ignores comments. They are just there for the people who read
your Java program. A comment starts with a /* and ends with a */.
A comment may also start with a "//" . The end of the comment is assumed to be the end of the
line.
// Lesson 1 Program 1
Packages
Packages are optional and used mostly in large programs involving many classes. Packages allow
you to group a collection of classes together that have a common purpose. A Package includes many
classes. A class may import classes from a package.
a package class
contains many program using a package
classes
class
class
class
Import statements are used to include Java classes contained in a package. Each package has a
class that performs Input/Output, math functions, language implementation etc. Each class has
many methods so that you can easily get your Java program up and running quickly. The purpose of
pre-defined classes is to relieve the programmer of all burdens. System source code files include
input/output classes that allows you to get data from a keyboard or file system, send information to
the computer screen, store data on an output file, make a connection to the internet etc. All of the
Java system classes you use are imported from packages. You will get used to all the packages in
Java because you are always forced to use them. The compiler needs to know what packages you
want to use when it compiles your program. You use the import statement to use packages.
. import package_name.*;
import java.io.*;
When you import a package you get to use all the classes in that package. In our example owe have
imported the java.io package and all of its classes. This package contains all classes needed for I/O.
I/O means all the input and output streams classes needed to read data from a keyboard, send
information to a file etc. We will study all the Java I/O streams in this course. The * means to
import all classes in the java.io package. If you just want one class in this package then you can
specify it by name.
import package_name.class_name;
import java.io.BufferedReader;
Most people don't know all the names they want in a package so they use * to get all classes
belonging to that package. Java automatically imports the java.lang .* package for you. This
package contains all the basic Java classes to compile and run your programs like the System and
String classes. Don't forget the semicolon at the end of the package name in the import statement.
You can also write your own Java packages, just to store you very own classes. To make your
classes belong to a package you just put the name of the package at the beginning of your Java
source code file. All classes in this file will now belong to your package.
package package_name;
package student;
You must be careful in using packages of the same name. Some Java development tools will
overwrite classes having the same name with the same named package without warning. You will
loose all your original code. Always make sure all your package names are unique.
You can also import your own packages. To use your own package you must also use the import
statement.
import student.*;
The "*" means use all classes in your package. If you just want to use a specific class of a package
then you just specify which class you want:
import student.Calculate;
CLASSES
A class defines all the variables and methods that your object will need. A class is defined by a
level of visibility, the class keyword, the class name and the required variables and methods.
The open curly bracket { means to begin something the closed curl bracket } means to end
something.
class visibility
The level of visibility states who can use this class. Visibility for classes can be public or friendly.
If the visibility is not specified the default visibility is assumed to be friendly. The visibility of our
example class is public. Visibility is like a protection mechanism where the programmer can choose
who can access the class.
friendly means only classes in the package or file can access this class
(default) (classes defined in the same file are considered to be in the same package)
There is no friendly keyword. Friendly visibility is the defaults visibility when you do not specify a
visibility.
variables
Visibility is like a
protection mechanism
allowing only certain class visibility methods
objects to enter
public or friendly
The class keyword indicates the following block of code is to be a class definition. All classes need a
name so that the programmer and compiler can identify it. The name of our example class is L1P1.
The variables and methods belonging to a class are enclosed by curly brackets { }. The variables in
a class are shared between all methods in the class. This is why classes were invented so that we
could have a collection of methods all sharing the same variables. This is a highly desirable thing to
do, it allows your programs to be highly organized and stops data corruption. Data corruption is
avoided because we now know which methods access the data. All classes start with a CAPITAL
letter where methods start with a lower case letter. You need to define a class before you can make
an object of it. A class definition is like the recipe to bake a cake. You need a recipe before you can
bake a cake. When a cake is baked it is ready to be eaten. Obviously you cannot eat a recipe! When
your program is running objects are constructed in the computer memory from your class
definitions defined in your program. A class contains variables and methods. Just like a cake
needs ingredients and the needed instructions to bake the cake. Variables are used to store and
retrieve data. The variables in a class are shared between all methods in the class and retain their
value. This is the main reason we have classes is that we want a bunch of methods to share the
same variables! A class also defines all the methods needed by the object to access the data.
Methods contain variables and programming statements. Variables in a method are used for
temporary storage where the programming statements are the instructions telling the computer
what to do. The variables in a methods do not retain their values and are said to be temporary. Only
when a methods is used will the variables contain a value. After a method is finished running the
variables values disappear. We will study methods in future lessons. In this lesson we will
concentrate on variables.
LESSON 1 PROGRAM 1
A simple Java program only needs a class and a main method. The main method is the first
method to be executed when the Java program first runs. Each class can have its own main method.
All class names in Java start with a CAPITAL letter, where method names start with a lower case
letter. The following Java program has a class called L1p1 and is public meaning everybody can use
it. Our example class just has a main method and prints out the message "Hello" to the screen.
// example class
public class L1p1 class L1P1
{
// main method
public static void main ( String[ ] args )
main method
{
System.out.println("hello");
}
The L1p1 class is known as the "running class" because it is the class we call to run the program. It
makes sense that the running class is public. Why ? Our main method just puts the word "hello" on
the screen using the following programming statement:
The System class is defined in java.lang and is automatically imported for you by the Java compiler.
We will discuss the System class in more detail shortly.
LESSON 1 EXERCISE 1
Type the above program into your Java compiler and run it. You can obtain the JDK from Sun
Microsystems at www.java.sun.com. For those people using the JDK, type the program into an
editor, the file will be called L1p1.java. From the command line of your computer type:
javac L1p1.java
java L1p1
Your program should now run. The command line is case sensitive. The file name must be identical
to the class name. Change the above program so that it print's out "Hello" and your name on the
computer screen. Call your class L1ex1 and your Java file L1ex1.java. You will now need the
following commands to compile and run your program.
javac L1ex1.java
java L1ex1
The next challenge is to compile and run java programs defined in packages. This always seems a
difficult thing to do. Just follow the following steps and then it should work.
Step 1: Type in the following program in a file called L1p2.java, but now define in a package
called student.
package student;
{
System.out.println("hello");
}
javac student\L1p2.java
step 4: run the file specifying the class path. The class path tells the Java loader where the student
package is.
Notice the '.' (dot) after -classpath this means use current directory. Notice the / after student this
means the L1p2 class file is located in the sub directory student. Notice the slash leans towards the
right, this is a Unix format for specifying subdirectories and files. You must use this format.
We want to run a class defined in a another package. This is another difficult thing to do. We write a
class called L1p3 in another file called L1p3.java. In this file we the import student package and call
the main method from the L1p2 class.
Step 1: Type in the following program in a file called L1p3.java that imports the student package
import student.*
L1p3 L1p2
// example class
public class L1p3
main main
{
// main method
public static void main ( String[ ] args )
{
L1p2.main(args);
}
step 2: compile the class in the parent directory but specify where the student package is
Since the student package is in the student subdirectory the compiler can find it so you can omit the
-classpath directive
javac L1p3.java
step 3: run the file specifying the specifying the class path. The class path tells the Java loader
where the student package is.
Since the student package is in the student subdirectory the class loader can find it so can omit the
-classpath directive
java L1p3
The L1p3 class main method calls the main method from the L1p2 class.
MAIN METHOD
When you run your program, the main method is the first method to be called from the running
class. Every class you want to run must have a main method.
{
System.out.println("hello");
}
We will now discuss and analyze the main method in detail . Every method must state who can
access it, what data type value it returns, its name what data type values it receives.
parameter(s)
method visibility
friendly can be accessed by classes in the same package or file(classes defined in the same file are
(default) considered to be in the same package) (There is no keyword called friendly)
private visibility means the method can only be accessed by the class it was defined in.
All classes are placed in program memory when a Java program is loaded. Static means the code of
the main method is directly available to be used. A static method it not associated with an object
and can be used standalone. A static variable is also not associated with any object and can also be
used standalone. For non-static variables and methods, you need an object before you can use
them. Why ? Because the methods are accessing variables of an object. If you do not have an object
then the methods cannot access the variables of the object. Right ?
object memory
additional memory for objects
program memory
Class Execution file loaded classes
Class
static variables
static methods
non static methods
The purpose of a method is to receive a value, do a calculation and return a result. A method may or
may not return a value. The return data type is the type of data the method will return. The return
data type of void is used to indicate a method does not return a value. Notice the return data type
of the main method is void. We will study data types very shortly. All method names end with
round brackets () to distinguish the method name from an variable name. Values are sent to a
method through a parameters. Parameters are declared inside the round brackets of the method
name declaration to pass values to the method. The values sent to the main method are known as
arguments.
Arg is an array of String objects that will let you send data values to the main method. You send the
data values to the main method through the parameter list by including extra information on the
command line when you run your Java program. An example is you may want to specify an
additional data file name when you want to run your Java program on the computer.
The argument "myfile.dat" will be placed into an array of Strings referred to by the parameter args.
Do not be too worried about arguments and parameters now, you just need to know that you can
send information to the main method from the command line when you run your Java program. The
String object type will be explained in this lesson. Arrays and methods will be explained in detail in
future lessons. Without the main method the program can not run. Review questions: Why must the
main method be made public ? Why is the main method static ?
LESSON 1 EXERCISE 2
Write a program that gets a name from the keyboard and greets the user of your program with the
name they entered. Call your java program and class L1Ex2. The following is an example compiling
and running the program.
javac L1Ex2
Constants
Numbers like (0-9) and letters like ('a'- 'Z') are known as constants. Constants are hard coded
values assigned to variables. There are many different types of constants.
Numbers represent numeric value whereas letters are assigned numeric values for identification
from a chart known as the ASCII table. The letter 'A' is assigned the numeric value 65. Letters
constants have single quotes 'a' around them and are known as characters. What is the difference
between '9' and 9 ? Numbers may be grouped together to make larger numbers like 1234.
Characters maybe grouped together to make messages and enclosed by double quotes: "hello".
Groups of letters are known as character strings. What is the difference between "1234" and 1234 ?
What is the difference between a character and a character string ?
backslash characters
There are special character that are called back slash codes. The backslash codes allow you to
specify new line or tab in your character strings like: "hello\n"
range of a number
All memory is made up of bits having values 0 and 1. Eight bits are make up a byte.
1 byte = 8 bits 0 1 1 0 1 0 1 0
Data types use 1 to many bytes. Data types representing small numbers use few bytes of memory
where data types representing large numbers use many bytes of memory. All numbers in Java are
signed meaning they can represent negative and positive numbers. The first bit Most Significant Bit
(MSB) in a signed number is called the sign bit. It indicates a signed number if it is positive or
negative.
sign bit
The smallest negative value to the largest positive value a number can represent is known as the
range of a number. We need to know the range of a number before we can use it or we will get
inaccurate results. We use the following formula to calculate the range of the number from the
number of bits N the number has.
(8-1) (8-1) 7 7
- 2 to 2 - 1 = - 2 to =
2 - 1 = -128 to 127
This means a data type that has 8 bits can represent values between -128 and 127. Why is the
negative number magnitude greater than the positive number magnitude ?
-1 0
The positive numbers start
at 0 and end at 127
The negative numbers start
at -1 and end at -128
Variables let you store and retrieve data in a computer memory represented by a variable name
like x. The variable name lets you identify a particular memory location. The compiler reserves the
memory address automatically for you when it complies your program. A variable is like a bank
account. You can put money in and take money out. The particular place (location) where your
money is located is identified by the bank account number. Variables have different data types, just
as a bank account would represent many different currencies. Each variable must be declared with
a data type. The data type indicates what kind of data the variable is to represent. The following
chart lists the Java data types and an example of the data it is to represent.
These are known as primitive data types and are not considered objects. .Data types are not
objects because they just store data, and cannot do any operations on the stored data. Where
objects store data and can do operations on the stored data, using its methods. We need different
data types because we want to minimize the amount of data memory space we use. The data type
also indicates the type of data the memory allocated for the variable is to represent
Float and double data types are used to represent large numbers known as floating point numbers
stored in a small memory space. Floating point numbers have a fraction (mantissa) part and an
exponent part and represented in decimal point notation 24.56f or exponent notation 3.456E04f.
You will notice that float constants have a 'f' at the end of them. In Java you need to distinguish a
float constant from a double constant. It is the exponent that allows the floating point number to
represent a large value in a small memory space. The following is a 32 bit floating point format
known as a float, where the sign, exponent and fractional parts are stored separately.
- 12 .12365 1.2365 * 10 12
The following is a 64 bit floating point format known as a double, where the sign, exponent and
fractional parts are stored separately. Double has greater precision over float because it stores
more bits in their exponent and fraction.
When you declare a variable you are telling the compiler to reserve a memory space location in the
computer memory for your data when your program runs. The variable name is used to represent
the location in the computer memory where the data value is stored. Declaring a variable is like
opening a bank account The name of the variable is like the bank account number. The bank
account number tells you where your money is in the bank. The bank account number identifies the
location where your money is in the bank. It is just like the variable in your program identifying the
locations in the computer memory where your data value is stored. To declare a variable you specify
the data or object type and the variable name. A data type is like the currency of the money stored
in the bank account. When you declare a variable in a method the data value is uninitialized U
meaning a known value has not been placed at that memory location yet. When you declare a
variable in a class definition it gets a default value of 0. You declare a variable by specifying the
data type and an identification name. Variable names should be short and meaningful. Every
variable must be declared with a data type and a name. The data type tells your program what kind
of data the computer memory is suppose to represent. The variable name tells your program the
location in the computer memory where your data value is stored. Data type indicated what kind of
data the variable represents.
You may declare more than one variable at a time if it is the same data type, by separating the
variable names by commas.
You may assign values to variables when they are declared. This is called initializing. It is like
opening a bank account with an initial deposit.
A string variable s1 refers to a String object rather than contains the character string itself. The
string object contains the character string "hello". Refers means s1 is not the String object itself but
contains the location where the String object is located in the computer memory.
You can declare many variables and initialize them all at once if they are of the same data type, by
separating the variable names and initializations by commas.
data_type variable_name_and_initialization_list; m 1
p 3
String Objects
"message"
It is easy to use character strings in Java because Java has the built in String class located in
java.lang. Character strings in Java are represented by the String class. A String is considered an
object in Java and is not a primitive data type. String is known as a object type rather than a
data type. The String class lets you do operations on strings. These operations may be assigning
character strings or joining two character strings together. A character string is made up of
characters. A character is a single letter in the string. A character is denoted by single quotes. like
the letter 'a'. There is a big difference between 'a' and "a". 'a' is a character where as "a" is a
character string with only 1 character.
The String variable s does not contain the character string "hello" but contains the location where
the string object is.
s
String s = "hello";
Assignment statements using the "=" assignment operator allow you to assign values to existing
declared variables. The expression on the right hand side is assigned to the variable on the left hand
side of the assignment "=" operator. The variable gets the new value and the old value is over
written. Values are expressions. An expression may be a constant, numeric, String data values or
other variable with an assigned value. Once a variable is declared it does not need to be re-declared
to assign a new value to it. Its like you do not need to re-open a bank account when you want to
make deposits and withdraws. Before you can assign a value to a variable, the variable must be
previously declared. When you assign a variable to another variable the value of the variable (not
the variable name) on the right hand side is assigned to the variable on the left hand side.
Assignment statements have the form:
variable_name = expression;
s1 = "today"; // the String object s gets the character string "hello" s1 today
The System.out.println(); statement is used to print values and messages to the computer screen.
The System class is defined in java.lang and is automatically imported for you when you compile
your program. The System class has a variable called out that is a reference to a PrintStream class
object defined in java.io. (we will study reference's to objects shortly) println() is a method of the
PrintStream class. The println( ) method causes your printed message to end with a new line after
the message is printed not before. If you do not want a new line after your message use the print()
method instead.
System out.print("hello"); // print a message to the screen, with out a new line
System.out.println("hello"); // print a message to the screen
System.out.println("hello"); // print a message to the screen hellohello
hello
To print out a variable value you just include the variable name.
To print a message and a variable value to the screen you list the message in double quotes use the
"+" catenation operator and list the variable name. Messages are surrounded with double quotes
and variables are not. The "+" catenation operator is used to join messages and variables together.
System.out.println("the value of x is: " + x); // print a message and value to screen
LESSON 1 EXERCISE 3
Write a simple Java program that has only one class and a main method. In the main method
declare five variables of different data types. and initialize these variables with values. Use the
System.out println() statement to print the values of the variables on the screen. Next assign
values to your variables and print out the new values. Call your class L1ex2 and your Java file
L1ex3.java.
IMPORTANT
You should use all the material in all the lessons to do the questions and exercises. If you do not
know how to do something or have to use additional books or references to do the questions or
exercises, please let us know immediately. We want to have all the required information in our
lessons. By letting us know we can add the required information to the lessons. The lessons are
updated on a daily bases. We call our lessons the "living lessons". Please help us keep our lessons
alive.
E-Mail all typos, unclear test, and additional information required to:
courses@cstutoring.com
students@cstutoring.com
www.cscourses.com/java.htm
This lesson is copyright (C) 1998-2006 by The Computer Science Tutoring Center "cstutoring"
This document is not to be copied or reproduced in any form. For use of student only
A classes defines all the variables and methods a object would need. When you make a object from
a class definition, the object is then known as an instance of a class. An object is allocated
memory for the variables defined in a class. A class may have many instances all made from the
same class definition. Just as there can be many cakes made from the same recipe. When many
cake's get baked they also get names: cake1, cake2 cake3 etc. The item you are making is a cake,
but each individual cake made is known separately. The class is the basic definition that instances
are created from. Each instance or object will have its own distinguishable properties. Just like each
cake can have its own distinguishable properties. Chocolate cake, vanilla cake etc. This is the
highlight of Object Oriented Programming. where a class provides a common definition that objects
are created from. When you define a class you must list all the data variables and methods the class
needs. When you create an instance of a class the object will get distinguishable properties or
attributes when the variables of the object are initialized. How are the properties of an object
initialized? The variables may be initialized in the class definition or by using a constructor. A
constructor is a special method to initialize the variables of an object. A constructor has the same
name as the class. A constructor is like the baker who bakes the cake. The baker uses the recipe
and ingredients to bake the cake. The recipe is the class, the ingredients are the data and the baked
cake is the object. Values are sent to the constructor who then initializes the variables of the object
with these values. When an object is made, memory for the variables of the object is allocated in the
computer memory. An example of a class is a Person class. A Person may be defined with age,
name, height and weight. The Person class may be defined with methods to initialize age, name,
height and weight and to retrieve these values. Every time you create an object from the Person
class definition, you will get a separate Person object. Each Person object would have a different
name, age, height and weight. Each Person object is distinguishable from other Person objects
because each Person object has unique properties. How does an object get its own distinguishable
properties? When the variables of the object are initialized with different values by calling the
constructor or initializing the variables defined in class with values when they are declared.
defining a class
We will define a Person class. An attribute of a person can be their name. Our class will have the
name of the person and a constructor to initialize the person's name when the Person object is
created..
// person class
public class Person this Person Class
{
private String name; // name of person Variables
// constructor to initialize variable name
public Person(String name)
{ Constructor
this.name = name; // initialize name
}
}
A reference to the executing object or the class being defined is automatically supplied by the
compiler and is called this.
constructors
Constructors are special methods that are used to initialize the variables of a created object.
Constructors have the same name as the class. Values are passed to the constructor through
parameters. Parameters are used to receive value. Parameters are enclosed by round brackets and
defined by a parameter type and identified by a parameter identifier.
The parameter type is String and the parameter identifier is name. The value represented by the
parameter identifier is assigned to a specified variable defined in the class. In most situations, the
parameter identifier and variable defined in the class have the same spelling. To distinguish the
difference between a parameter identifier and the variable defined in the class, a reference to the
class you are defining is used. This reference is called this and refers to the class you are presently
defining or the object that is being executed when your program is running. The parameter identifier
receives a person's name. The parameter identifier representing a persons name is assigned to the
variable name defined in the Person class. Constructors that receive values through a parameter list
to initialize the variables declared in the class are called initializing constructors.
{
the this reference refers to the class you are
this.name = name;
defining or the presently executing object.
}
default constructor
A default constructor initializes the variables defined in a class with default values.
// default constructor
public Person() A default constructor initializes the variables
defined in a class with default values.
{
name = "Ed";
}
A class does not always need a constructor. The variables of a class can be initialized when they are
declared in the class definition. This is a good feature of Java. We can make a Person class that does
not have a constructor by pre-initializing the variables defined in the class with values. The compiler
will initialize the variables declared in the class definition when the object is created.
// person class
public class Person this Person Class
{
String name = "Ed"; // name of person
} Variables
When we pre-initialize the name of the person in the class definition, then we will have many Person
objects with the same name. This is totally undesirable. When do we need constructors ? The rule is,
we need constructors when we want to give our object different data values when it is constructed.
When a constructor is not defined the Java compiler will supply a default constructor automatically.
Unfortunately the Java compiler will not supply a default constructor if you have defined other
constructors.
1. in a constructor
An object reference has to be declared before an object can be made. An object reference is a
variable that stores the location of an object. When a object is created, memory is allocated for it.
The object reference stores the starting location where the object is located in computer memory.
Declaring an object reference is just like declaring an integer variable.
data_type variable_name
Instead of a data type we now have an object type, instead of a variable name we have an
object name. The object type is the class name. When you define a class you have automatically
created an object type. The object name is any name you want to identify the object. We declare a
reference to a Person object called p.
object_type object_name;
The object name is known as an object reference because it is a reference to an object, it is not the
object itself. The object reference will store the location where the object is created in memory.
When you declare an object reference in a method it is unitialized. When you declare an object
reference in a class definition it gets a default value of null. null refers to no known object and does
not refer to any object. An object must be created and assigned to the object reference.
After you declare an object reference, you have to create an object. This is like baking a cake. A
cake needs to be made before it can be eaten. A object needs to be created before it can be used.
When an object is created it is known as an instance of a class. An instance of a class is created in
run time (when your is running). Creating an object is much like assigning a value to a variable.
int x = 5;
x 5
Except the value is the location of an object.
p Tom
When a object is created memory must be allocated for it. Memory for objects are created in run
time using the new operator. The new operator allocates memory for the Person object, and the
object's starting memory location is assigned to the object reference. The object reference contains
the location of where the object was created in memory. The variables in the objects are initialized
by calling the class constructor. When the constructor is called the constructor will initialize the
variables belonging to the object declared in the class.
(2) create an instance of the class, p = new Person("Tom"); // assign Person object to p
assign the created Person objects
location to the object reference p
When we create an object the new operator allocates memory for the object and the constructor
initializes the variable defined in the class for the object. We have now created a Person object
initialized with the name "Tom". The object reference variable p has the location of the Person
object. The above two steps may be combined into 1 step.
If we did not include a Constructor in our class definition then we can still create an object by calling
the default constructor. You call the default constructor with no arguments.
p2 Ed
Person p2 = new Person();
In this situation, the object variables will have the values that they were defined with which is "Ed".
In programming you must make a connection between what constructors are called and which
variables were initialized. Think that calling a constructor is creating different kinds of cake.
Each cake object is made from the same recipe, the Cake class. Each cake object gets initialized with
a different flavor when it is made. Summarizing we create the object from the class definition, we
allocate memory for the object using the new operator, we call the constructor to initialize the
variables defined for the object by the class.
main method
The main method is the first method to run when you run your program. The main method is static
meaning the code can be directly accessed from the loaded class. The main method is usually used
to declare objects, instances of the class that the main method belongs to. This is a unique feature
of Java where each class can have its own main method. By each class having its own main method
each class can be tested individually before they are integrated into a complete program.
// main method
public static void main ( Strings[ ] args )
{
Person p1 = new Person("Tom"); // create instance of the class Person
Person p2 = new Person(); // create instance of the class Person
}
The main method is static and can be accessed directly from the Person class. When objects are
created from a class definition the static variables and methods are not created again inside the
object. In an object, memory is only allocated for the non-static variables declared in a class. The
object may use the static variables of the class, but does not contain them. Both static and non
static methods can access an object variables. Variables in an object are shared between all
methods defined in a class. The object reference p was declared in main and refers to a Person
object. You must understand the difference between Person class and Person objects. The static
variables and methods belong to the Person class. There is only one person class but there can be
many person objects. The Person class is in program memory where the Person object is in object
memory. There may be many Person objects but only one Person class. Note: each Person object
refers to a String object representing the Person's name.
Person class
Person object's String object's
(declared in Person class)
main method (static)
toString method
Once we get our object created we want to do something with it. The only thing we can do with our
Person object is to print the name of the Person on the computer screen. Java lets you return a
string representation of an object by calling the toString method. The toString method just
makes and returns a String object, but does not print out to the screen. You need to call the
toString method with the System.out.println() method to print to the computer screen.
{
return "my name is: " + name; // make a String and returns it
}
The toString method is also conveniently called by using the object name. The Java compiler will
automatically call the toString method for this object. The System.out.println() method is called
to print out the String object returned by the toString method. When you want to use a method
you call it by its name.
or if you like typing so much then you can use the object name, the dot operator and the toString
method name.
The above two methods are equivalent. Using the object name is more professional.
If the object does not have a toString() method then the location of the object is printed out with
the class name a @ symbol and some stupid number in hexadecimal identifying the object:
MyClass@7da8
Person class
Here is our complete Person class. The main method is used to create Person objects and calls the
toString() method from each object. We have two constructors. Having two methods with the same
name is possible in Java. as long as the parameter types are different. This technique is called
method overloading which means same method name but different parameter types. The compiler
knows which constructor to call by matching the number of arguments when the constructor is
called.
// person class
public class Person
{ a class may have more than 1
private String name; // name of person constructor this is called overloading
// default constructor
public Person()
{
this.name="Ed"; // initialize variable name to "Ed"
}
// initializing constructor
public Person(String name)
{
this.name = name; // assign user value to variable name
}
{ Ed
p1
Person p1 = new Person();
System.out.println(p1);
Person p2 = new Person("Tom");
System.out.println(p2); p2 Tom
}
In the main method we make two objects. One made using a default constructor, the other using an
initializing constructor. When you have other constructors defined you must include a default
constructor if you create objects that need default constructors. The Java compiler will not
automatically create default constructors for you, if you already created other constructors. You will
get an error message if you call a default constructor and you have not defined a default constructor
with your other constructors.
LESSON 2 EXERCISE 1
Type in the Person class and run it on your computer. Instantiate objects with your own name. Call
your project L2ex1 call your class Person and your Java file Person.java. Remove the default
constructor and instead initialize the name variable with a value.
LESSON 2 EXERCISE 2
Add more attributes to the Person class like height, age and weight. Update your constructor and
toString method.
LESSON 2 QUESTION 1
class components
A class list all the variables and methods for a object. A class is defined as follows:
final variables // variables once initialized the value cannot change (read only)
main method // creates i/o streams, creates classes and call's class methods
A class may have many different kinds of variables. Variables that are read only, that are shared
between all instances of a class just known to one instance of a class. Variables may be initialized in
the class definition or by using a constructor. When all the variables are initialized in the class
definition a constructor is not needed. In this case the Java compiler will supply a default constructor
automatically. Methods contain programming statements and temporary variables. The variables in
a method do not retain their values after the method has finished running. The variables defined in
the class retain their values. The main method is used to start your program and create an object
from the class it was defined in. You will learn in detail all the components of a class in future
lessons. In this lesson, we will concentrate more on variables declared inside a class.
variable visibility
In Java you can declare and initialize variables as you need them. You can declare variables in the
class definition, in individual methods or globally in your program. Variables declared in a class have
level of visibility that indicate if the variables are to be known to other classes or just to be known
to the class they were declared in.
private int x;
Variables declared in a class definition may have visibility public, friendly or private. If there is no
visibility specified the default visibility is friendly. There is no keyword friendly.
public class
access public variables
some other class public variable some other class
same package different
package
friendly variable cannot access
private variables
private variable
Variables in a class should always be declared as private. By having all variables in a class private
forces all classes to exchange data through methods. By classes exchanging data through methods
enables all classes to operate independently. The methods act as a protection ring to protect the
data. Objects exchange data through methods (M)
CLASS B
CLASS A M
M M M
Exchange data
through
private methods private
variables M variables M
M M
M M M M
declaring variables
Variables declared in a method are not known to other methods or classes. They are said to be local
to that method and will not be recognized anywhere else. Variables declared in a method may not be
declared as private or public. Variables declared in a class are shared by all methods of that class.
Final Variables
The final keyword let you define a variable as "read only". This means you cannot change the
value of the variable once it is initialized. A final variable must be initialized with a constant when it
is declared.
final int MaxSize = 10; // final variable initialized to constant value 10 cannot be changed
Using final variables is a must. There should be no hard coded numeric values in your program. The
purpose is this. If you change MaxSize to be 12 then you do not need to change all 10's to 12 in
your program. Without using a final variable you may inadvertently change some 10's to 12's that
don't need to be changed and then your program may not operate as expected. Final variables are
usually placed inside the class definition before all methods are defined. Final variables may also be
declared in methods as well as in class definitions. Final variables declared in class definitions may
be private or public.
Static variables are needed only when you want one variable always the same variable to be
accesed by the class. Only one memory location is allocated to a static variable. Static variables are
also known as class variables. In contrast non-static variables are known as instance variables,
because a new variable is made every time an instance of the class is made. Static variables should
be initialized to a default value when they are declared. Static variables can only be declared in the
class definition. Static variables cannot be declared in a method. Static variables are placed in
program memory where the class was loaded and can be directly used. Note: static methods can
only access static variables.
program memory
Object
Instance Variable
class loaded into, memory:
Object
static variable Instance Variable
Static variables can be accssed by all objects. When would we use static variables ? We can use the
Person class as an example. Would we want the age of a person to be shared between all instances
of Person ? Probably not. As soon as we change the value age in one object it will reflect the same
value for all instances of the Person objects. Are all people the same age? Probably not. We would
like age to be different for each person object. What would be a good static variable for a person
class ? The number of people objects created. We need to keep track of how many people objects
were created. This can be done by using a static variable.
There will be only 1 static variable located in program memory and shared between all objects.
Every time an instance of the class is made the static variable can be incremented. When a static
variable is declared in the class definition it should be initialized to a default value like 0. Here is
the Person class with a static variable. When accessing a static variable inside the class definition
you use the static variable name.
When accessing a static variable outside the class definition, you must use the class name not the
instance name or object reference name.
// person class
public class Person
{
private static int num = 0; // declare static variable num
private String name = "Ed"; // name of person
// default constructor
public Person()
{
num = num + 1;
}
// initializing constructor
public Person(String name) class Person
{ Person
(static)
this.name = name; Objects
num = num + 1;
}
main:
// main method
public static void main ( String[ ] args )
p1 Ed
{
Person p1 = new Person(); num
System.out.println(p1);
Person p2 = new Person("Tom"); p2
System.out.println(p2); Tom
}
{
return "my name is: " + name + " there are " + num + " persons");
}
} my name is: Ed there are 1 persons
LESSON 2 EXERCISE 3
Type in the above Person class with the static variable and run it on your computer. Remove the
static modifier on variable num and re-run the program What did you noticed ? Call your project
L2ex2 call your class Person and your Java file Person.java.
Reference Variables
Reference variables are used to refer to an object. They are not the objects themselves, but
reference variables contain the location of where the object is stored in the computer memory. The
only object we have been using so far is instances of the String class and our own classes like the
Person class. Objects are stored in memory. References variables refer to the location of an object
created in computer memory. As mentioned before, declaring a reference variable is no different
then declaring a variable.
The only difference is, instead of a primitive data type we use the class definition name. The class
definition name is also known as an object type. When a reference variable is declared in a method
it is unitialized and does not refer to any object. When a reference variable is declared in a class
definition its gets default value of null meaning refers to no known object.
object_type object_name;
If you declare a reference variable in a method and you do not assign an object to it, then you
should assign null to it. null is used to represent no known object.
String s4 = "" ; // reference variable refers to string object that is empty s4 ""
s3 does not refer to any object where s4 refers to a string object that is empty.
s3 null s4 ""
The String object is created in compile time and placed in the class execution file. The "="
assignment operator is used to assign the String object to the object reference variable s. The string
object is automatically constructed for you because the compiler calls the String class constructor.
When the program is loaded and running the reference variable s refers to the location of the string
object placed in program memory.
Existing objects may be assigned to other object reference variables. Let's make another string
object called s6.
The location of the object refereed to by s6 is assigned to s5. Now both s5 and s6 refer to the
"goodbye" string object. Each stores the location to the String object "goodbye"
s5 = s6; s5
s6
Now s5 and s6 refer to the String object created by s6. What happen to the object referred to by s5
? In Java you do not need to worry about deallocating memory, Java does this for you automatically,
any memory not being used is collected for re-use. It's called garbage collection. There are 2 run
time methods System.gc() and Runtime.gc();
LESSON 2 EXERCISE 4
Write a small program by answering the following questions that just includes a class and a main
function If you are using a project call your project and class L2Ex3. You may want to print your
values on your computer screen by using the System.out class print method as follows:
A program example consisting of a class called L2P2 with variables and a main method
demonstrating using different types of variables is as follows. The main method is used to create an
instance of this class.
Once an instance of a class is created we can access the member variables of the created object by
using the object name the dot operator and the variable we want to access.
The ". " dot operator states the variable name belongs to the object referred by test.
// public class
public class L2p1
{
public final int Max = 5; // final variable
public String name; // public variable reference
private int count; // private variable
// main method
public static void main ( Strings[ ] args )
{
L2p1 test = new L2p1(); // instantiate class L1p2
test.name = "Hello"; // set public variable to "hello"
int x = test.Max; // variables belonging only to a method
test.count = L2P1.Num; // assign static variable to private variable
System.out.println("test.name " + x + test.count); // print hello
}
Program Output:
class object memory
memory
object L2p1
class L2p1 Hello 5 0
Num: 0
Main Max: 5
name: Hello
test count: 0
x: 5
MEMORY MODEL
A memory model shows where all the programming components are placed in the computer
memory. The memory model will let you understand the difference between static variables and
methods and objects. The class file is loaded into the program memory when you run your program.
In the class file program memory is reserved for static variables and methods. Memory is allocated
in the computer memory for objects created from the class definitions. Objects are only known by an
location represented by a @xxxx The methods belonging to a class are also stored in program
memory or read off the class file. The methods of a class do not get stored with the object in
Computer data memory. Non-static methods of a class can only be accessed by objects because
variables inside a non-static class will access variables in an object.
LESSON 2 EXERCISE 5
Make a memory model for your Person class, instantiate at least 2 Person objects in your main
method.
IMPORTANT
You should use all the material in all the lessons to do the questions exercises. If you do not know
how to do something or have to use additional books or references to do the questions or exercises
please let us know immediately. We want to have all the required information in our lessons. By
letting us know we can add the required information to the lessons. The lessons are updated on a
daily bases. We call our lessons the "living lessons". Please let us keep our lessons alive.
E-Mail all typos, unclear test, and additional information required to:
courses@cstutoring.com
students@cstutoring.com
www.cscourses.com/java.htm
This lesson is copyright (C) 1998-2006 by The Computer Science Tutoring Center "cstutoring"
This document is not to be copied or reproduced in any form. For use of student only.
File: JavaL3.doc
OPERATORS
Operators are symbols that are used to do operations on variables. The operations may be adding or
comparing the values of variables. etc.
x + 5
An operand may be a variable or a constant. Operands and operators are called expressions that
represent a value and used in assignment statements. An assignment statement is used to assign
values to an variable. The expression on the right hand side of the assignment statement is
evaluated and the value assign to the variable on the left hand side of the assignment statement.
expression 11 12 1 (13)
arithmetic operators 6
LESSON 3 EXERCISE 1
Write a java program that uses all the arithmetic operators and prints the results to the screen. Call
your java program and class L3Ex1.
The increment and decrement operators are used to add 1 or subtract 1 from a variable. This
saves you some time typing. They work in a prefix mode and in a postfix mode. Pre meaning
increment the variable before assignment and post means increment the variable after
assignment. I t is a two step operation. The variable on the right is assigned a value from the
variable on the left and the variable on the left is incremented or decremented by 1.Or the variable
on the left is incremented or decremented by 1and then assigned to the variable on the right.
Lesson 3 Question 1
Fill in the values for x and y. Assume all statements continuous. Each answer depends on the
previous answer.
x y
y = 5; -- 5
x = y++;
x = y--;
x = ++y
x = --y
LESSON 3 EXERCISE 2
Write a java program to verify your answer above and print out the results to the screen. Call your
java program and class L3Ex2.
RELATIONAL OPERATORS
Relational operators test the values of variables if they are greater, greater or equal , less or
less or equal by comparing their values to other values. Testing is done by a test condition
having the form:
(condition)
(x > 5)
The test condition is evaluated as true or false. Evaluate the following for x = 5; y = 5;
You can print to the screen the value of a test condition. It will say true or false.
false
System.out.println((x < 5));
LESSON 3 EXERCISE 3
Write a java program that uses all the relational operators and prints the results to the screen. Call
your java program and class L3Ex3.
EQUALITY OPERATORS
Equality operators are used to test if a variable is equal to another variable or constant, and to
test if a variable is an instance of a class. Evaluate the following for x = 5; String s = "hello";
Notice that the equality operator "= =" is different from the assignment operator "=". Java will
give you an error when you try to use the assignment operator as a test condition. When you use
the compare operator "==" to test if two object references are equal you are testing if two object
reference refer to the sane location. You are not testing if both objects contain the same data
contents. Each object will have methods to test its data contents. Can you say s =="hello" ? You
can but you are not testing if s is equivalent to "hello" you are testing if s and "hello" refer to the
same String object. The String class has additional methods to test if the string data values are
equivalent. You will learn these very shortly.
LESSON 3 EXERCISE 4
Write a java program that uses all the equality operators and prints the results to the screen. Call
your java program and class L3ex4.
LOGICAL OPERATORS
Logical operators are used to test if two conditions are both true using the AND (&&) logical
operator or if either test condition is true using the OR ( | | ) logical operator. Parenthesis are used
around the test conditions to force the condition to be evaluated first.
((x == 5) || (x != y))
Round brackets are used around the test conditions to force the test condition is to be evaluated first
Evaluate the following for x = 5; and y = 5; Hint: evaluate each condition as true or false first.
&& logical AND both ( (x != 5) && (x == y) ) test if x is not equal to 5 and x is equal to y false
The OR ( | | ) and AND (&&) logical operators are said to be short circuited or lazy evaluation As
soon as if finds one condition not true or false it will not test the other condition.
LESSON 3 EXERCISE 4
Write a java program that uses all the logical operators and prints the results to the screen. Call
your java program and class L3Ex4.
A memory cell in a computer is called a bit and can have two possible states on or off and is
represented as a 1 or a 0. Numbers containing 0's and 1's are known as binary numbers having a
base of 2. Since 0's and 1's are very difficult to work with, four bits are grouped together to
represent the decimal numbers 0 to 15. The decimal numbers 0 to 15 can be represented in base 16
as 0 to 9 and A to F. Base 16 is also known as hexadecimal numbers. Letters are used because we
want one character to represent a number. Base 16 is used because it is more convenient to work
with then binary numbers
The following chart shows the numbers 0 to 15 in bases binary (2), hexadecimal(16) and
decimal(10).
0000 0 0 1000 8 8
0001 1 1 1001 9 9
0010 2 2 1010 A 10
0011 3 3 1011 B 11
0100 4 4 1100 C 12
0101 5 5 1101 D 13
0110 6 6 1110 E 14
0111 7 7 1111 F 15
It's easy to convert a binary number top a hexadecimal number. All you have to do is group four
binary bits together in groups.
1 1 1 0 0 1 0 1 1 0 1 1 1 0 0 1
E 5 B 9
If you want to convert hexadecimal numbers to binary just use the chart ! Look up the hexadecimal
number and write down the binary equivalent.
E 5 B 9
1 1 1 0 0 1 0 1 1 0 1 1 1 0 0 1
To convert a binary number to a decimal number you just multiply each bit by its weight position
and add them up. A weight is the power of 2 of the bit position For example bit position 3 will have
weight 2 exponent 3 = 8. Bit positions start from the right most significant bit and start at bit
position 0. 2 to the power of 0 is 1 (2 exponent 0) =1. Example convert the binary number 1011 to
decimal 11:
bit position 3 2 1 0
weight 8 4 2 1
binary number 1 0 1 1
add up result 8 +0 +2 +1 = 11
To convert a decimal number to its binary equivalent you continually divide all the quotients by 2
and keep track of the value of each remainder. Each remainder must be multiplied by the base (2).
To get the correct binary number you then take the remainders from the top of the chart.. Example
convert decimal 11 to binary 1011. Start at the bottom of the chart. We divide 11 by 2. The quotient
is 5 and the remainder is .5. Multiply each remainder by 2. Continue with the other quotients. Take
the answer from the start of the chart to the bottom: 1011.
0 .5 * 2 = 1
2 1 .0 * 2 = 0 1 0 1 1
2 2 .5 * 2 = 1
2 5 .5 * 2 = 1
2 11
A truth table lists all the possible combinations of the input to calculate the outputs. You know how
to add numbers so we will make a truth table for adding binary numbers.
0 0 1 1
+ 0 + 1 + 0 + 1
0 1 1 10 (2 in Binary)
The bit wise operators work on individual bits. The bit wise operator truth tables should now be
easier to understand. Instead of ADDing you will be ANDing, ORing and XORing. The bitwise
operators operate on individual bits of variables. You need to understand binary and hexadecimal
numbers to use the bit wise operators.
& bitwise AND clear bits to zero 0&0=0 0&1=0 1&0=0 1&1=1
Did you notice everything you AND (&) a bit with 0 the result is zero. Every time you OR ( | )a bit
with 1 the result is 1 . When you XOR ( ^ ) two bits that are the same together the result is zero.
When you XOR ( ^ ) two bits that are the same the result is 0., different the result is 1. When you
complement 0's become 1 and 1's become 0's.
LESSON 3 QUESTION 2
Use the above chart and calculate the results for the following operation and fill in the boxes.
Binary:
Decimal:
2. How would you use the AND & bitwise operator to test if a number was even or odd ?
3. What do you think the XOR ^ bit wise operator is used for ?
4. What would we use the OR | operator for ?
5. What other uses would the bitwise AND & operator be used for ?
Example using bit wise & operator to test if a number is even or odd :
If the number is odd the result is (0x01) a true condition. If the number is even the result of the test
condition is (0x00) a false condition. Why ? A true is considered a non zero value where a false is
considered a zero value.
Example using bit wise & operator to test if a number is even or odd:
If the number is odd the result of the test condition is = 0x01 a true condition. Why? If the number
is even the result of the test condition is = 0x00 a false condition. Why ?
Another method to test if a number is even or odd is to take the mod 2 of the number.
Take any char like 'A' xor it with another character like 's' called a key and you get a secret
character like '%'. (encryption) Take your secret character '%' xor it with your key character 's'
and you get your original character back 'A'. (decryption)
LESSON 3 EXERCISE 5
Write a java program that uses all the bit-wise operators and prints the results to the screen. Also
encrypt and decrypt characters. Call your java program and class L3Ex5.
Shift operators let you multiply or divide by powers of 2. There are three types of shift operators:
(3) unsigned right shift >>> x = x >>> N; // shift x right by N bits divide by 2n
To multiply by a power of 2 you shift left N bits. To divide by a power of 2 you shift right N bits.
To shift bits left you put an extra 0 on the right hand side of your binary number. Red represents
the left most bit that will be lost when we shift left. Green represents the shifted bits and violet
represents the added right bit after we shift left. There is no difference shifting signed or unsigned
numbers left. Example shift 0101 left by 1 bit.
Here is a small program that assigns 5 to x and shifts x left by 1 bit. Don't get the left shift operator
<< mixed up with the output stream operator <<. They are both the same symbol!
Try shifting 0011 left by 1 bit. What happens when you shift a signed negative number left ?
To divide by a power of 2 you shift right N bits. To shift bits right you put an extra bit on the left
hand side of your binary number and remove the right most bit. The extra bit on the left is a 0 if the
left most bit is 0 and is 1 if the left most bit is 1. This is called signed extension. This means if you
divide a negative number by 2 then the answer must still be negative.
positive number
signed shift right
The bit on the left is known as the
before after sign bit.
negative number
signed shift right The bit on the left is known as the
sign bit.
before after
When we shift right the right most bit is lost. We cannot represent fractions with integers data types.
When we shift right it appears the values are truncated to a smaller value 5/2 = 2.5 = 2. (2 is
smaller than 3) -5/2 = -3. (-3 is smaller than -2).
msb = 0 msb = 1
unsigned shift right unsigned shift right
Here's a program that initializes an unsigned int to - 5 which is really 65531. When we shift right a 0
is attached to the left most side of x and now the number is 32765.
class UnSignedShiftRight
{
public static void main(String[] args)
{ 65531 (-5)
/* shift unsigned number right */ 32765
int x = -5;
System.out.println(x);
x = x >>> 1;
System.out.println(x);
}
}
When the MSB or most left bit is 1 then a signed number is considered negative. The following chart
lists all the numbers for a signed number using 4 bit resolution. When N is 4 and we use our signed
number range formula
-8 -7 -6 -5 -4 -3 -2 -1 0 1 2 3 4 5 6 7
1000 1001 1010 1011 1100 1101 1110 1111 0000 0001 0010 0011 0100 0101 0110 0111
With signed negative numbers the MSB is always 1. The number of 1 depends on the resolution. The
following table lists -5 for N of 8, 16.
N = 16 1111111111111011 short -5
How do we calculate binary representation for binary numbers ? To find out what binary number is
represented by a negative number we use two's complement on a positive binary number to find its
negative binary representation. Do you know what signed extension means ? To convert from a
negative binary number to a positive binary number and vice versa You use 1's complement to
complement each bit and then add 1 (2's complement) . We are assuming a 4 bit binary number
resolution where the MSB of 1 represents a negative number and a MSB of 0 represents a positive
number.
1's complement 1010 (-6) 0100 (4) 1100 (-4) 0010 (2)
LESSON 3 QUESTION 3
Binary:
Decimal:
2. When we shift right where does the most right binary bit go ?
3 Why are the left shift and right shift bitwise operators so important ?
LESSON 3 EXERCISE 6
Write a class called L3Ex6 that just has a main method. In your main method initialize a variable to
a positive number. Shift the positive number left by 2 and print out the results. Next initialize the
variable to a negative number. Shift the negative number right by 2 and print out the results. Shift
the negative number right by 2 using the unsigned shift operator and print out the results. Test if
the shifted numbers are even or odd and print out the result of the test.
shortcut operators
Short cut operators allow you to save typing in adding numbers etc.
+= x += 5; x = x + 5; *= x *= 5; x = x * 5; %= x % = 5; x = x % 5;
-= x -= 5; x = x - 5; /= x /= 5; x = x / 5; ^= x ^= 5; x = x ^ 5;
Precedence
Precedence tells the compiler which operations are to be performed first. Round brackets ( ) are
used to force which expressions to be evaluated first. If round brackets are not used then the
compiler must decide for you. The compiler makes it decision by using a precedence table that
indicates which operators are to be performed first. Multiplication and division have higher
precedence than addition and subtraction. Associatively is a term that states in which order the
operations are to be evaluated, either from left to right or from right to left. Operators in a
expression having the same level precedence are evaluated to the associativity direction.
precedence table:
LESSON 3 EXERCISE 7
Design your own mathematical equation using all the arithmetic operators. Assign values to all of
your variables, don't use any round brackets. Print out the results. Put round brackets in your
mathematical equation and print out the results. Compare both answers by printing them out.
Write some equations using the short cut operators. Call your class L3ex7 and your Java file
L3ex7.java.
if statement
The if statement is used with conditions to make a decision in a program flow. When the if
expression is true then the statements belonging to the if statement is executed. When the if
expression is false then program flow is directed to the next program statement. If an if statement
has more than one statement them the statements must be enclosed by curly brackets.
if - else statement
An if statement may have an optional else statement. The else statement executes the alternative
false condition. Curly brackets are also needed if more than one statement belongs to the else
statements.
if(expression) if (x==0)
T F
{
if(x==0)
true statements y = x;
x=x+y;
} y = x;
x = 1;
else x = x + y;
else
false statements
x=1;
Conditional Operator ?:
The conditional operator ?: evaluates an condition. If the condition is true it returns the value of
the true expression. If the condition is false it returns the value of the false expression. It's like an
if-else statement but in a condensed form
if(x == 5)
y = x + 1;
? if
else
y = x - 1; : else
LESSON 3 EXERCISE 8
Write a class called L3Ex8 that just has a main method. In your main method initialize 3 integer
variables with different values. Print out the names of the variables and values to the screen. If
variable 1 is larger than variable 2 then print out " variable 1 is larger than variable 2 " else print
out " variable 1 is smaller than variable 2 . Repeat for variables 2 and 3.
An assignment conversion occurs when you assign a value to a variable of a different data type then
the original. For example you can assign an int to a double.
int x = 5;
d = x;
Now d has the value 5.0. This is known as a widening conversion because you a assigning a data
type that represents a value of smaller numbers to a data type than can handle larger numbers.
int
char
If you try to assign a double to an int, this is impossible to do so the compiler generators an error.
This is known as a narrowing conversion because you a assigning a data type that represents a
value of larger numbers to a data type than can handle smaller numbers
double
char
short byte
int
variable of new data type = (new data type)expression of old data type.
int x = (int) d;
In this case the value of d representing a double value is forced to an int data value when assigned
to x. The variable d keeps its original value. With type casting there is a loss of data precision the
loss of the fraction 0.5.
double d = 10.5;
int x = (int) d.
Now x has the value 10, the fraction is lossed but d retains of value 10.5 variable d remains
unchanged.
arithmetic promotion
If arithmetic expressions contains different data types all bytes, shots and char are converted to int.
unless there is a converted to a double float or long if present this is known as Arithmetic promotion
. Arithmetic promotion can give you many side effects when shifting unsigned right a signed byte.
The answer is -4 rather than 12 that was expected. This is because the byte is converted to a int
then shifted right then the last 8 bits are returned as a byte and the result of -4 is due to signed
extension when converted from an int.
-64 2684435452 -4
s * i >= f / d
int double
int double
double
boolean
LESSON 3 EXERCISE 9
byte b = 5;
b = b * b;
IMPORTANT
You should use all the material in all the lessons to do the questions exercises. If you do not know
how to do something or have to use additional books or references to do the questions or exercises
please let us know immediately. We want to have all the required information in our lessons. By
letting us know we can add the required information to the lessons. The lessons are updated on a
daily bases. We call our lessons the "living lessons". Please let us keep our lessons alive.
E-Mail all typos, unclear test, and additional information required to:
courses@cstutoring.com
students@cstutoring.com
http://www.cscourses.com/java.htm
This lesson is copyright (C) 1998-2006 by The Computer Science Tutoring Center "cstutoring"
This document is not to be copied or reproduced in any form. For use of student only.
File: JavaL4.doc
STRING OBJECTS
Java has the String class that lets you use character strings with ease. You do not need to use the
new operator to instantiate a String class object. The Java compiler automatically creates a String
object in compile. When you declare a String reference variable the String reference is not referring
to any String object and is uninitialized. To declare a String reference:
object_type object_name;
.A String reference is used to hold the location where the String object is created in computer
memory. You may want to assign null to your string reference. null means your String reference is
not referring to any object.
You may want to assign an empty string object to your String reference. A String object is created
from the empty string.
What is the difference between String s; String s = null; and String s = ""; ?
String objects are made from character strings. When the compiler sees a character string it creates
a String object from it in compile time. The String objects are placed into a pool of other String
objects. You can assign a character string to an existing String reference:
The String object is created by the compiler and the String object location is assigned to the String
variable s.
To join two string objects together you use the + operator and assign the result to a String object
reference. A new String object is created and assigned to s. New String objects are always being
created from other String objects.
The string class has methods that you can use to do operations on strings. To use a string class
method, you specify which String object you want and then use the dot operator "." to specify
which method you want to use from the String class.
object_name . method_name(argument);
The above statement uses the length() method belonging to the String class to assign the length of
a string to the variable len. From the last page the String reference s refers to the String object
"hellogoodbye" . The length of a string is how many characters it has. What is the value of len ?
String objects are said to be immutable, this means once they are created they cannot be changed.
When you use a String method a new String object is always created and returned. The original
String object does not change. To be able to keep your change the String object returned must be
assigned to your String reference variable.
For example the substring() method is used to return a portion of a String object by specifying the
start and end characters:
s2 will now refer to the String object "hello" where s is still refers to the String object
"hellogoodbye", the original string does not change.
There are 2 different ways to test if a string object is equal to another string object
(1) using the equals() method to test if the data contents are equal (s1.equals(s2)) test data contents
(2) using the == operator to test if both string variables refer to the same String (s1 == s2) test location
object. We are testing if both string references refer to the same String Object
location.
To test if two string objects have identical data contents we use the equals() method:
(s1.equals(s2)) // test if the data contents of string s1 is equal to the data contents of string s2
To test if two string variables refer to the same String object location we use the == operator
(s1 == s2 ) // test if the data contents of string s1 is equal to the data contents of string s2
String pool
When we declare and initialize a string reference with a character string, a String object is created
automatically for you in compile time and placed into a string pool. The compiler does not want
to have more than 1 String objects with the same string data. The compiler will assign an existing
String object from the string pool if it sees more than 1 string reference assigning the same
character string. String objects are made from character strings. Character strings are not String
objects.
s1
String s1 = "Hello";
String objects can also be created in run time using the new operator. In this situation a new String
Object is crated in run time from the string object in the string pool created in compile time.
s1 "Hello"
String s1 = new String("Hello");
Now s1 and s2 refer to separate String objects. There is a lot of overhead and wasted memory in
creating string objects in run time. This is why it is seldom done.
case scenarios
Now let assign "Hello" to s2, notice the data contents are the same but the locations are same
Now let assign "Hello" to s2, notice the data contents are the same but the locations are different.
Now let assign s2 to s1, s1 = s2; notice the data contents are the same and the locations are the
same
s1 data location
s2 true true
Here is a small program demonstrating testing string for equality for all 4 cases.
// lesson 4 program 1
class L4P1
{
// test string objects
public static void main(String[] args)
{
// case 1: different data contents different locations
String s1 = "Hello"; // assign "Hello" to s1
String s2 = "Goodbye"; // assign "Goodbye to s2 s1: Hello s2: Goodbye
System.out.println("s1: " + s1 + " s2: "+ s2); // print out s1 and s2
The following chart lists some common String class methods and examples in how to use them:
Compare if two strings have sane data contents (s3.equals(s4)) cond false
test if two strings refer to the same string object (s3 = = s4) cond false
What happens if you assign s3 to s4 from the Strings in the above chart ?
It is false because "HelloHello" was not previously in the String pool so that an additional String
object was created for the String pool. When "HelloHello" was created by joining two "Hello" String
objects it "HelloHello" was not put into the String pool because "HelloHello" was created in run time
when the program was running.
LESSON 4 EXERCISE 1
Write a small program that just has a main method by answering the following questions, call your
class L4Ex1 and Java file L4Ex1.java
5. Assign s2 to s1
ARRAYS
An array is a group of consecutive same data types or object types sequentially allocated in
memory and accessed by a common name.
Each data type storing value is known as an element of the array. Arrays in Java are objects. The
Array objects stores the array data and has methods to do operations on that data.
Why do we need arrays? We need arrays when we want to access a group of numbers individually
that are sequentially stored under a common name. An example is a series of temperatures
recorded every hour for a particular day. Each number is the temperature for each hour. We need to
access each recorded temperature by a common array name like temperature.
using arrays
(2) must allocate memory for the Array object using the new operator
To declare an array reference variable we specify the data or object type with square brackets [ ]
and the array variable name. The square brackets[ ] indicate that this reference variable refers to an
array object. When you declare an array variable it does not refer to any Array object and is
unitialized if declared in a method but set to null if declared in a class.
data_type [ ] array_name;
You may want to assign null to a1 when you declare it to indicate it does not refer to any object yet.
Before you can use an array reference variable you have to allocate memory for an Array object.
You allocate memory for an Array object by using the new operator with the required size of the
array in square brackets. When you create an Array object array data elements values are set to
zero for primitive data types and null for object reference types.
An Array object of 5 integers is created and referenced to by a1. Each integer is known as an
element of the array. When an array only contains a single row of data, it is known as a 1
dimensional array. The row has the number of columns equal to the array size. Array reference
a1 refers to an array object of 1 row and 5 columns all elements initialized to zero. a1 has the
location of the array object.
(2) create an array object using the new operator: a = new int [5];
The above 2 lines may be combined into 1 line. You may declare an array reference variable and
allocate memory for the Array object in one statement.
int[] a = new int [5] // declare an array variable and allocate 5 integers
Each element of an array is accessed by an index. In Java array indexes start at 0 rather than 1.
When you have an array of 5 data types, the first element has an index of 0 where the last element
has an index of 4. Don't forget this. It is easy to get mixed up when accessing array elements.
array index:: 0 1 2 3 4
array elements: 0 0 0 0 0
You access an array element by enclosing the desired array index number in square brackets [
index].
array_variable_name[index ]
a[2]
0 0 5 0 0
variable = array_variable[index] ;
reading:
(1) Go to array
x = a[2]; // variable x will get array value at index(2)
2 get array element value at
index and give to variable
What is the value of x ?
You may use variables for array indexes. By using variables your program can change the array
indexes while your program is running.
int i = 2;
a[i] = 5; // array element at index 2 gets the value 5
x = a[i]; // variable x will get the value of array a1 at index 2
LESSON 4 EXERCISE 2
Declare a one dimensional array called a of data type integer of size 5 columns Assign to each
element of the array a its column index. Do not use loops. Print out the contents of the array and
the array length. Call your class L4Ex2 and your program L4Ex2.java.
You may assign an array variable to another array variable. When you assign array reference
variables to each other the location of the array object is given to the other array variable.
Now array variable a2 and array variable a1, refer to the same array object.
a 0 1 2 3 4
0 0 5 0 0
a2
You will find the values accessed by a1 are the same as the values accessed by a2.
You need to write your own method to test if the data contents of an array is equal. You can only
test if two array reference variables refer to the same array object.
if(a.equals(a2)) Test if 2 array objects refer to the same location not data contents
You will also test if two array variables refer to the same object location. The Array class does not
have a equals() method so the equals() method belonging to the Object super class is called that
just compares the array object locations. To test if two arrays contain the same values you would
have to use a for loop to test each value of both arrays for equality.
You can find the number of columns of a one dimensional array by using the array public length
member variable of the Array object
int len = a.length; // get length of array a1 length of one dimensional array
You can create a 1 dimensional array of object reference variables. First step is to make an array of
object reference.
Array a3 will be an array of string object reference variables, each element initialized to null.
null null
Second step is to fill your array with string objects. You assign string objects to each array element:
a3[0] = "hello"; // assign the string "hello" to array variable element index 0
a3[1] = "goodbye"; // assign the string "goodbye" to array variable element 1
"hello" "goodbye"
You can retrieve the String object also from your array of string variables. s
String s = a3[1]; // retrieve sting object referred by array at index 1
The String object location stored in a3[1] is assigned to the String object variable s.
LESSON 4 EXERCISE 3
Create a 1 dimensional array of 5 string objects, initialize each element the array to your favorite
word. Create an 1 dimensional array to hold 5 integers. Initialize each element in the array with a
randomly number between 0 to 4. Use the integer array as indexes to print out the words stored in
the String array. You do not need to use any loops. Call your class L4ex3 and your program
L4ex3.java.
LESSON 4 EXERCISE 4
Create two initialized arrays of equal length . Using statements test if each array are equal. Call your
class L4ex4 and your program L4ex4.java.
Arrays that have more than 1 row are called 2 dimensional arrays. The declared data type has 2
square brackets [ ][ ]to indicate a 2 dimensional array. To declare an 2-d array reference variable.
data_type [ ][ ] array_variable_name;
Before you can use an 2 dimensional array reference you have to create an Array object. You create
an array object by using the new operator with the required row and column sizes in square
brackets.
number number of
of rows columns
int[ ][ ] b = new int[3][4]; // declare and allocate memory for a 2-D array
To access the elements of a 2 dimensional array you specify the element you want by using the row
index and column index. in square brackets.
To write a value to a two dimensional array you must specify the row and column index.
LESSON 4 EXERCISE 5
Declare a 3 by 3 two dimensional array called b of int data type. Assign to each element of array b
the value of its row and column (example row 1 index column 2 index would get the value 12 ). Print
out each element of the array as the array should appear in row column order. Call your class
L4ex5 and your program L4ex5.java.
You can even have a two dimensional array of object variables. First step is to declare and allocate a
2 dimensional array of object variables and then create object for each array object variable.
reference to a reference to a
row 0 b2[0] b[0][0] b[0][1] row 0
string object string object
reference to a reference to a
row 1 b2[1] b[1][0] b[1][1] row 1
string object string object
b2[0][1] = "Hello";
b2[1][1] = "Goodbye";
reference to reference to
row 1 b2[1]
string object string object
"goodbye"
LESSON 4 EXERCISE 6
Allocate a 2 by 2 two dimensional array of String object variables. Assign to each element of the
array your favorite words. Print out each word of the array using a reference to each row. Call your
class L4ex6 and your program L4ex6.java.
Each element in the array is a String reference variable that will store the locations of a String
object. The second step is to assign the 2-dimensional array of String references String objects.
How do I access each individual elements of the 2-D array of objects ? Easy ! Each row index of b2
refers to a array of columns ! This means all you have to do is access each row index that refers to
the column you want. Each row index of a 2 dimensional array refers to one whole row. Example
b2[0] refers to the whole row at row index 0. You can now access each array elements by first
referring to the columns of a particular row. You need a 1 dimensional array variable to refer to a
row of a 2 dimensional array.
r[0] r[1]
Once you get a variable to a particular row of a 2 dimensional array then it is easy to access an
element of the column of that row..
What does s refer to ? What is the difference between a String[ ] and a String ?
reference to reference to
row 1 b2[1]
string object string object
"goodbye"
You can also use variable indexes to access elements of a 2 dimensional array.
x = b2[1][2]; // x gets the value of array location row index 1 column index 2
You can find the number of rows of a two dimensional array by using the length directive.
int rowSize = b2.length; // get how many rows the 2-d array r has
To find out how many columns a particular row has you must specify which row of the 2 dimensional
array. You specify which row you want by using a row index on the array reference variable.
int colSize = b2[0].length; // get the number of columns this row has
LESSON 4 EXERCISE 7
Create a 2 dimensional array of 2 rows and 3 columns to hold String objects. Declare a 1
dimensional array reference variable. Assign to the 1 dimensional reference variable the first row of
the 2 dimensional array. Use the 1 dimensional array variable to assign string objects of your
favorite words to the 2 dimensional array. Repeat for the second row. Call your class L4ex6 and
your program L4ex6.java.Print out all the String objects stored in the array using the 2 dimensional
array reference printing in column - row order first. We are now printing the first column of each
row first:
INITIALIZING ARRAYS
Arrays may be initialized when they are declared. You can initialize an array with constants each
separated by commas and all enclosed in curly brackets. The new operator is not needed when
initializing arrays. Java will reserve memory for you automatically in compile time. To declare and
initialize a 1 dimensional array of 5 integer elements:
You can even initialize a 1 dimensional array to hold references to String objects.
"hello" "goodbye"
"hello" "goodbye"
"tomorrow" "today"
arrays of objects
The Object class is the super class of all Java objects, using an array of Objects means you can
have an array of many different Object types. The only Objects we know about is the String object,
the Array object and our own classes.
When you access an Object in the array of objects you have to type cast. Typecasting informs the
compiler about the expected Object type you want to use. To type cast you put the data type or
object type in round brackets ahead of the what needs to be type casted. Type cast does not change
the original object, it only the forces the object type of the original object to be the same as the
object reference you are assigning to.
(object type)
Incrementers and decrementers are used to change the values of array index variables automatically
for you. We use both the pre --i and post i++. Pre means increment before and Post means
increment after the assignment. Using incrementers and decrementers is a 2 step process. The
value is extracted from the array at the index then the index is incremented or decremented or the
index is incremented or decremented and the value extracted.
LESSON 4 QUESTION 1
A one dimensional array is initialized with the following values: int a = {10,12,34,21,24}; and i is
set to 2: int i = 2;
a 10 12 34 21 24
Fill in the columns for each value of x and i before and after the statement is executed. Assume all
operations are continuous. Each answer relies on the previous result. Hint: put the array indexes on
the top of the array for each column.
x = a [i++]; 2
x = a [++i];
x = a [i--];
x = a [--i];
Arrays come in handy for constructing variables to hold primitive data types like int, float, double
etc. Primitive data types are not considered objects. You can make a variable to hold a primitive
data type like an integer by constructing a one dimensioma1 element array. You first declare an
array reference variable and allocate memory for a integer data type.
You next assign a value to the 1 dimensional element array and put a value into the array at index
0:
a ----> 5
LESSON 4 EXERCISE 8
Write the following small program that just includes a class and a main function. You may want to
print your values on your computer screen by using the System.out.println() method. Figure out the
values before printing out the correct answer. Call your class L4ex8 and your program
L4ex8.java.Examples using System.out.println ():
IMPORTANT
You should use all the material in all the lessons to do the questions exercises. If you do not know
how to do something or have to use additional books or variables to do the questions or exercises
please let us know immediately. We want to have all the required information in our lessons. By
letting us know we can add the required information to the lessons. The lessons are updated on a
daily bases. We call our lessons the "living lessons". Please let us keep our lessons alive.
E-Mail all typos, unclear test, and additional information required to:
courses@cstutoring.com
students@cstutoring.com
http://www.cscourses.com/java.htm
This lesson is copyright (C) 1998 -2006 by The Computer Science Tutoring Center "cstutoring"
This document is not to be copied or reproduced in any form. For use of student only.
File: JavaL5.doc
A Java program is made up of classes. Java classes are made up of variables and methods.
Methods are made up of variables and programming statements. The variables in a method are
only known to that method only. Methods are called by other methods to calculate a value. A
method may or may not return a value. Methods are needed to avoid repeating statements in a
program. For example the method to calculate the square of a number is used over and over again
when we want to calculate the square of a number.
programming
class methods
statements
class definition
Classes are made up of variables and methods. The main reason we need a class is that we need
variables to be shared between all the methods belonging to the class. This is what object oriented
programming is all about, classes containing methods sharing common variables. The variables
defined in the class are usually for use by the methods defined in the class and nobody else. A class
is introduced by the visibility modifier the class keyword and a name. In the class definition we
declare and define the variables, constructors, methods, and main method and toString methods.
main method // creates i/o streams, creates classes and call's class methods
The visibility modifier specifies if the class is public. If the visibility modifier is missing then the
class is assumed to be friendly. A public class can be used by any other class. A friendly class can
only be accessed in the package it was defined in. The variables defined in the class are used for
storage and retrieval of data to be shared between all methods defined in the class. The
constructor is used to initialize variables of the class when the class is created. The methods are
used to do calculations for the class and exchange data to other classes. The main method is used
to create an object of the class by calling the class constructor. The toString method is used to
return a String representation of the variable values defined in the class. All executing objects
variables and methods can be referenced by the this reference variable provided automatically by
the Java compiler. Each object created from the class definition will have its own memory area for
the variables declared in the class. We are providing an example class Calculate. The following is
the start of the class definition.
When a method uses the services of another method, the method using the method is called the
calling method and the method being used is called the called method. The calling method may
want to send values to the called method.
The called method receives the values from the calling method through a parameter . A parameter
has a specified data type and name. A parameter can be used like a variable in a method and
already has a pre-initialized value.
If more than one parameter is needed then the parameters are separated by commas. When you
have more than one parameter then you have a parameter list.
The values sent to the method through the parameters are called arguments. An analogy to a
parameter is a receiving dock of a warehouse that receives goods. The receiving dock has a name
(parameter name) must know what kind of goods (parameter type) it will be receiving. The
receiving dock gets the goods and distributes for use in the warehouse. Before we can use a method
it has to be declared and defined. In Java methods are declared and defined right in the class. A
method is declared and defined by visibility, what value it returns, a name, and a parameter list.
The above square() method has public visibility, which means any one can use it, returns an int
value, has the name square and has a parameter list with an int parameter. The square method
calculates the square of the number it receives through its parameter list.
A method may or may not return a value to the calling method. The method may accept no
parameters or not return a value, or may have many parameters and return a value etc. When a
method does not return a value the keyword void is used for the return data type. The following
method putValue() writes a value to the screen but does not return a value. The return data type is
void.
Calling a method
A method calls another method by its name and passes values to that method. The values passed
are known as arguments. An argument can be a variable, constants, expressions or even a
method call. In case of expressions the evaluated value of the expression is used. If the argument is
another method call the return value of the method is used. You call a method by its name and
supply the required number of arguments enclosed by round brackets. The number of required
arguments usually but not always depends on the number of parameters defined in the method.
method_ name ( );
If more than one argument is needed then the arguments are separated by commas.
calling called
method method
return data
An assignment statement is used to assign the return value of a method to a variable in the calling
method.
The main method is the first method to be executed when a Java class is ran. Each class can have
its own main method. If each class has its own main method then, you can test each class
individually. The main method job is to make objects of the class it was defined in. In this case the
main method will make a calculate object called calc.
{
Calculate calc = new Calculate(); // instantiate class
int x = calc.square(5); // variable x gets square of 5 */
System.out.println("square of 5 is = " + x); // print value of x
}
The main method has the static modifier. The static modifier specifies to the compile that this
method can be used directly without accessing an object. The purpose of a main method is to
instantiated all the objects needed to get the program running. We use the new operator to make
an instance of a class. Classes that are instantiated are known as objects. The new operator
allocated memory for he object. The object contains the variables defined in the class. Every time
you define a class you are also defining an object type. You se this object type to declare references
to objects created from the class definition. To instantiated a class you declare a object reference of
the class you want to create and call the class constructor. The constructor's job is to initialize the
objects variables defined in the class with values. The object also includes references to the methods
defined in the class definition. Static methods are readily available from the class where non-static
methods can only be called from an object created from the class definition. In our example the
Calculate class we do not have a constructor because we do not have any variables defined in the
class. In this situation the Java compiler supplies a default constructor for you. You create an object
from a class definition as follows:
What is the difference between a class and an object ? A class defines the variables and methods an
object needs. An object is allocated memory for the variables defined in the class. After the
calculate class is instantiated we call the square method to calculate the square of a number and
returns the result to the calling method (the main method). To call the method of a class object you
use the object reference name, the dot operator "." and the method name you want to call. The dot
operator states that this method belongs to this object.
calc
5
calc.square(5);
square method
(called)
x
25
The main method creates a Calculate object reference by the object reference calc located in the
main method. The main method is static meaning the code is ready to be used. The variables
defined in a static method are also static. The main method calls the square method reference by
the object reference calc.
LESSON 5 PROGRAM 1
{
public static void main(String args[])
{
Calculate calc = new Calculate(); // create calculate object
int x = calc.square(5); // variable x gets square of 5 (25)
System.out.println("square of 5 is = " + x); // print value of x
}
{
return x * x; // return square of x
} square of 5 is = 25
LESSON 5 EXERCISE 1
Type in the calculate class, call your program Calculate.java. Try to find the square of other
numbers like 10, 20 etc. Add a putValue() method that will print out the value of a number. Call
the putValue() method from the main method.
program flow
The main method calls the square method of the Calculate class to calculate the square of 5.
int x = square ( 5 ) (1) The main method calls the square method with the argument 5
(2) The parameter x receives the value of 5 from the calling method. The square
int square( int x )
method calculates the square of a number and returns the results
x (3) The calling method gets the results from the square method, and assigns the
(25) returns value to the variable x. The main method continues executing statements
overloading methods
A method in a class can have the same name as other methods in the class as long as it has a
parameter list with different data types. The parameter names may be different or same but the
data types must be different This technique is known as method overloading. Same method name
but different parameter list. The compiler knows which one to call by matching the parameter
number and data types.
{
return x * x; // return square of x int square(int x)
}
Unfortunately method overloading does not work for return data types. The following method will be
overloaded to a double even though the return type is int.
{ int
return x * x; // return square of x
} int square(double x)
LESSON 5 EXERCISE 2
Add to the Calculate class the above overloaded square methods and try them out in your main
method. Then change one of the overloaded method to have a default parameter and call it in the
main method. Also add square overloaded functions of parameter type characters. When you take
the square of 2 chars data types Java converts the results to int, you need to convert them back to
char by typecasting to char. return (char) (ch * ch); Try to find out the square of a square by
calling the square method with a square method as its argument !
Values are passed to a method from the calling method to the called method by use of an
argument list. The method being called receives the values through its parameter list. A
parameter list allows methods to receive values. There is a sequential one to one correspondence
between the calling methods argument list and the called methods parameter list. The parameter
and argument name maybe the same or different but the object and data types must be identical.
The parameters x, y, z are known as the formal parameters and the received values are called the
actual parameters. Arguments a, b, c must be of data types: int a; float b and double c;. The actual
parameters receive values from the argument list that are passed to the formal parameters. The
formal parameters may be used just like pre-initialized variables in your method. The arguments are
mapped into the parameters.
When you call a method and pass arguments to that methods parameters is like equating the
arguments to the parameters, parameter = argument. in our above example x = a; y = b and z =
c; The parameters become temporary variables in the method.
Values are passed to the method through a parameter list. In Java all parameters are passed by
value. When values are passed by value, this means a copy of the value of the variable is given to
the called method. A copy of the variable is made for use in the method. If an object reference is
passed to a method then a copy of that object reference is made for use in the method. This does
not mean a copy of the object but a copy of the reference variable. This means you can still change
the member variables of the class referred to by the object reference, but you cannot change what
the object reference refers to.
pass by value
When a variable is passed to a function by value the parameter in the called function holds a copy
of the passed value. The parameter is a temporary memory location to hold the value passed to it.
This means you cannot change the value of the variable in the calling function from the called
function.
class PassValueTest
{
public static void main(String[] args)
{
Calling int x = 5;
function funcv(x); x 5
} Called
function
void funcv(int x)
x 5 10
{
x = 10;
}
}
Each function has its own x. Each x is separate and cannot effect each other. If you assign a another
value to the x in funcv then that x would get a new value. The x in main will retain its original value.
When a variable is passed to a function by object reference the parameter in the called function
holds a copy of the passed value. The parameter is a temporary memory location to hold the value
passed to it. This means you cannot change the value of the object reference in the calling function
from the called function. The value of an object reference is the location of an object.
class PassReferenceTest
{
public static void main(String[] args)
{
Calling String s = "Hello";
function funcr(x); s "Hello"
}
Called
function
void funcr(String s)
s 10
{
x = 10;
}
}
Each function has its own s. Each S is separate and cannot effect each other. If you assign a another
String object to s in funcr then that s would refer to another String. The s in main will retain its
original reference.
class PassReferenceTest
{
public static void main(String[] args)
{
Calling String s = "Hello";
funcr(x); Called
function s "Hello"
} function
"Goodbye"
void funcr(String s)
s 10
{
x = 10;
}
}
This is easily explained using an example class the Point class. The Point class has two public
variables x and y. you can pass an object reference of this class to a method. You can change the
value of x and y of the point class object in the called method. You can make the object reference
point to another point class and change its public variables. But the original point class variables do
not change. In contrast if we pass a String object reference to a method and change the contents of
the String in the calling method to a new message, and when we print the value of the String class
object after the method is called it has the same message. Why ? The answer is this, the String class
always makes a copy of the original String, so we need to re-assign the new copy of the String to
the original String object reference. When we are in the called method we cannot do this because we
pass the String object reference by value. The direction is input only. We cannot change the
contents of the original object reference in the calling method. Here's the Point class and Change
class.
LESSON 5 PROGRAM 2
{
p
p.x++;
p.y++; "hello"
s
p = new Point(p.x,p.y);
p.x++;
p.y++;
s = "goodbye";
7,12
}
}
"goodbye"
// initializing constructor
public Point (int x, int y )
{
this.x = x;
this.y = y;
}
LESSON 5 EXERCISE 3
Type in the above program and print out the values in the Change constructor line by line;
If you need to receive values back from a method through its parameter list, then you can send and
receive values to that method by using a singled element 1 dimensional array. When the method
receives the array reference it can change the value inside the array. The calling method can read
the value changed in the array. In our example, we just use a static methods to avoid making
objects.
class Surprise
{
a[0]
public static void main(String args[])
{
update(int[] x)
// create a 1 dimensional 1 element array
int[] a = new int[1];
a[0] = 0; // set array element to 0
// print out value before
System.out.println("the value before is: " + a[0]);
x = update(a); // call method change
// print out value after
System.out.println("the value after is " + a[0]);
}
LESSON 5 EXERCISE 4
Write a program that has method with 2 String parameters String and an array String reference.
In the method join the two strings together set the array reference to the result. The main method
will declare 2 String object reference each initialized to your favorite words and an initialized array
reference. Print out the values of the variables before and after the function call. Call your class
L5ex4 and your program file L5ex4.java.
Return values may also be passed to the calling method by value or by object or array reference.
The return statement inside the method is used to return values to the calling function.
return expression;
The return statement is not necessary if the method does not return a value. A return statement
without an expression will force the method to terminate. You can only uses the return statement
with methods that have return data types of void.
return;
Primitive data types like int and float are passed by value, arrays and object are passed by object
reference
{
return i + i;
}
{
return true;
}
{
return s + s;
}
{
a[0] = a[0] * a[0];
return a; // return array reference
}
If a method does not return a value then the method name is preceded by the keyword void. This
methodc just prints out a value does not return anything.
{
System.out.println("the value is: " + i);
}
void can also be used in the parameter list if the method accepts no parameters. This is seldom
done, if so then only by programmers who are paranoid.
{ {
return num; return num;
} }
LESSON 5 EXERCISE 5
Write a program that has method with 2 String parameters String and returns a String reference . In
the method join the two strings together and return the result. The main method will declare 2
String object reference each initialized to your favorite words and an initialized array reference. Print
out the values of the variables before and after the function call. Call your class L5ex5 and your
program file L5ex5.java.
LESSON 5 QUESTION 1
A small program is presented next to demonstrate pass by value and pass by object reference and
return by value and object reference You may want to keep a chart to record the values for each
method call.
start
methoda
methodb
methodc
methodc
{
// main method
public static void main(String[] args)
{
int x = 5; // declare integer variable x and assign 5 to it
int y = methoda(x);// call methoda pass by value
// what is the value of y ? // 6
// what is the value of x ? // 5
String s1 = "hello";
// what is the value of s1 ? // "hello"
String s2 = s1;
// what is value of s2 ? // "hello"
// what is value of s1 ? // "hello "
s1 = methodc(s2);
// what is the value of s1 ? // "goodbye"
// what is the value of s2 ? // "hello"
} // end main
{
// what is the value of i ?
i++; // what is the value of i ?
return i; // what value does the method return ?
}
{
// what is the value of i[0] ?
i[0]++; // what is the value of i[0]?
return i[0]; // what value does the method return
}
{
// what is the value of s ?
s = "goodbye"; // what is the value of s ?
return s; // what value does the method return ?
}
Arrays are passed by array reference. Pass by array reference holds the location of the Array
object. It is this location that is passes to the method not the Array object itself. An added bonus
when using array references is that when you change the value of the array element inside the
method, the array outside the method will retain this new value. You cannot change the original
array reference inside a method.
An array reference is indicated by the[ ] on the data type : int[] a. The following method has a
array reference as its parameter:
When an 1 dimensional array is passed to a method only the name is used, because an array name
is a reference.
The following example program initializes a 1 dimensional array and has a method that returns an
array value at a specific index..
{
int a[]={1,2,3,4,5}; 1 2 3 4 5
int value = getValue(a,1);
System.out.println("The array value at index 1 is: " + value);
}
LESSON 5 EXERCISE 6
Write a Java program that has only one class called L5ex6 and a main method that declares an 1
dimensional array of 5 integers pre-initialized to your favorite values. Pass the array and an index
to a static method called change( ). Add to the array at the specified index the array value and the
array index. Return the value of the array at the specified index to the main method Print out the
return value and the value at the array index to the screen using System.out.println(). Call your
program L5ex6.java To use System.out.println() to print a message and a value:
System.out.println(" x is " + x );
You use two square brackets [][] to specify a data type as a 2 dimensional arrays reference.
When an 2 dimensional array is passed to a method only the name is used, because an array name
is a reference.
The following example program initializes a 2 dimensional array and has a method that returns an
array value at a specific row and column index.
{ 1 2 3
// main function
public static void main(String[] args) 4 5 6
{
int b[][]={{1,2,3}{4,5,6}};
int value = getValue(b,1,2)
System.out.println ("The array value at row index 1 column index 2 is " +
value);
}
{
return a[i][j]; The array value at row index 1 column index 2 is: 6
}
LESSON 5 EXERCISE 7
Write a Java program that has only one class called L5ex7 and a main method that declares an 2
dimensional array of 2 rows by 3 columns of integers pre-initialized to your favorite values. Pass the
array and row and column index to a static method called change( ). Add to the array at the
specified row and column index the array value and the row and column index. Return the value of
the array at the specified index to the main method Print out the return value and value at the
array row and column to the screen using System.out.println(). Call your program L5ex7.java To
use System.out.println() to print a message and a value: System.out.println(" x is " + x );
To return an array you must include the square brackets with the data type. When an array is
returned from a method only the name is used, because an array name is a reference.
int a1 = {1,2,3,4,5};
The following program calls a method that receives a 2 dimensional array reference and returns a 1
dimensional array reference.
// Lesson 5 program 6
// passing array references
class L5p6
{
// pass an 2D array reference, return an 1D array reference
static int[] method(int[][] b) {
int[] a = new int[b.length*b[0].length];
a[0] = b[0][0];
a[1] = b[0][1];
a[2] = b[0][2];
a[3] = b[0][0];
a[4] = b[0][1];
a[5] = b[0][2];
return a;
}
{
// initialize a 2-d array
int[][] b = {{1,2,3},{4,5,6}};
// pass 2-d and receive a 1-d array reference.
int[] a = method(b);
// print out sum of 1 dimensional array
System.out.println(a[0]+a[1]+a[2]+a[3]+a[4]+a[5]);
}
LESSON 5 EXERCISE 8
Write a Java program that has only one class called L5ex8 and a main method that declares an 1
dimensional array of 6 integers pre-initialized to your favorite values. Pass the array to a method
called convert that returns a 2 dimensional array of 2 rows and 3 columns. Print out the values of
the returned 2 dimensional array in main. Do not use any loops. Call your program L5ex8.java
IMPORTANT
You should use all the material in all the lessons to do the questions and exercises. If you do not
know how to do something or have to use additional books or references to do the questions or
exercises please let us know immediately. We want to have all the required information in our
lessons. By letting us know we can add the required information to the lessons. The lessons are
updated on a daily bases. We call our lessons the "living lessons". Please let us keep our lessons
alive.
E-Mail all typos, unclear test, and additional information required to:
courses@cstutoring.com
students@cstutoring.com
http://www.cscourses.com/java.htm
This lesson is copyright (C) 1998-2006 by The Computer Science Tutoring Center "cstutoring"
This document is not to be copied or reproduced in any form. For use of student only.
File: JGuideL6.doc
Class Definition
Classes are defined by an access modifier, the keyword class and a class name.
{
private variables
constructor
set methods (mutator methods)
process methods (calculating
methods)
get methods (accessor methods)
main method
toString method
}
The access modifier states who can access the class. The class key word states the following
block of code enclosed in curly brackets is a class and the class name identifies this block of
code. The access modifier is public or private
public means all classes can use the variables and methods belonging to this class
friendly is not a keyword but is the default visibility if you do not include an access modifier.
Class Example
We will explain a class by using an example. We will use the Vehicle class as an example.
The Vehicle class has private variables for the color and year of the Vehicle. The
constructors have parameters to initialize variables defined in the class. The Vehicle class
has methods to get information and send information.
The vehicle object will have variables to describe the vehicle as follows:
variables description
object references
After a class is defined a reference to a Vehicle object has to be declared before an object
can be made. Declaring an reference to an object is just like declaring a variable.
The only difference instead of a data type we have a object type. The object type is the
class name.
When you declare variable as an object type then it is known as an object reference. An
object reference refers to an object. An object reference is not a object, it only stores the
location of a object. You need to create an object before you can use it. Just like a cake
needs to be baked before it can be eaten. You use the new keyword to allocate memory
for the object and call the class constructor to initialize the variables defined in the class.
The new operator allocates memory for the variables required by the object and the
constructor is used to initialize the variables belonging to the object. The constructor
receives values through its parameter list to initialize the variables of the object. The object
reference refers to the created object. The object reference holds the location where the
object is created in computer memory.
v1 Ford
Mustang
red
1989
object properties
Each object created will have distinguishable properties. When you define a class you list
the variables and methods the class needs. How does each object get distinguishable
properties ? When you create an instance of a class the object will get distinguishable
properties when you initialize its data member variables. For example, the Vehicle class
may be defined with make, model, color and year. The Vehicle class may be defined with
constructors to initialize make, model, color and year and methods to assign and retrieve
these values. Every time you create an object from the Vehicle class definition you will get a
separate Vehicle object. Each Vehicle object would have a different make, model, color and
year. Each Vehicle object is distinguishable from other Vehicle objects because each Vehicle
object has unique properties when the variables were initialized by the constructor when the
object was created. An object is allocated memory for the variables defined in the class.
v1 v2
Ford Toyota
Mustang Swift
red green
1989 1995
variables
Variables are defined in the class and used by the object to store and retrieve data. All
methods defined in a class may access these variables. Variables defined in a class may be
public or private.
private int x;
public means everybody can use the variables belonging to this class
private means only methods of this class can use variables belonging to this class
Variables in a class should always declared private. This is one of the main purpose of a
class is having methods belonging to a class to access common variables. By having private
variables forces all class to exchange data through methods rather than directly using the
variables. This is a highly desirable thing to do. The programmer now can use objects
without worrying about data corruption and how the data is stored in the object. Variables
that do not specify a access modifier are known as friendly. There is no keyword friendly it
is just the default visibility.
Variables defined in a class, method or parameter list may have the final modifier. Final
means you cannot change the value of the variable once it is initialized. A final variable
must be initialized when it is declared and is known as "read only".
private final int CurrentYear = 1999; // final variable initialized to current year
When you only want one variable to be allocated then you declare a variable to be static.
Only one memory location is allocated for a static variable. Static variables are also known
as class variables. In contrast non-static variables are known as instance variables,
because a new variable is made every time an instance of the class is made. Static variables
should be initialized to a default value when they are declared. Static variables can only be
declared in the class definition. Static variables cannot be declared in a method. Static
variables must declared in the class definition and should be initialized to a default value
like 0. Note: Static methods can only access static variables.
Object
Instance variable
program memory
When do we need to uses a static variable ? We use static variables when all objects need
to access the same variable value. A good example is to keep track of how many Vehicle
objects were created. This can be done by using a static variable. Every time an instance of
the class is made the static variable can be incremented. To access the static variable inside
the class you just use it just as a variable belonging to the class.
When accessing a static variable outside a class you must use the class name not the
instance (object name) name. You access static variables outside the class by using the
class name, the dot operator and the static variable name.
class_name . static_variable_name
x = Vehicle.num; // assign to x the value of the static variable num.
It is possible to access static variables by the instance name because every object has
access to its class variables and methods. It is better programming when accessing static
variables to use the class name not the object name.
Class elements:
Classes are made up of variables, constructors, main method, input methods, process
methods and output methods. We will now discuss all the components of a class. An
automatic reference to the executing object or the class you are defining is called this. You
use the this reference to refer to variables and method belonging to the object currently
running. All methods belonging to the class share the variables belonging to the class.
receive Data from outside world ----> set Methods store input data in variables of class
get data from variables in class get Methods -----> send Data to outside world
Set methods are sometimes called mutator methods and get methods are sometimes
called accessor methods. The beauty of Java is that it has special methods called
constructors that are automatically called to initialize variables defined in the class and
allocate memory for any other objects or arrays when the class is instantiated. We use the
vehicle class as an example.
// vehicle class
public class Vehicle
{
private String color = ""; // initialize to default value
private int year = 0; // initialize to default value
public static int num = 0; // number of vehicle objects created
private final static currentYear=1999; // current year
default constructors
Default constructors accept no arguments and are used mainly to initialize variable
belonging to the class. Default constructors are not used too much in Java because
variables belonging to the class can be initialized when they are declared. Default
constructors must be included if you want to make default objects if other constructors are
defined
// default constructor
public Vehicle ( )
{
year = 0; // initialize to default values
color = ""; Vehicle
num++; // increment instance counter
}
Initializing constructors
Initializing constructors accept arguments that are used to set variables belonging to the
class to user specified values. A class may have more than one initializing constructor
depending on what data is required to initialize private variables. Notice that the parameter
year has the same exact spelling as the variable year belonging to the class. The this
variable is used to distinguish a variable belonging to the class and a parameter.
// initializing constructor
public Vehicle (String color, int year )
color year
{
this.color = color; // initialize color
this.year = year; // initialize year
num++; // increment instance counter Vehicle
}
conversion constructors
Constrictors that store the data in a completely different format then from the input data
format are called conversion constructors. For example Year may be represented a string
that we have to convert to a numeric value. The Integer.parseInt(year) is used to convert a
year in String to an integer data type using the parseInt method of the Integer class we will
study in future lessons.
{
this.colour = color;// initialize vehicle color
this.year = Integer.parseInt(year); // convert year Vehicle
num++; // increment instance counter
}
copy constructors
There are also constructors that copy the data from an existing objects they are called copy
constructors. Copy constructors receive a reference of the class they are copying. All the
variable values are copied from Vehicle object v2 into the Vehicle object being created
refereed to by the this reference.
// copy constructor
public Vehicle (Vehicle v2 )
Vehicle v2
{
this.colour = v2.colour;// initialize vehicle color
this.year = v2.year; // convert year Vehicle
num++;
}
Methods
The main method is used to instantiated the class it is in, create the required input and
output data streams, and call methods from the instantiated classes. Set methods are
used to initialize variables with data from the outside world and are made public. Set
methods are also called mutator methods because they are changing the variables.
Process methods may be private or public and do calculations using the private variables
belonging to the class. Get methods return data to the outside world from the variables
and must be made public. Get methods are also called accessor methods because they are
accessing data. Variables and methods are declared and defined right in the class definition.
Variables and methods belonging to a class are called member variables and methods.
The access modifier is used to set the visibility. Visibility sated who can access the method.
visibility analogy
Only the class can access its own private variables and methods. Anybody else who wants
to access these private variables must use the class methods to access them. Think as
private variables as being bars of gold in a bank. Think as the security guards as methods
that allow the outside world to access the gold bars. If anybody could just walk into a bank
and get gold bars then the bank would soon go broke. In contrast public variables allow
everybody to access the information, think as these variables as waste paper baskets on the
street. People are free to deposit waste and to pick up waste. Methods are used to exchange
data between classes:
class A class B
methods methods
private private
exchange
variables variables
data
methods methods
The main method is used to instantiate the class it resides in. You must declare an object
reference of your class and use the new operator to create the object and call the class
constructor to initialize the object. The created object is assigned to the declared object
reference. When you create an object of your class this is called instantiating the class.
The class is the definition that defines how the object is to be made. Object references are
declared just as you would declare a variable.
1989 year
Member variables and methods are accessed by the "." dot operator which means "belongs
to"
veh.year = 0;
The this reference is used to refer to the executing object or class you are defining. It
comes in handy when you want to distinguishes a variable defined in a class to a
parameter with the same name.
To call a method belonging to a object you call the method using the object reference the
dot operator and the method name and include any arguments.
veh.setColor("red");
If the method returns a value then you can assign this value to a variable.
toString() method
The toString() method returns a string representation of your object. This means it returns
the names and values of variables declared for this object.
{
String s = "\n" + "Vehicle info " + "\n";
s += "colour: " + colour + "\n";
s += "year: " + year + "\n";
s += "number of vehicles: " + num + "\n";
return s;
}
The first method a Java program executes from the class is the main method. The main
method is located in the running class. The main method can be used directly without a
reference to an object Why ? The main method is used to instantiate the class it is in. The
running class has the same name as the Java file name and is case sensitive.
{
variables and statements
}
{
Vehicle v1 = new Vehicle("red",1989); // make red vehicle
System.out.println(v1); // print vehicle info
Vehicle v2 = new Vehicle ("green",1990); // green vehicle
System.out.println (v2); // print vehicle info
Vehicle v3 = new Vehicle(); // instantiated a new vehicle
System.out.println (v3); // print vehicle info
v3.setColour("red"); // set vehicles colour to red
System.out.println (v3); // print vehicle info
v3 = v2; // v3 refers to vehicle v2
System.out.println (v3); // print vehicle info
}
The main methods must be public for everyone to use, static this method can be used
directly without a reference to an object. Void means this method does not return a value.
The input parameter arg of the main method allows the user to pass data to main method
before the main method runs. The main method may need a file name to open a data file
etc. The following is the complete Vehicle class definition.
LESSON 6 PROGRAM 1
import java.io.*;
// vehicle class
public class Vehicle
{
private String colour = ""; // initialize to default value
private int year = 0; // initialize to default value
private static num = 0; // number of vehicles created
private final static currentYear=1999; // current year
{
year = 0; // initialize to default values
colour = "";
num++; // keep track of number of vehicle objects created
}
// initializing constructor
public Vehicle (String colour, int year)
{
this.colour = colour;
this.year = year; // initialize the year and color
num++; // keep track of number of vehicle objects created
}
// conversion constructor
public Vehicle (String color, String year )
{
this.colour = color;// initialize vehicle color
this.year = Integer.parseInt(year); // convert year to int
num++; // keep track of number of vehicle objects created
}
{
this.colour = v2.colour;// initialize vehicle color
this.year = v2.year; // convert year
}
{
this.colour = colour; // set colour
}
{
this.year = year; // set year
}
{
return color; // return color
}
{
return year; // return year
}
{
return(year <= CurrentYear); // check if year is valid
}
{
String s = "\n" + "Vehicle info " + "\n";
s += "colour: " + colour + "\n";
s += "year: " + year + "\n";
s += "number of vehicles: " + num + "\n";
return s;
}
{
Vehicle v1 = new Vehicle("red",1989); // make red vehicle
System.out.println(v1); // print vehicle info
Vehicle v2 = new Vehicle ("green",1990); // green vehicle
System.out.println (v2); // print vehicle info
Vehicle v3 = new Vehicle(); // instantiated a new vehicle
System.out.println (v3); // print vehicle info
v3.setColour("red"); // set vehicles colour to red
System.out.println (v3); // print vehicle info
v3 = v2; // v3 refers to vehicle v2
System.out.println (v3); // print vehicle info
}
red
v1
1989
program output:
Vehicle info
colour: red
year: 1989
number of vehicles: 1
Vehicle info
colour: green
year: 1990
number of vehicles: 2
Vehicle info
colour:
year: 0
number of vehicles: 3
Vehicle info
colour: red
year: 0
number of vehicles: 3
Vehicle info
colour: green
year: 1990
number of vehicles: 3
LESSON 6 EXERCISE 1
Type in the Vehicle class definition and run it. Add some more tests in the main program.
Copy existing Vehicle objects using the copy constructor. Test the vehicle year by using the
verify Year method. The Java program will be typed into a file having the same name as the
class Vehicle.java. Call your project L6ex1. You will notice the System.out.println()
statements in the main method. They are used to print out values of the variables to the
screen. Add make and model attributes to the class definition, and the required supporting
methods to the Vehicle class. An example of a make would be "Ford" and an example of
model will be "Mustang" Retest your program after adding the additions to your class Use
the static variable num to keep track and report how many vehicle objects were
instantiated.
Make a student class that has a name and id and mark. Make constructors to initialize the
variables defined in the class and make methods to get and set name and mark. Don't
forget to make a toString() method. In your main method test your student class by
making student objects and printing them out.
Student name
id
mark
LESSON 6 EXERCISE 3
In the Student class make an array of marks (max 4 marks). Make a variable to hold the
average mark. Make a method to set a mark: setMark(double mark, int index) by
supplying a mark and a index to the mark array. Make a method to get a mark: double
getMark(int index) by supplying a index to the mark array. Make a method to calculate the
average from the marks stored in the array. double calcAvg(); Update the toString()
method to print out the marks and the average mark. In your main method test your
student class by making student objects and using the setMark() method to set the marks.
Printing out all the student objects created..
You should use all the material in all the lessons to do the questions and exercises. If you
do not know how to do something or have to use additional books or references to do the
questions or exercises please let us know immediately. We want to have all the required
information in our lessons. By letting us know we can add the required information to the
lessons. The lessons are updated on a daily bases. We call our lessons the "living lessons".
Please let us keep our lessons alive.
E-Mail all typos, unclear test, and additional information required to:
courses@cstutoring.com
students@cstutoring.com
http://www.cscourses.com/java.htm
This lesson is copyright (C) 1998-2006 by The Computer Science Tutoring Center "cstutoring"
This document is not to be copied or reproduced in any form. For use of student only
File: JGuideL7.doc
class
We now look at java programming statements. Method
Programming statements are contained in the methods and
are the instructions telling the computer what to do. The
methods have temporary variables that the programming Temporary
statements use for intermediate calculations. In the Variables
methods we are most interested to control program
execution flow. We use conditional statements using if and
else. We use loop statements for repeating programming Programming
statements. Statements
Method statements are now introduced by typical application. There is no specific order in which to
use them. You may declare and initialize variables as you need them The only catch is that if you
declare a variable inside a statement block then the variable is not accessible outside the statement
block. A statement block is any statements enclosed by an opening "{" and closing "}" curly
brackets. The following test example is one complete Java program written in a main method. You
can type in each statement to see how it runs. The programming statements are written in blue and
the comments are written in green. Be careful not to type in the text explaining each section.
/* L7p1.java */
// class to test statements
class L7p1
{
public static void main(String args[ ])throws IOException
{
// declare constants
final int MaxSize = 10;
final int NumRows = 3;
final int NumCols = 3;
if statement
The if statement is used with conditions to make a decision in a program flow. An if statement
contains one or more conditions that are evaluated as true or false. When the if expression is
true then the statements belonging to the if statement is executed. When the if condition is false
then program flow is directed to the next program statement. If an if statement has more than one
statement them the statements belonging to the if expressions must be enclosed by curly brackets.
An if statement allows you to make a choice in program execution direction.
if - else statement
An if statement may have an optional else statement. The else statement executes the alternative
false condition. Curly brackets are also needed if more than one statement belongs to the else
statements.
if(condition) if (x==0)
{ T F
true statement(s) y = x; if(x==0)
x=x+1;
else }
else y = x;
x = x + y; x = 1;
false statement(s) x=1;
If - else statements may be nested. In this case the else belongs to the balanced if. In case of
confusion to determine which else belongs to which if use curly brackets.
if (condition) if (x == 2) if
{ {
true statement (s) if(x == y)
if (expression) y = 2; if
true statement(s) else
else y = x++;
false statement(s) } else
}
else
else
y = x; else
false statement(s)
T F
if(x==2)
T F
if(x==y)
y = x;
y = 2;
y = x++;
while loop
The while loop tests the condition at the top of the loop. If the expression is true the statement
inside the while loop is executed. When the while condition is false the program exits the loop. You
must be careful and make sure that the test condition is initialized before entering the loop. It is
beneficial to initialize your test condition right in the condition. The while statement allows you to
read items when you do not know how many items you have. If the test condition is false before
entering the loop the while loop statements will never get executed.
do while loop
The do while loop tests the condition at the bottom of the loop. The statements inside the loop are
executed at least once.
while ( condition ); {
System.out.println(i); i++
i++;
} while ( i < MaxSize) T
System.out.println ("I got:" + i + " items"); i < MaxSize
What is the difference between a while loop and a do while loop. When would you use a while
loop ? When would you use a do while loop ? A do while loop executes the loop statements at
least once, where a while loop may never execute the statements. You use a do while loop when
you want the loop to be executed at least once.
for statement
The for statement is used when you know how many items you have. For example to read a known
number of items from a file.
statement
System.out.println
("I got:" + i + " items"); i++ Increment
index
All expressions in the for statement are optional. When there are no expressions then would be an
infinite loop.
You can include more than 1 index in a for loop expression, by using the comma operator in each
expression. But you can only have 1 test condition.
break statements
The break statement lets you get out of a for, while or do statement. It lets you exit a loop before
it terminates.
continue statement
The continue statement is used with for, while, do to continue to the next iteration of a loop and to
skip statements that you do not want to evaluate for certain iterations.
int x = 0;
{
if ((i >= 3) && (i <= 4)) continue; /* skip for 3 and 4
x=x+i; /* this statement skipped of condition true */
System.out.println(i + " " );
} 0 1 2 5 6 7 8 9 10
What is the difference between a break statement and a continue statement ? The break
statement lets you exit the loop early and the continue statement lets you skip executing
statements in the loop.
For statements are usually nested. This means a loop inside a loop. Nested for statements are
handy in printing out the contents of a two-dimensional array. a.length gives you how many rows
you have and a[i].length gives you the number of columns for each row.
int [ ][ ]a = {{1,2,3},{4,5,6},{7,8,9}};
{ Inner Loop
/* inner loop for number of columns */
for(int j =0 ; j < a[i].length; j++)
The inner loop using the column index ( j ) prints out the contents of all the columns of the row
pointed to by the row index ( i )
columns
j i j
1 2 3 0 0, 1, 2
rows i 4 5 6 1 0, 1, 2
7 8 9 2 0, 1, 2
If you just want to print the diagonal of an array then you just print out the values of the array
element when i == j, when the row index equals the column index.
{
/* loop for number of columns */
for(int j=0; j < a[i].length; j++)
{
/* test if column equal row */
if(i == j)
/* print out rows and columns *
System.out.println(a[i][j] + " ");
else System.out.println( " ");
}
System.out.println();
}
j i j
1 0 0, 1, 2
i 5 1 0, 1, 2
9 2 0, 1, 2
i 5 1 0, 1, 2
7 2 0, 1, 2
if else-if
The if - else - if statements can be sequenced to choose a certain condition. If the if condition is
true the statements belonging to that if statement are executed. If the condition is false then next if
condition is evaluated If an if condition cannot be evaluated as true then program execution is
directed to the else statement.
T
if(expression) if(x == y)
x = 1; (x == y)
statement x=1;
F
else if(expression) else if(x < y)
T
x = 2; (x < y)
statement x = 2;
else else F
statement; x = 4;
x=4
switch statement
To avoid typing in many else-if statements then the switch statement is used. The switch
expression must be evaluated to a common Java data type, like char, int, float etc. The constant
expression must be a constant value and not a variable name. The break statements stops
the program execution from going to the next case. Without the break statements, you will get
unexpected results. Sometimes it is desirable to omit the case statements and breaks. By using
this technique you can test for multiple conditions.
switch( switch(x)
expression) {
case 0 :
{ {
case constant 1: System.out.println("first item is " + items[0] ) ;
statements break;
break; }
case 1:
case constant 2: case 2:
statements {
break; System.out.println("the items are: " + item[1] + " " + item[2]);
break;
case constant N:
}
statements
case 3:
break;
{
default: System.out.println("the third item is: " + item[3] + " " +
statements item[2]);
break; break;
} }
default: break;
}
In the switch statement code example why does case 1 not have any statements or break statement
? Because we want to trap for two conditions when x == 1 and x == 2,
} // end main
Program output:
I got 5 items
I got 6 items
11 12 13
21 22 23
31 32 33
11-----
--22---
-----33
You may need to share data between classes, like a table of values. You need to designated class to
access common data to all the other classes. The other classes can access this data through the
class methods. One class distributes data to all other classes. This class could be called data
manager. The other classes can access this class through a static method called getInstance() of the
DataManager class. There should only be one instance of a data manager class. The only way you
can do this is to make the constructor private (yes you can have private constructors) and have the
getInstance() method instantiate the class only once. Other tomes the getInstance() method is
called the method will return an reference to the object.
DataManager dm = DataManager.getInstance();
If you follow certain programming style conventions your programs will be easier to read. You will
instantly recognize variables and methods as being parameters or member variables etc.
All final variables should start with capital letters final int Num =
7;
LESSON 7 EXERCISE 1
Write a Java program using loops that print out the following triangle. Call your class and file
L7ex2.java.
*
**
***
****
*****
LESSON 7 EXERCISE 2
Write a Java program using loops that that print out the following Diamond. Call your class and file
L7ex2.java.
*
**
***
****
*****
****
***
**
*
LESSON 7 EXERCISE 3
Write a program that prints out the reverse diagonal of a 2-dimension array of 5 rows and 5
columns. Call your class and file L7ex3.java.
the classes pertaining to the Java language are in the package java.lang, this package is
automatically imported for you. Common use programming tools are in the java.util package. an
Example would be a random number generator class Random.
OBJECT CLASS
The Object class is the super class of all classes. All classes come from the Object class. This mean
the Object class has methods that all other classes can use. Some of these methods are:
method description
public boolean equals(Object obj) Indicates whether some other object is "equal to" this
one.
public final native Class getClass(); Returns the runtime class of an object.
public native int hashCode(); Returns a hash code value for the object.
The String class has a lot of uses for assigning strings, copying strings, joining strings etc. When
using the String class methods you always need to assign the result of the method to a String
reference. This is because a reference to a copy of the original String with changes is returned by
the method. This means you have to assign the results to another String reference or to itself. A
String object is said to be immutable meaning its contents cannot be changed. The String class is
located in java.lang.
char charAt(int index) getting a character of a string at index i char c = s1.charAt(0); // 'h'
String substring(int start) get substring of this string from start to s2 = s1.substring(3);
end of string // "lo"
String substring(int start, int end) get substring of this string from start to s2 = s1.substring(0,4);
end-1 // "hell"
boolean equals(String str) test if two strings have the same if( s1.equals(s2) ) // false
message (data contents)
boolean equalsIgnoreCase (String str) test if two strings have the same if( s1.equalsIgnoreCase(s2) )
message ignoring upper/lower case // false
int compareTo(String str) compares two strings less than < 0, if( s1.toCompare(s2) )
equal == 0 or greater > 0 // > 0
int indexOf(int ch) returns the index (position)of the first int index = s1.indexOf('l');
occurrence of the specified character // 2
int lastIndexOf(int ch) returns the index of the last occurrence int index = s1.lastIindexOf('l');
of the specified character // 3
String replace (char old, char new) returns a new String resulting from s1 = s1.replace ( 'h' , 'j' );
replacing all occurrences of the old // "jello"
character with the new character
String concat(String str) returns the concatenation of two strings s3=s1.concat(s2+" ");
(joins two strings together) //"helljello "
static String valueOf (type variable) converts a variable or constant into a String s4 = s1.valueOf(5);
string //"5"
LESSON 7 EXERCISE 4
Write a Java program to print out all the odd characters of a string and make them upper case and
the even characters lower case.
LESSON 7 EXERCISE 5
A string buffer lets you reserve extra memory for a string. By reserving additional space then we can
easily append characters to it. This results in faster execution time of your program.
h e l l o
Without the StringBuffer class your program will always have to get additional memory for your
string, when you join string together or other string operations. The StringBuffer class is said to be
mutable meaning you can change its contents directly. A conversion method converts a string
buffer to a String. The string buffer has the methods of the string class with same functionality:
length(), charAt() and getChar() and these additional ones:
StringBuffer (int length) constructs a string buffer with an initial StringBuffer sb = new StringBuffer(80);
capacity of 80 characters
StringBuffer (String str); constructs a string buffer of the String str StringBuffer sb = new StringBuffer(s);
StringBuffer append (String s) appends this string to the string buffer sb.append(s);
int capacity() returns current capacity of buffer string int capacity = sb.capacity();
char charAt(int index) Returns the character at a specific index char ch = sb.charAt(2);
void setLength(int n); set length of string discarding characters or '\0' sb.setLength(50);
padding
void setCharAt the character at the specified index is set to ch sb.setCharAt(2, 'x');
(int index, char ch)
String String makes a string pointing to buffer data contents String s = new String(sb);
(StringBuffer buffer);
LESSON 7 EXERCISE 6
Write a Java program to append 5 words with spaced and convert to a string and print to the screen.
Java has classes to convert char, integer, float and double primitive data type into objects. They
are called wrapper classes, because they enclose a primitive data type. For every primitive data type
there is a wrapper class. They are sometimes called big Char, Integer, Float or Double because of
the capital letter and they are class objects. We need wrapper classes for primitive data types char,
integer, float and double because they are not objects and we need to convert them to objects..
The wrapper classes are found in java.lang.* . Wrapper classes provide methods for doing
conversions from string to numeric values or vice versa. Each wrapper class has a static valueOf()
method to convert a String to a wrapper class. There is a wrapper class for every primitive data
type.
data conversion
The wrapper classes are most widely used to converting a String to a integer, float or double value.
Each wrapper class has a xxxValue() method to return a primitive data value from a wrapper object.
The Integer wrapper class has the static parseInt(String) method to convert a String to a int.
LESSON 7 EXERCISE 7
Write a class called MyInt that stores an int value. Make a constructor that accepts a int. You will
also need the following methods. Test each method in a main method. Hint: to convert a string to a
integer take each number in the string and multiply each by powers of 10 and sum up the results.
public static MyInt valueOf(String value) convert a string representing an integer value to a int.
return a MyInt object.
public static int parseInt(String value) convert a sting representing an integer value to a int, return a int
The Random class is located in java.util and is used to generate random numbers. Random number
generators are seeded with a numeric value, so that the same numbers are not the same when the
program runs every time. The seeded number is unique and is usually a numeric value representing
the time of day. When you create a Random object it is automatically seeded with the system time.
You must use the setSeed(int) method to set the seed .
Random() constructor, seeded to the current time of the computer Random r = new Random()
double nextDouble() returns the next random number between 0 and 1.0 double d = r.nextDouble();
int nextInt() returns the next random int number positive or negative int i = r.nextInt();
int nextInt(int max) returns the next random int number positive number int i = r.nextInt(100);
between 0 and max
double nextGaussian() returns the next gaussian distributed value with mean double g = r.nextGaussian()
0.0 and standard deviation 1.0 (bell curve)
void setSeed(long seed); sets the seed of this random number generator g.setSeed(1000);
LESSON 7 EXERCISE 8
Store 5 different word in an array. Generate 5 random numbers between 0 and 4 and print out the
words stored in the array indexed by the random numbers. You do not need any programming
loops., Use all sequential statements. Call your class L7ex8 and your program file L7ex8.java.
The math class located in java.lang supplies static methods for commonly used mathematical
operations.
LESSON 7 EXERCISE 9
Write a Java program using the Math class to find the maximum of 3 numbers, and the minimum of
the same 3 numbers. Find the power of the minimum and maximum numbers and the square root
of the power. Use the wrapper class to convert to primitive data types. Print out all the results. Call
your class L7ex9 and your program file L7ex9.java.
IMPORTANT
You should use all the material in all the lessons to do the questions and exercises. If you do not
know how to do something or have to use additional books or references to do the questions or
exercises, please let us know immediately. We want to have all the required information in our
lessons. By letting us know we can add the required information to the lessons. The lessons are
updated on a daily bases. We call our lessons the "living lessons". Please let us keep our lessons
alive.
E-Mail all typos, unclear test, and additional information required to:
courses@cstutoring.com
students@cstutoring.com
http://www.cscourses.com/java.htm
This lesson is copyright (C) 1998-2006 by The Computer Science Tutoring Center "cstutoring"
This document is not to be copied or reproduced in any form. For use of student only.
File: JGuideL8.doc
Stream I/O
Streams attach data to objects. Data flows in streams. An input data stream is needed to connect
data from the keyboard to your program. The connection to the keyboard is System.in. An output
data stream is needed to send data to from your program to the computer screen. The connection to
the screen is System.out. The System class is found in java.lang.* and is automatically imported
for you. The stream classes are found in java.io.*. You need to use the import java.io.*;
statement for your class when you want to use input/output stream classes.
output data
To send output to the screen you use the System class, which has a reference to a printStream
object out .
To put a message on the screen we use the methods in the PrintStream class. There are two
methods you can use to print data on the screen. System.out.println() prints out a message
ending with a new line after printing out the message and System.out.print() prints out a message
ending without a new line.
You can join (concatenate) other string or variables together by using the + operator:
hellotoday
You can also print out a variable value on the screen:
int x = 5;
To get a character or string message from the keyboard you first have to create a data input
stream. A data input stream makes a connection between the keyboard and your program. The
System class located in java.lang has a reference called in that is a reference to an object of the
InputStream class located in java.io. The input stream can only read a byte of data from the
keyboard using the int read() method. You need to create a DataInputStream object when you
want to read more than 1 byte. The DataInputStream class is now depreciated but can still be
used by people who have older versions of the JDK.
The DataInputStream object has many methods to get data from the keyboard. We can read a char
from the keyboard using the read() method and assign it to a char variable.
We can also read a message from the keyboard using the readLine() method and assign it to a
String:
The difference between read() and readLine() is that read() just reads 1 character 'A' from the
keyboard where readLine() reads a whole message line from the keyboard including white space.
"It is a cloudy day". The following example program reads a message from the keyboard and print
out the message to the screen. The throws IOException statement located in the main() method
will allow Java to report any input stream errors encountered while this program is running.
class L8p1
{
public static void main(String args[])throws IOException
{
// instantiate data input stream Program output:
DataInputStream din = new DataInputStream (System.in);
// Ask user to enter a message
System.out.println("please enter a message:"); please enter a message:
// read message from keyboard
String msg = din.readLine(); Hello there
// print message to screen
you have entered: Hello there
System.out.println("you have entered: " + msg);
}
A buffer stores keys from the InputStreamReader it in an allocated memory area called a buffer.
Your program will read characters from the buffer rather than directly from the device. This relieves
the input device from being accessed every time data is required from the program. All the data
required is stored in the buffer. Only when the buffer is full then your program will read all the data
from the buffer.
You need to set the buffer size to 1 to get the buffer to operate properly. The buffer does not release
the data until it is full. A BufferedReader needs an Input Stream (InputStreamReader) to connect
the keyboard (System.in) to the BufferedReader. By using the Buffer Reader this lets the user type
words faster than the program can read them.
The scanner class located in java.util.* makes it a little easier to read data from keyboard. To create
a Scanner object:
With the scanner object you can read strings, ints floats doubles etc.
note: you should always use sc.nextLine(); if you want to read data from the next line.
A buffered writer collects characters to be written to an output device Only when output buffer fills
up, then all the characters are written to the output device. This relieves the output device from
being assessed all the time. The buffer does not release the data until it is full. A BufferedWriter
needs an OutputStreamWriter to connect it to the screen (System.out). By using a Buffered Writer
this allows your program to write to the computer screen faster than it can display the data.
class L8p2
{
public static void main(String args[])throws IOException
{
// create a buffer reader
BufferedReader bin = new BufferedReader
(new InputStreamReader(System.in),1);
}
please enter a message:
Program output:
It is a cloudy day
LESSON 8 EXERCISE 1
Write a Java program to read 5 different words from the keyboard and store in a file. Read in the file
and print out the words to the screen. Call your program file L8ex2.java and your test file L8ex1.dat.
The StringTokenizer class is located in java.util and is used to separate a message into individual
words. Each word in the message is called a token and the space between the words is called a
delimiter. You can only use the string tokenizer class with strings.
delimiter tokens
(individual words)
The StringTokenizer object receives a message, which it separates into words. When you create a
StringTokenizer object you must specify which characters are delimiters. You may specify 1 delimiter
or multiple delimiters. The default delimiters are " \t\n\r". (space, tab, new line, carriage return).
The job of the StringTokenizer is to break up a message into individual words.
StringTokenizer message
(convert messages into words)
words
StringTokenizer (String str, String delim) str = input string delim = string containing delimiter characters
StringTokenizer (String str) str = input string default delimiters " \t\n\r" (tab,new line, carriage return, space)
String nextToken() returns next token, throws NoSuchElementException if there are no more tokens
String nextToken (String delim) returns next token, after switching to new delimiter
int countTokens() returns number of tokens in the string (how many tokens left)
Here is an example program to print out all words of a String message using String Tokenizer. Each
word in the string is a token. The string Tokenizer class will let access each individual word one by
one from the string.
{
// create a buffer reader
BufferedReader bin = new BufferedReader (new
InputStreamReader(System.in),1);
LESSON 8 EXERCISE 2
Write a program that asks the user to enter a message from the keyboard, and put into an array of
Strings. Create a BufferedReader to get data from the keyboard and use the readLine() method to
get a message from the keyboard. Use readLine() to get a whole line from the file and use
StringTokenizer to get individual words. Use System.out.println() to print the words to the screen
chosen randomly from the array. Call your program file L8ex2.java and your test file L8ex2.dat.
If you have java 1.5 then you can use the scanner class to separate a message into individual words
import java.io.*;
import java.util.*;
class L8p4
{
FILE CLASS
The file class basically a class that keeps tracks of file names but has nothing to do with opening
and closing files.
constructors
File(File, String) Creates a File instance that represents the file with the specified name in the specified directory.
File(String) Creates a File instance that represents the file whose pathname is the given path argument.
File(String, String) Creates a File instance whose pathname is the pathname of the specified directory, followed by
the separator character, followed by the name argument.
methods
canRead() Tests if the application can read from the specified file.
getAbsolutePath() Returns the absolute pathname of the file represented by this object.
getParent() Returns the parent part of the pathname of this File object, or null if the name has no parent
part.
isAbsolute() Tests if the file represented by this File object is an absolute pathname.
isFile() Tests if the file represented by this File object is a "normal" file.
lastModified() Returns the time that the file represented by this File object was last modified.
length() Returns the length of the file represented by this File object.
list() Returns a list of the files in the directory specified by this File object
list(FilenameFilter) Returns a list of the files in the directory specified by this File that satisfy the specified
filter.
mkdirs() Creates a directory whose pathname is specified by this File object, including any
necessary parent directories.
renameTo(File) Renames the file specified by this File object to have the pathname given by the File
argument.
The following program uses the File class to list all the files in the current directory. A name can
represent a file or a directory. Directories contain files.
symbol description
You can use the following
symbols to specify the .. up one directory
starting directory or use a
hardcoded path like . current directory
"c:\mydirectory"
\ root directory
class Lister
{
public Lister(File f)
{
System.out.println(f.getAbsolutePath());
list(f,0);
}
{
// get all files belonging to this directory
String contents[] = dirfile.list();
for(int i=0;i<contents.length;i++)
{
for(int spaces=0;spaces<depth;spaces++)
System.out.print(" ");
{
// current directory
File f = new File(".");
Lister list = new Lister(f)
}
LESSON 8 EXERCISE 3
Write a program that checks if a file exists and renames it. The user enters the name of the file and
the new file name. You can use command line arguments if you want. You can call your class
Rename and your program file Rename.java.
A file output stream sends data from to a file. The DataOutputStream now gets a FileOutputStream.
.The FileOutput Stream is a low level acces providing writing at the byte level the
DataOutputStream is high-level writing more than 1 byte.
To open and write to a file we instantiate a file output stream with a file name
To open and write to a file at the end of a file (append) we instantiate a file output stream with a
file name and set the append bit true. (there seem to be a bug when using append)
When you finished using a file for writing you have to close it.
LESSON 8 EXERCISE 4
Write a program that initializes and writes a double, float , int, short, char, byte and String to a file
to a file. Call your file L8ex4.dat. Call your class L8ex4 and program file L8ex4.java.
file writers
import java.io.*;
class FileWriterTest
{
public static void main(String[] arg)throws IOException
{
FileWriter fw = new FileWriter("test.dat");
fw.write("hello there\n");
fw.write("goodbye there\n");
fw.write("see you in a while crocidile\n");
fw.write("see you later aligator\n");
fw.close();
}
You can even have a buffered file output stream using the file writer to write to the file. The buffered
Writer collects a chunk of data then writes out all at once to minimize I/O overhead constantly
writing to the file.
It is easy make a BuffererdWriter using a FileWriter object to open a file for writing
import java.io.*;
class BufferedWriterTest
{
public static void main(String arg[])throws IOException
{
FileWriter fout = new FileWriter("test.dat");
BufferedWriter dout = new BufferedWriter(fout,1);
dout.write(s+"hello\n");
fout.close();
}
Print Writer
A Print Writer object uses the familiar print and println methods. A Print Writer object also needs a file
writer object.
A print writer object is easy to use, you should use it. Here is a sample program that uses a PrintWriter
to write a sentence to a file.
import java.io.*;
{
FileWriter fout = new FileWriter("test.dat");
PrintWriter pw = new PrintWriter(fout);
pw.println(s+"hello\n");
pw.close();
}
To open and read from a file we need a FileInputStream class instead of System.in. The
FileInputStream feeds a DataInputStream class. The FileInputStream is the low level reader at
the byte level where as the DataInputStream is the high level reader reading many bytes. The
DataInputStream class is now depreciated but can still be used by people who have older
versions of the JDK.
We instantiate a file input stream with the input file name. If the file cannot be found to open a
FileNotFoundException is thrown.
When you finished using a file for reading you have to close it.
LESSON 8 EXERCISE 5
Write a program that reads a double, float , int, short, char, byte and String from a file to a file.
Open your file L8ex5.dat from exercise 4. Read the values from the file and print to the screen. Call
your class L8ex5 and program file L8ex5.java.
file readers
There is also a LineNumberReader class that keeps track of the line number read.
Here is a test program using a FileReader that reads sentences from a file and displays the line
numbers.
import java.io.*;
class ReaderWriterTest
{
public static void main(String[] arg)throws IOException
{
FileReader fr = new FileReader("test.dat");
LineNumberReader lnr = new LineNumberReader(fr);
String s;
// test for null string means end of file
while((s = lnr.readLine()) != null)
System.out.println(lnr.getLineNumber() + ": " + s);
fr.close();
}
}
You can even have a buffered file input stream using the file reader to read from the file. The
BufferedReader collects a chunk of data from the file at once to minimize i/o overhead constantly
reading from the file.
FileReader
Program BufferedReader file
It is easy make a BufferedReader using a FileReader object to open a file for reading
import java.io.*;
class BufferedReaderTest
{
public static void main(String arg[])throws IOException
{
FileReader fin = new FileReader("test.dat");
BufferedReader din = new BufferedReader(fin,1);
String s = din.readLine();
System.out.println(s);
fin.close();
}
}
The following program reads a message from the keyboard and writes it to a file. We then close the
file and reopen the file to read the contents and display on the screen. The file is called test.dat.
{
// create a buffer reader
BufferedReader bin = new BufferedReader (new
InputStreamReader(System.in),1);
LESSON 8 EXERCISE 6
Write a program that asks the user to enter a message from the keyboard, store the message in a
file and prints out the sentences randomly. Create a BufferedReader and use the readLine()
method to get a message from the keyboard. Open up a text file for writing and write the messages
to the file using a FileWriter or BufferedWriter. Close the file and then reopen the file for reading.
Use a FileReader or BufferedReader to read a whole line from the file and store in an array of
Strings. Print out the sentences randomly from the array of Strings. Call your program file
L8ex6.java and your test file L8ex6.dat.
The Scanner class can also be used to read data from a file. The Scanner class needs a FileReader
object to open and read the file.
We have taken the above program and used Scanner and Print Writer objects.
import java.io.*;
import java.util.*;
Random access lets you access the file at any location. Random access is quite different from
sequential access where you get to read and write bytes sequentially one by one. You create a
Random object by giving the file name and access mode. the modes are "r" for read only and "rw"
for both reading and writing.
You use the void seek(long position) method to seek to any position. The file starts at position 0.
raf.seek(p*5);
The long length () method returns the length of the file in bytes.
Finally the long getFilePointer() method returns the current position within a file in bytes .
Here is a program that writes words to a file and then randomly reads then from the file and prints
them to the screen.
import java.io.*;
class RandomAccess
{
public static void main(String[] args)throws IOException
{
// open for read/write
RandomAccessFile raf = new RandomAccessFile("out.dat","rw");
String[] words = {"cat\n\r","dog\n\r","ate\n\r","run\n\r","cry\n\r"};
// write words to file
for(int i=0;i<5;i++) raf.writeBytes(words[i]);
// read back words at different locations
for(int i=0;i<10;i++)
{
long p = (long)(Math.random()*5); // get random number between 0 - 4
raf.seek(p*5);
String s = raf.readLine();
System.out.println(s);
}
}
}
LESSON 8 EXERCISE 7
Write words randomly to a file and then read back randomly using random lengths. Call your class
L8ex7 and your program file L8ex7.java.
SERILIZATION
Serialization lets you read and write objects to a file. The objects you using must implement the
Serializable interface located in java.io.*; failure to do so your Java program will throw an
NotSeriaizableException that the target object is not Serializable. To write an Object to a file you
first need to create an ObjectOutputStream using a FileOutputStream.
Next you create some objects like the Person object and write to the file using the
writeObject(Object obj) method
and then read the objects using the Object readObject() method
p3 = (Person)in.readObject();
Notice we have to type cast to a Person object. If you do not know what kind of object you have
then use Object.
Here is the test program to write a person object to a file and read them back. The
ClassNotFoundException is needed if the target object is not in the file.
import java.io.*;
import java.io.*;
LESSON 8 EXERCISE 8
Use one of your own classes and write and read back objects from a file. Call your class L8ex8 and
your program file L8ex8.java.
ADDITIONAL EXERCISES
You do not need to do them all. Just send in the first one.
LESSON 8 EXERCISE 9
Write a class called Num that receives numbers from the keyboard, stores them in an array, and
reorders (exchanges) them. The main method will call the class method get() to get single digit
numbers from the keyboard and the class method toString() to display the entered array elements
on the screen. When 5 numbers are entered the main program will ask the class to start exchanging
numbers by calling the class method reorder(). Exchange the last with the first, the second with the
second last etc. The main method will call the class method toString() to display the reordered array
elements on the screen. Your constructor should get the size of the array. Your class will have an
input function called get(), a process function called reorder() and a output function called
toString(). All variables must be private. Put your class in a file called Num.java If you are using an
IDE call your project L8ex9.
class Numbers
LESSON 8 EXERCISE 10
Continue from Exercise 1. Have the reorder method also keep track of the smallest number and the
largest number in the array. Make two variables in the class min and max and methods to get their
values. The main method will work the same as before Print out the reordered array along with the
min and max values. Call your program L8ex10.java.
LESSON 8 EXERCISE 11
Include in your class Num a method to add up all the elements in the array and print the result. Call
your program L8ex11.java. As before the main method will ask the user to enter array values from
the keyboard. Print out the input array and the sum of all the elements.
LESSON 8 EXERCISE 12
Include in your class Num a method add to add two arrays together into a third array. Call your
program L8ex12.java. As before the main method will Ask the user to enter array values from the
keyboard. Print out each input arrays and the final result. Print out the contents of the third array.
Hint: the add method will have two input parameters that are Num class objects.
LESSON 8 EXERCISE 13
Write a class called Num2 to handle two-dimensional arrays. You need a print method and a mul()
method to multiply two 3*3 two-dimensional arrays into a third array. Call your program
L8ex13.java. As before the main method will ask the user to enter array values from the keyboard.
Print out each input array and the final result.
LESSON 8 EXERCISE 14
Write a program that takes a two dimensional array lets say 5 * 5 and rotates each element by the
amount a user enters on the keyboard. If the user enters a positive number 2 all the elements in the
array will shift right by 2. If they entered a negative number all the elements in the array will shift
left. Print out the array before and after rotation. Call your program L8ex14.java.
LESSON 8 EXERCISE 15
Ask the user to enter in the keyboard how many characters they want on a output line. Ask the user
to enter many lines from the keyboard or read text lines from a file. Produce an output on the
screen where all the lines are a fixed width where the left and right margins are justified. Hint: use
an output buffer to format the lines first before printing. Call your program L8ex15.java. Example
the above lines would appear as follows or a line width of 28 characters:
LESSON 8 EXERCISE 16
Write a program that removes all the comments from a Java program. file Your program should be
able to handle nested comments. "Comments inside comments". Report any comments that do not
end and nested comments that are unbalanced. Write the results to another file. An example-input
file would be:
/* lesson 8 program 16 */
import java.util.*;
{
Random r = new Random(); // make a random number generator
import java.util.*;
class L8p9
{
public static void main(String[] args)
{
Random r = new Random();
System.out.println((r.nextDouble() * 100);
LESSON 8 EXERCISE 17
Write a program that prints out the transpose of a matrix. Call your class and program file
L8ex16.java. For example. Call your program L8ex17.java.
1 2 3 1 4
4 5 6 2 5
3 6
LESSON 8 EXERCISE 18
Write a Java program that print out a triangle. The user of your program will specify the width of the
base of the triangle. Call your program L8ex18.java.
*
**
***
****
*****
LESSON 8 EXERCISE 19
Write a Java program that print out a Diamond. The user of your program will specify the maximum
width of the diamond. Call your program L8ex19.java.
*
**
***
****
*****
****
***
**
*
LESSON 8 EXERCISE 20
Write a Java program that calculates a magic square. In a magic square the elements of each row
and column add up to the same value. The user will enter the size of the square, the square is
always odd. The steps to making a magic square as follows:
(1) set k to 1 and insert into the middle of the top upper line
(4) move down one square from the last position and insert k.
A multiple of n squares will be 3 6 9 for a 3 * 2 square. If you go left and you are at the start of a
column you have to wrap around to the last column. If you are the bottom of the row and you have
to move down one row then you wra0p around to the first row. Call your class and file L8ex20.java.
LESSON 8 EXERCISE 21
Writ a program that take any number and outputs it into words For example the number 123 will be
converted into one hundred and twenty three. Call your class and file L8ex21.java.
LESSON 8 EXERCISE 22
Write a program that takes a numeric string like $+-12,564.56 and checks it for validity and correct
it if certain elements are missing. Your program should output "INVALID" if the string is invalid and
cannot be corrected, else the corrected output string. If a decimal point is missing it will insert the
decimal point and two zeros. If there is only one digit after the decimal point it will insert the extra
digits. There should be a comma before every three digits, if the comma is missing then your
program should insert it. Right justify your output. Call your class and file L8ex22.java.
LESSON 8 EXERCISE 23
Write a program that asks the user to type in 10 numbers into an array. Your program should scan
the array and look for numbers that repeat. Your program will report the number of the largest
group of repeating numbers. The repeating numbers may be anywhere in the array and do not need
to be sequential. If there are no numbers that repeat then return the largest number found in the
array. Call your class and your file L8ex23.java.
LESSON 8 EXERCISE 24
Write a program that prints out the reverse diagonal of a 2-dimension array of 5 rows and 5
columns. Call your class and file L8ex24.java.
IMPORTANT
You should use all the material in all the lessons to do the questions and exercises. If you do not
know how to do something or have to use additional books or references to do the questions or
exercises, please let us know immediately. We want to have all the required information in our
lessons. By letting us know we can add the required information to the lessons. The lessons are
updated on a daily bases. We call our lessons the "living lessons". Please let us keep our lessons
alive.
E-Mail all typos, unclear test, and additional information required to:
courses@cstutoring.com
students@cstutoring.com
http://www.cscourses.com/java.htm
This lesson is copyright (C) 1998-2006 by The Computer Science Tutoring Center "cstutoring"
This document is not to be copied or reproduced in any form. For use of student only.
File: JavaL9.doc
The Object Oriented Programming approach allows a program to be more organized. Methods
having a specific task can be grouped together in a class. Methods in a class share all variables
defined in the class. A class is like a factory, a car assembly plant, a furniture plant etc. Each factory
performs a specific operation. Since there are different kinds of factories with certain operations then
there must be different kinds of classes with certain operations. Each factory has different
departments to do specific tasks so that the factory can operate efficiently. Classes must also have
different methods to do specific tasks so that the class can operate efficiently. A factory must get
some raw materials, do some manufacturing process and then deliver a finished product like a car or
a washing machine. A class must get data from the keyboard or a input file, must process the data
by doing a calculation and deliver the output on a screen or store the output data in a file for future
use. A class receives data through set methods (also called mutator methods), does a calculation
by using process methods and delivers the output result through the get methods (also called
accessor methods). The input values will be stored internally in the class in the private variables.
Private meaning no one else can use these variables, only the class that defined them. Think that
the private variables are the inventory parts in the storeroom of a vehicle assembly plant. If they
were made public then any one could just walk in and take them and then after a couple of days
the stock department will be empty. The factory could not make any more vehicles and the plant
would shut down. Private variables make good sense. If they were public other classes could use
them and maybe corrupt the data. In this case the program will crash and the computer will shut
down. We need set and get methods to access private variables belonging to the class. This
technique is known as encapsulation or hiding data from the outside world. The advantage of this
method is that the people accessing this data do not need to know how the data is stored internally,
what database they are using, what data structure they are using. They just want to get the data!!!
The class will handle the entire overhead in managing the data. This takes the burden away from the
programmer. Think that the communication between classes is roads and the data is the raw
material being delivered to the factory by the delivery trucks. The delivery trucks bring the raw
material (the data), to the receiving department (the set methods). The factory manufactures the
products (the process methods) using all the resources of the factory the variables defined in the
class. When the product is ready for delivery the pickup trucks pick up the finished goods (the data)
from the shipping department (the get methods) and deliver the product to the outside world.
class model
Data from outside world --> Set Methods put data into private variables
(mutator)
The input methods are also called mutator method because the data in the object will be changed.
The output methods are also called accessor methods because data is being accessed from the
object. Always think of a class as a factory with specific operations to do. If you have many different
things to do then you would need many different classes. By having many different classes, each
performing a specific dedicated operation, your program will be highly organized and more efficient.
There is always a reference to the object being accessed and is called this. The compiler creates it
and you can use it to refer to the variables and methods of the object that is currently being
accessed. A class defines the variables and methods an object will need. The variables are usually
defined first. Many objects are made from the same class definitions. A Java program will have many
different classes each dedicated to a specific task. The methods defined in the class help the class do
its task by doing operations on the data. A class is defined by a visibility, name, variables,
constructors and methods:
class
definition Objects are
created from a
class definition
object object
object object
PERSON CLASS
We will now present an example class the Person class. The Person class keeps track of the persons
name, address and age.
constructors
Java allows you to initialize private variables when they are declared in the class definition. You
should always initialize private variables to default values like 0 or null when declaring them in your
class. Constructors are used to initialize private variables to their operating values and to create
other objects. Constructors have the same name as the class. You can have many constructors, each
serving a different purpose. Constructors may have many input parameters or no input parameters.
Constructors with no input parameters are known as default constructors. Default constructors
set the private variables of the class to default values. Default constructors are not used too much in
Java because the variables belonging to the class can be initialized to a default value when they are
declared. We are not using default constructors.
{
name = ""; // person's name
status = "operating"; // persons address
age = 0; // person's age
}
Constructors with one or more input parameter are known as initializing constructors. Initializing
constructors are used to initialize private variables of the class to user specified values.
{
this.name = name; // person's name
this.address = address; // person's address
this.age=age; // person's age
}
Conversion constructors may be needed to convert one data format into another data format. For
example time can be represented by a string "8:30pm" or as a number 2030. If the class store's
time as a number, you will need a conversion constructor to convert time in a string representation
to time in a numeric format. We supply the age in a string format and must convert to an integer.
Copy constructors are used to copy an existing object. The parameter of the copy constructor gets
a reference to another Student object. The values of the variables of one object are copied to the
object you are creating.
instantiating classes
When you instantiate a class it becomes an object. Instantiating happens when the new operator is
used to allocate memory for the object. The constructors are called to initialize the variables in the
object.
methods
Methods are needed to send, receive and do operations on the data belonging to the object. The
variables of a class are private so we need methods to access the data. The Person class has
methods to receive data, send data and do calculations on the data. You call a method by using the
instance name, the dot operator and the method name. For example to call the getName() method:
// Person.java
import java.io.*;
{
private String name; // persons name
private String address; // persons address
private int age; // persons age
{
name = ""; // person's name
status = "operating"; // persons address
age = 0; // person's age
}
{
this.name = name; // person's name
this.address = address; // person's address
this.age=age; // person's age
}
{
String s = " name: " + name + "\n";
s += "address: " + status + "\n";
s += "age: " + age + "\n";
return s;
}
MAIN METHOD
The first method to be executed in a Java program is the main method. The main method wills
instantiate Person Objects. In Java each class may have its own main method, so that each class can
be tested separately. Its up to the programmer to remember which main method will start the whole
Java program. The running class that has the main method usually has visibility public. The main
method is static because it is needed to run the program right away. The main method instantiates
Person objects. Here is a main method for the Person class:
// main method
void static main (String args[ ]) throws IOException
{
Person p1 = new Person("Tom","121 College Street",25);
System.out.println("p1);
p1.incAge();
System.out.println("p1);
}
LESSON 9 EXERCISE 1
Type in the Person class. In the main method make many Person Objects. Use the default,
initializing, conversion and copy constructors. Use all the methods.
LESSON 9 EXERCISE 2
Make a student class that has a name and id and mark. Make constructors to initialize the variables
defined in the class and make methods to get and set name and mark. Don't forget to make a
toString() method.
Student name
id
marks
In the Student class make an array of marks (max 4 marks). Make a variable to hold the average
mark. Make a method to set a mark: setMark(double mark, int index) by supplying a mark and a
index to the mark array. Make a method to get a mark: double getMark(int index) by supplying a
index to the mark array. Make a method to calculate the average from the marks stored in the
array. double calcAvg(); Update the toString() method to print out the marks and the average
mark. In your main method test your student class by making student objects and using the
setMark() method to set the marks. Printing out all the student objects created.
Now you need to make a Mark class for the Student class. What things would a Mark class need ? It
would need a of course a mark and a course.
id course
mark
The mark class just needs a constructor to initialize the mark and the course and methods to get
mark and course name. After you have finished writing the Mark class you will need to replace the
double mark array in the Student class with the Mark class.
before after
You will also need a setMark() method to create Mark objects and receive a course name as well as
a mark. When you add marks you now need to make a new Mark object.
return sum/numMarks;
}
Don't forget to have a toString method to print out all the entered marks and average.
String ID
String name double mark
Mark marks[] String course
int numMarks;
student(String id,String name, int name); Mark (double mark, int index);
String getId(); double getMark(int index);
String getName(); String getCourse();
double getMark(int index); String toString();
void setMark(double mark, int index);
double calcAvg();
Sting toString();
LESSON 9 EXERCISE 3
Update the setMark() and calcAvg() and toString() methods of the Student class. Create a student
and mark object and then use the setMark() method to add the mark object to the student class.
Make a few students with mark objects and then print out the results.
course class
The next thing you should do is making a Course class. The course class will have a name,
description and a course number.
name
Course class:
description
number
LESSON 9 EXERCISE 4
Code the Course class make a constructor and a toString() method. In the Mark class replace the
String course with your class Course. you will now have Course course; rather than Sting course;
In the main method of the Student class you first need to create some Course objects like Course c1
= new Course("History", "Introduction to History","HIS101"). When you make add a mark to a
Student you need to include the course object for example:
s1.setMark(56,c1);
student(String id,String name, int name); Mark (double mark, int index); Course (String name, String
String getId(); double getMark(int index); description, String number);
String getName(); String getCourse(); String toString();
double getMark(int index); String toString();
void setMark(double mark, int index);
double calcAvg();
LESSON 9 EXERCISE 5
Sting toString();
When you start to get a lot of classes you need to make a driver class. The driver class is
responsible to create all the required objects. The Driver class usually is called the Manager class or
the enclosing object.. In the student example our driver class could be called School. The School
class will be responsible to create student objects, create course objects and mark objects to set the
marks for each student, calculate the average marks and report the results. Write the School class.
The School class will just have a main method that instantiated The School class will be responsible
to create student objects, create course objects and mark objects to set the marks for each student,
calculate the average marks and report the result's. Your object model would now be like this:
School Class
main()
INHERITANCE
Classes have the ability to use methods and variables from another class. The derived sub classes
inherit variables and methods from a super class. This means a class called the derived sub class
can use variables and methods of another class the super class. It's like the subsidiary store using
the sales clerks from the main office to help out at rush hour. The super class supplies methods and
variables to the derived sub class. In programming the goal is to avoid repetition. Not only is a long
repetitious program difficult to follow but it also avoids a lot of typing. Inheritance comes to the
rescue. We may have many types of Persons, Students, Employees, HomeMakers etc. What do they
all have in common ? A name, address and an age. The Person class is the super class having the
common things the Student class is the sub class having unique things like an Student ID.
The sub class may use the methods and variables of the super class. The sub class is derived from
the super Person class. The Student classes are all derived from the super Person class. Every time
you derive a Student from a PAERSON class a Person object is also created, because the Student
class needs the methods and data of the Person super class! When you create another Student
object you automatically get another Person object. What gives ??? The popular misconception of
inheritance is that only one super class is created, but in reality for every sub class derived, another
super class is also created. Inheritance was design to avoid repetition. All inheritance is saying is to
create additional sub classes that use common elements of a super class. Put all the common
elements in one class called the super class. Each derive sub class needs a separate copy of the
variables of the super class., or else each sub class will have the same values located in the super
class. Inheritance does not mean I want I only want one copy of a super class and many sub
classes. The super class contains the common variables and methods needed by the sub class. The
programmer now has to its disposal, the methods of the sub class and the methods of the super
class. Without the super class the programmer would have to type in the same methods and
variables every time he creates a Student class. Repetition is avoided because you may need
additional classes like Employee, homemaker etc. With a common student super class adding a
Employee class is a piece of cake. You just derived more sub classes from the super class.
To derive a class from another class we use the extends keyword in the class definition. You may
only derive a class from one super class.
class Student extends Person // derive a Student class from super Person class
{
String id;
}
The methods of the super class must have visibility public or protected to be accessed by the sub
class. Each sub class has its own super class. Compilers share the methods of the super class to all
derived sub classes to avoid duplication of code. The data variables in the super class cannot be
shared between derived sub classes. Each sub class needs its own copy of the super class private
variables. If not each sub class will have the same values, inherited from the super class, which is
what we don't want. Inheritance allows the derived sub classes to access the methods and data of
the super Person class directly.
The derived sub class constructor must call the super class constructor to initialize variables of the
super class. Failure to do so may cause your program to stop. You will get incorrect values or null
pointer exceptions when you try to access variables located in the super class. Constructors are not
inherited from the super class and must be supplied if needed in the sub class. You call the super
class constructor by using the keyword super( ). The keyword super always refers to the super
class. If the super class and derived class have default constructors then the super class is called
with no arguments.
// default constructor
Student()
{
super(); // call super class constructor
this.id = id; // initialize student id
}
If the super class constructor requires arguments then you must pass the derived sub class
parameters as arguments to the super class constructor call. The variables of the super class must
be initialized.
{
// initialize super class with parameters from sub class
super(name, address, age);
this.id = id; // initialize student id
}
For the copy constructor you pass the sub object reference to the super class.
Student(Student s2)
{
super(s2); // pass to super class
You intantiate sub classes just the way you instantate any class.
Once you get your sub class instantiated you can now call methods of the super class or derived
class. The variables and methods of the super class must be public, protected or friendly for the
derived sub class to access them. The derived sub class cannot access private variables and
methods of the super class.
sub_class_object_reference.super_class_method(optional_argument_ list);
accssibility
The following chart indicated what access modifier is needed so that the sub class can access
methods of the super class. You interpret the chart as follows: If the method of the super class is
public then a such class or class in the same package or not in the sane package can override the
methods of the super class. The rest is quite obvious.
Legend: SC = sub class, NSC = not sub class, P = package, NP = Not Package
P X X P X X P X X P
NP X X NP X NP NP
Inheritance works only one way. This means if you intantiate a Student object, then this object can
only access variables and methods of the Student class, it knows nothing about the derived sub
classes. It can not access variables and methods of a derived sub class, because it does not know
anything about the derived sub classes.
If the derived class has methods of the same name and same type parameter list, the derived
class will override method of the super class. Do not confuse override with overloaded.
Overloaded means methods with same name but different parameter data types. Override
means methods in the derived sub class that have same name and same parameter data types
and order as methods in the super class. The derived methods will be called instead of the super
class methods. Variables defined in the super class cannot be overridden by variables of the sub
class.
A sub class method cannot override a super class method that has a lower access visibility than the
sub class method. This means a private sub class method cannot override a protected super class
method.
public public
If the derived class needs to call methods of super class then the derived class must use the super
keyword to call the method of the super class. The derived sub class may call same name methods
of the super class by using the super keyword and dot "." operator and the method name. It calls
the same name method of the super class rather than its own
Using overriding and calling methods of the super class the Student derived sub class can print out
unique information like Student ID. Then Student can call the super class to print out all the
common information like the name, address and age.
Student class
The methods in the super and derived sub class are public so that other people can use them. We
now present the Student derived sub class. Notice we just have a few lines of code. The Student
class uses variables and methods of the super Person class.
// student.java
{
String id; // students id
// initialize vehicle plant variables
public Student(String name, String address, int age, String id)
{
super(name,address,age); // send parameters to super class
this.id = id; // initialize student id
}
{
super(s2); // pass to super class
}
// return id
public String getId()
{
return id;
}
{
String s = "\n" + "id: " + id + "\n";
s += super.toString(); // get super class info
return s;
}
Overloading is when a class has the same function name but each function has a different
parameter list. Overriding is when the derived class function has the same name and same
parameter list as the base super class method. If the base class contains overloaded methods that
are overridden in the derived class the compiler will automatic choose the base methods that are not
overridden but overloaded. For example the following base class has 2 overloaded methods but the
derived class just overrides one of them. The program knows which one to call.
// base class
class Base
{
public int square(int x)
{
System.out.println("base int" );
return x*x;
}
{
System.out.println( "base double" ); Program Output:
return x*x;
}
}
base int
the square of 5 is: 25
// derived class derived double
class Derived extends Base the square of 5.5 is: 30.25
{
public double square(double x)
{
System.out.println( "derived double" );
return x*x;
}
{
Derived d = new Derived();
System.out.println( "the square of 5 is: " + d.square(5) ); // call base int
System.out.println( "the square of 5.5 is: " + d.square(5.5) ); // call double
}
CALLING DERIVED SUB CLASS METHODS AND VARIABLES FROM THE SUPER CLASS
We can use the instanceof operator to safely call derived function from the base super class. When
a base super class method calls a overridden method it will calls the base super class method if the
calling object is a base super class object or else will call the derived sub class method if its a
derived class object. Variables cannot be overridden. If the derived sub class variable has the same
name as a base super class. Then the base super variable will be called in the super class and the
derived sub variable will be called in the derived sub class. the If the base class wants to call a
method from the derived class and this function is only in the derived class then the calling object
must be tested if its a derived object before the derived class method is called. If you do not test
then your program would generate a CastClassException. This is easily handled using the instanceof
operator.
((DerivedClass)this).derivedMethod();
Notice we typecast this to the DerivedClass before calling the derivedMethod(). We can also access
a derived sub class variable from the base super class using this approach. The following program
demonstrates the base super class calling overridden base super class methods or overridden
derived sub class methods. We also demonstrate the base super class only calling methods
belonging to the derived sub class. Variables cannot be overridden and are called from the class they
are in. Here is a summery of the possible scenarios:
situation action
1 if super class object super class calls overridden method of the super class
2 if sub class object super class calls overridden method of the sub class
3 if non-derived method super class calls method and variables of sub class provided we typecast
{
((Cat)this).derivedMethod(); // call sub method
System.out.println(((Cat)this).name); // call sub variable
}
{ I am a Animal
Animal a = new Animal(); // create an animal object I am a Animal
a.baseMethod(); // call base function I am a Animal
Animal c = new Cat(); // create a cat object
I am a cat
c.baseMethod(); // call base function
}
I am a cat
I am a cat
}
IMPORTANT
You should use all the material in all the lessons to do the questions and exercises. If you do not
know how to do something or have to use additional books or references to do the questions or
exercises please let us know immediately. We want to have all the required information in our
lessons. By letting us know we can add the required information to the lessons. The lessons are
updated on a daily bases. We call our lessons the "living lessons". Please let us keep our lessons
alive.
E-Mail all typos, unclear test, and additional information required to:
courses@cstutoring.com
students@cstutoring.com
www.cscourses.com/java.htm
This lesson is copyright (C) 1998-2006 by The Computer Science Tutoring Center "cstutoring"
This document is not to be copied or reproduced in any form. For use of student only.
File: JavaL10.doc
Status: proof
LESSON 10 POLYMORPHISM
Person
Students
History Math
Geography Science
The History, Geography, Science and Math students all derived from the Student class. They know
nothing about the Person class. The only class that knows anything about the Person class is the
Student class.
LESSON 10 EXERCISE 1
Write sub classes History, Geography, Science and Math for your Student class. Instantiate many
different types of students.
The next thing you need to do is to thing about was is unique about your sub classes. You may want
to adjust the marks for each student. Each student gets a mark. The mark is common to all students
so the mark will be located in the Student class. How you adjust the mark is unique for each
student.
LESSON 10 EXERCISE 2
Make a function adjust() for the Student class from last lesson. Each sub classes History,
Geography, Science and Math class will get a adjust method. The adjust method will adjust all the
marks for the different categories of students. You need to make some criteria's to decide how to
adjust the marks. In can be based on the average mark of all the students' foe particular course.
Each sub class needs a static average mark variable. If the average mark is below 60 % all marks
are raised 10 %. If the average mark is above 90% all marks are lowered by 5 %. Also only certain
marks can be adjusted foe certain course. You decide your are the boss here.
Student
adjust()
History Math
adjust() adjust()
Geography
Science
adjust() adjust()
Implementing Polymorphism
When you have many derived sub objects a program must keep track of which sub object to call.
Normally this would be accomplished by many if-else-if statements or switch case constructs.
Wouldn't it be nice if someone could do it for you automatically? Yes there is and the concept is
known as polymorphism and it is done transparently to the programmer. To implement
polymorphism an array of super object references is needed. In the main method of a Driver class.
We make an array of Student objects references.
Student reference
Your program must keep track of the number of Student objects in the array. Initially the number of
Student objects in the array is set to zero.
The length of the Array object can be used to tell us the maximum number of Student objects.
The next thing you have to do is to fill the table with derived objects History, Geography, Science
and Math,. This is easy!!! Since we have a table of vehicle class object references then all we have
to do is fill the table with references to each derived sub class we instantiate.
Notice when we create a car History object but the array object type is a Student object. This is
what polymorphism is all about a super class object reference representing a sub class object.
When we use the super class object reference, it transforms itself into a sub class object. Just as the
caterpillar transforms itself into a butterfly. We now have an array of Student object references
referring to derived sub class objects.
The Java program at run time keep tracks of which Student reference refers to a History,
Geography, Science or Math object not the programmer. It is important that the super class and
derived sub class methods have the same name and same number of parameters with same object
types. If they are different then polymorphism will not work. For polymorphism to work the derived
sub class must override the methods of the super class. If the derived sub class overrides a
super class method, then super class method is not called. The super class method may not ever be
used. Unfortunately even if the method of the super class is not used it still has to be present in the
super class. This can be annoying especially if the method is to return a data or object type.
Student
Student Student
History
v History
c v
upward conversions
When a base class reference refers to a super class this is known as a upward conversion very
similar in how a double represents a int in a widening conversion. A reference to a super class
can only access the variables and methods of the super class only.
double
widening int x = 5;
conversion.
double d = x; int
Student
Once the base class reference represent a sub class you need to type cast to get the sub class from
the super class reference. The compiler only knows the super class reference is suppose to represent
a super class. The compiler only compares the object types of the variables not the objects they
are representing. Each object in memory is marked to know which class its belongs to.
When you extract the sub class object from the super class reference thus is known as a downward
conversion. This is similar to having an int represent a double a narrowing conversion. A
reference to a sub class can access the variables and method of the sub class and the super class.
int
Student
downward conversion Student s = new History();
s
History h = (History) s;
h History
using polymorphism
Okay, its time to adjust the marks of the students objects in the array of student references. All we
have to do is the following, is to go through the table and call the derived sub class methods to do
all the work for us.
{
Students student = students[i]; // get a reference to the student
student.raise(); // call adjust() method for each student in array
}
A reference to each student object is stored in the array of student object references. With
polymorphism the program knows which student is a History, Geography, Science or Math student
and who to adjust the marks for. Polymorphism automatically selects which derived sub class
method to call. It's like a selector switch.
History object
Array of
Geography object
Student
references Science object
Math object
LESSON 10 EXERCISE 2
Make a Driver class called School that just has a main method. In your School driver class make's an
array of Student object. Instantiate many different types of students with different courses. Then
Call the adjust methods for all he students in the array. Print our the marks before and after.
When we do not need to write code for an overridden super class method you can make it abstract
meaning a method that has no code. The method starts with the keyword abstract has no body and
ends with a semi colon. We can make the adjust() method of the Student class abstract because we
do not have any code to write for it. The code will be implemented in the derived sub classes.
Once your class has an abstract method you need to declare the class as abstract too:
Abstract class cannot be instantiated because some of the methods are incomplete. When using
abstract class you are forced to instantiate the derived sub classes only.
LESSON 10 EXERCISE 3
In the student class change your adjust method to an abstract method. Change your Student class
to an abstract class.
employees
The vehicle plant class and derived sub classes are not strong examples of polymorphism, because
of the similarities between cars, trucks and buses. It is some times of a challenge to find unique
things about derived sub classes. An easier example to visualize polymorphism is a collection of
employees and how we give each employee a raise. We will have Secretaries, Managers, Workers
and Sales people each getting a different raise and bonus. Each class has a raise method that
calculates a raise differently.
Employees
raise()
base 10 %
Secretaries
Sales
raise()
Managers Workers raise()
0%
raise() raise() commission
5% 2%
// secretaries
class Secretary extends Employee
{
Secretary(String name, String address,double salary)
{
super(name, address, salary);
void raise() {}
}
// managers
class Manager: public Employee
{
Manager(String name, String address,double salary)
{
super(name, address, salary);}
void raise()
{
salary = salary + salary * .05;
}
}
// workers
class Worker : public Employee
{
Worker(String name, String address, double salary)
{
super(name, address, salary);
double raise()
{
salary = salary + salary * .02;
}
}
// salesman
class Salesman : public Employee
{
private double commission;
public Salesman(String name, String address, double salary, double commission)
{
super(name, address, salary);
this->commission=commission;
}
public double raise()
{
salary = salary + commission;
}
}
We can calculate the raise for all employees assuming we have an array of employee objects as
follows:
for(int i=0;i<NumEmployees;i++)
{
Employee* emp = employee[i];
emp->raise();
}
It's easy to see how polymorphism will work here. The base method raise() will calculate a basic
raise for all the employees. Let's say it will be 10 % of each employee's wages. The derived sub
classes will calculate additional bonus raises. Secretaries get zero raise, Managers get 5 % extra,
Workers get 2 % and Sales people depends on their yearly sales. This is an excellent example using
polymorphism. This example is more easily understood and apply because of the apparent
uniqueness of each sub class. Again we will have an array of Employees. Each entry will be a
Secretary, Manager Worker or Sales employee. To calculate a raise for each employee we call each
drive sub class. Each derived sub class will call its own raise() method.
residential properties
Another example is taxes on Residential properties. Taxes are calculated from the value of a
dwelling. Houses pay the most tax, and levied at 15 %, Condominiums pay a smaller tax, levied at
10 % , Rentals don't pay any tax. Again polymorphism comes to the rescue. It figures out how to
calculate taxes from the array of dwellings transparently to the programmer.. Each class has a raise
method that calculates taxes differently.
Dwellings
taxes()
base 0%
Homes
taxes() Rental
15% taxes()
Condominiums
taxes() 0%
10%
rental company
A last example is a rental company, they rent cars and trucks. Cars at a fixed day rate and trucks by
a day and mileage rate They rent cars at $24.95 per day with unlimited mileage. They rent trucks
at $19.95 per day plus 10 cents per mile. You need to keep track of the days and mileage for each
rental. Again polymorphism comes to the rescue. It figures out how to calculate the price of each
rental transparently to the programmer.
Rental
price
Cars
$24.95 per day Trucks
unlimited $19.95 per day
10 cents per mile
LESSON 10 EXERCISE 4
Write the code for the rental company. You need a Rental super class and two derived sub classes
RentCar and RentTruck. Keep things simple. Make a driver class that keeps track of all rentals in an
array. The main function of the Driver class will rent some cars and trucks with number of days and
mileage and then print out the costs.
bank account
The classic example is the bank account customer having a savings and a checking account. There
will be overridden methods for withdraws each account may have a different overdraft , interest
calculation, monthly fees etc. There will be common methods for customer, deposits etc.
Bank Account
Customer
IMPORTANT
You should use all the material in all the lessons to do the questions and exercises. If you do not
know how to do something or have to use additional books or references to do the questions or
exercises please let us know immediately. We want to have all the required information in our
lessons. By letting us know we can add the required information to the lessons. The lessons are
updated on a daily bases. We call our lessons the "living lessons". Please let us keep our lessons
alive.
E-Mail all typos, unclear test, and additional information required to:
courses@cstutoring.com
students@cstutoring.com
www.cscourses.com/java.htm
This lesson is copyright (C) 1998-2006 by The Computer Science Tutoring Center "cstutoring"
This document is not to be copied or reproduced in any form. For use of student only.
File: JavaL11.doc
uses "use a" When one class uses another class it uses variables and methods of that
class
containment "has a" Objects of one class contain objects of another class.
inheritance "is a" If a class extends another class, the derived sub class inherits methods
from the super class.
Class A
uses Class B
Class B
class A
Class A has a class B super class
Class B
class B sub derived
class is a derived from
class A
A cat "is a" animal that "has a" sound and "uses a" litter box.
Cat inherits Animal, the Cat object creates a Sound object and the Cat object uses a Litter Box
object. The difference between "has a" and "uses a" is that the "has a" relationship creates the
object and the "uses a" relationship uses an existing object created some where else. W e make the
Animal class abstract because we want the code for the peas() and speaks() methods to be written
in the derived sub class. We still need the Animal class because we want a class for common
variables like sound and any additional common methods. An abstract class is a class that has
abstract methods (methods with no code). Abstract classes still can have variables and other
methods with complete code. Abstract classes cannot be instantiated, because they have methods
that are incomplete.
// Lesson 11 program 1
}
program output:
// driver class
class L10p1
{ meow
public static void main(String args[])
{ the litter box is now full
Litter litterBox = new Litter();
Cat c1 = new Cat(litterBox); please empty the litter box
c1.speaks();
c1.peas(); the litter box is now empty
c1.peas();
litterBox.empty();
}
LESSON 11 EXERCISE 1
Draw the class diagrams and state the class relationships for:
"A student is a person that has a list of courses and uses a computer"
2. Always initialize variables to 0 and reference variables to null in your class definition.
3. Don't use too many user data objects in a class. Always make a new class for user data
objects.
Example a class may need a variable to describe an item. It would be better to create an item
class that has individual item variables. Use many classes to do specialize tasks rather than
one big class that does all.
4. Choose meaningful short names for your classes and methods. Classes start with a Capital
letter and methods start with a lower case letter.
CLASS COMPONENTS
The class system model states how the class is suppose to work. Objects are created from class
definitions. Objects are memory locations for variables defined in a class. The class you are defining
or the presently executing object is referred to by the built in reference this. The this reference is
supplied automatically by the compiler. The private variables hold the data values of the created
object. The constructor initializes the private variables to user defined values when the class is
instantiated (created). Data for the private variables may also be written to using the Set methods
(also called mutator methods). The process methods calculate results using the private
variables. Data is obtained from the class by using the Get methods (also called accessor
methods). You can think that a class is like a chemical tank When the storage tank is installed
(constructor) it gets some fresh liquid (data) ready for processing. Liquids (data) comes in from
the top (input methods), data is a mixture of other gooey liquids (process methods)and then
data is released from the bottom (output methods).
get data from outside world --> Set Methods put in private variables
(mutator)
MYARRAY CLASS
We will now introduce the Java class components by using an example the MyArray class. The
MyArray class will contain an array of integer items and keep track of the size of the array. Do not
be confused with the MyArray class and an array of data values. Computer programming is a precise
science. Little things may cause a big difference and many headaches.
class definition
A class definition states the class visibility, the class name and declares and defines all variables
and methods needed by the class. The class visibility states who can access the class. Each class
may have its own main method. The main method is the first method to be called when a class is
ran. The main method is used to instantiate the class it is in and other classes needed by the
program.
final variables // variables initialized once, value cannot be changed (read only)
main method // creates i/o streams, creates classes and call's class methods
The class definition for our Array class will start with a visibility of public and the class name Array.
// class MyArray
public class MyArray
class visibility
Classes may be declared as public, protected. A Public class interfaces to the outside world.
Protected means the class is only accessible by the super and sub classes In Java you may define a
class inside a class. If the visibility modifier is missing then the class has default visibility as
friendly.
friendly only classes in the same package can access this class
When a class is instantiated it becomes an object. The object type is a class name. The object
reference is a reference to the object. The object reference stores the location of the Array Object.
Variables and methods of a instantiated class are accessed by listing the object reference name
followed by the dot "." operator and the method to be called. A list of arguments is used to pass
values to the method from other methods
object _reference.method_name(argument_list);
a.getSize(); // call method getSize() belonging to Array object a
final classes
Final classes prevent the programmer from deriving a class from it. This means you cannot derive a
class from a final class.
this refers to the class object that the program is currently executing or the class you are presently
defining. The this reference is automatically created by the compiler and cannot be modified. The
this reference can refer to variables or methods belonging to the a object created from a class
definition. The this reference cannot access static variables or methods. Static variables and
methods belong to the class not to the object created from the class.
The this reference comes in handy in situations where parameter names of a constructor or method
have the same name as the variables belonging to the class. To avoid confusion of which variable
you are referring to, you use the this reference to refer to the variable defined in the class
definition.
MyArray(int size)
{
items = new int[size]; // allocated memory for array
this.size = size; // store array size in private variable
}
VARIABLES
Variables are used in the object for storage and retrieval of data. Variables are declared private so
they can be used only by the class methods that they are defined in. This means nobody else can
use them, to change data values unexpectedly,. Variables have visibility public, protected, private
and default friendly if no visibility modifier is specified.
visibility description
private variable only accessible inside the class that it was defined in
protected variable only accessible inside the class or sub classes derived from this class
Private means these variables can only be accessible inside the class it was defined in. This means
other class cannot access the private members of this class. If other classes want to access them
then they must use the public methods. The array class has two variables that are private (item and
size), because we do not want any other class to access them.
class MyArray
{
private int[] items = null; // items is a reference to a array of integers
private int size = 0; // size tells us the size of the array
final variables
A final variable value cannot be changed once it is initialized. We can have a final variable to
indicate the maximum size of out array. Final variables usually start with a capital letter.
Variables can be categorized as static variables or instance variables. Static variables are also
known as class variables and only one variable is made. Static variables belong to the class not to
instantiated objects, Static variables are shared between all instances of the class. If one object
changes the value of a static variable then the new value will be read by all the class instances. In
contrast instance variables belong to the object. Instance variables are created with every instance
of the class. If one object changes the value of a instance variable then the new value will only be
changed in that object. All other objects will retain their original values. Static variables can only be
declared in the class definition, they cannot be declared in individual methods. Static variables are
usually initialized with a default value when they are declared in the class definition. A good static
variable is one that keeps track of how many objects have been instantiated. Every time a
constructor is called the static variable can be incremented. What is the difference between a class
variable and an instance variable ?
class MyArray
{
static private int num = 0; // class variable only one variable in memory
private int[] items = null; // items is a reference to a array of integers
private int size = 0; // instance variable a copy made for every instance of
the class
If the variable is static then you use the class name to access variables and methods of the static
class.
MyArray.num
It is also possible to use an object name to access static variables, this is because the object knows
which class it belongs to. It is better to use the class name.
CONSTRUCTORS
Constructors are called when the class is instantiated. The constructor job is to initialize the private
variables, and create any other needed object . The constructor has no return value not even a void.
There are many types of constructors. default constructors, initializing constructors, conversion
constructors and copy constructors. Each constructor is used for a specific situation. This is possible
because the constructors are overloaded by different parameter types in the constructors
parameter list. Constructors are called when the class is instantiated. If you do not need to initialize
values then you do not need a constructor. In this case the values of the variables belonging to the
class object will have the values that they were declared with.
default constructor
A default constructor has no parameter list and initializes the private variables of a classes to default
values. Default constructors are not needed too much in Java because you can initialize variables
when you declare them in the class definition.
MyArray()
{
items = NULL; // set variables to default values
this.size = 0;
} a default constructor
// instantiating the Array class using a default constructor
MyArray a = new MyArray();
initializing constructor
Initializing constructors have a parameter list to initialize the private variables of a class to specified
value.
MyArray(int size)
argument values
{
Items = new int[size]; // allocated memory for array
this.size = size; // store array size in private variable
} a initializing constructor
conversion constructor
Conversion constructors have a parameter list that is used convert one data type into another data
type and to initialize the private variables of a class to specified value. In this example the array is
initialized from an array of string objects. Each String object is converted into an integer value.
{
items = new int[size]; // allocated memory for array argument values
this.size = size; ; // store array size in private variable
for(int i =0;i<size;i++) items[i] = Integer.intParse(v(i));
}
a conversion constructor
// instantiating a class using an initializing constructor
MyArray a = new MyArray("50"); // set size of array to 50 items
copy constructor
A copy constructor is used to copy the data elements of an existing class. Memory is allocated
before copying the array items from one array class to the array class object that is currently
executing. The a2 inside the copy constructor is different from the a2 object variable declared
outside the copy constructor.
{
items = new int[a2.size]; // allocate memory based on a2 size
// copy items a2
a2
for(int i=0;i<a2.size;i++) items[ i ]=a2.items[ i ]; copy
size = a2.size; // assign new size constructor
}
METHODS
Methods group programming statements together that execute sequentially under a common name.
Methods receive values, do calculations and return values. Methods are declared and defined inside
a class definition. Methods have different purposes. Input methods receive data from other class
objects. Output Methods deliver data to other methods or methods of other classes. Process
Methods use the private variables of the class object for calculations.
method definition
When you define a method you state the method visibility modifier, the return object type, the
method name and a parameter list that will receive values from other methods.
{ receive data
variables and statements;
values
optional return statement
}
method visibility
Methods may be public, protected or private. If they do not have a visibility modifier then they
are friendly.
visibility description
friendly only accessible inside the class defined in or by classes in same package
protected only accessible inside the class defined in or by subclasses derived from this class
Methods may also be static. Static methods are created before the class is instantiated. There is
only one copy made of a static method and is to be used by all instances of the class. Classes may
have static and non-static methods or a class may have all static methods. Unfortunately static
methods can only access static variables defined in a class or variables declared in the static
method. The main method is static. The main method can only access variables defined in the main
method or static variables belonging to the class.
return_data_type static method_name ( parameter list ) int static count( ) // static method
{ {
variables and statements; return num;
} }
To use a static method you state the class name and a dot operator and the static method name.
class_name. static_method_name
int x = MyArray.count();
It is also possible to use a object name to access static methods, this is because the object knows
which class it belongs to. It is better to use the class name.
final methods
A final method will not let any subclass override it. This means the super class method will always
be called rather than the derived sub class method.
Set methods receive data from the outside world. Input methods are public. In this example
method set() receive an index to place a data value in the array.
process methods
Process methods do some calculation or operation using the private variables of the class. The
process methods are usually public. The isItemOf () method tests if the specified data value is in
the array and returns true or false
{
for(int i=0;i<size;i++)
if (items[i]==data) return true; // return true if item found
else return false;
}
index method
The index() method gets the position of the data item in the array and returns the index of the item
is found. Returns
-1 if not found.
{
for(int i=0;i<size;i++)
if(items[i]==data)return i; // return index of item if item found
return -1; // return -1 if did not find
}
add method
The add() method adds an array object to another array object. The second array is passed to an
array object through the parameter list. The add method allocates memory for a new array if the
second array is larger.
a2
// add two arrays, make a new array if one array is large,
// pad excess items with zero's
public Array add(Array a2)
{
Array temp; this a3 = a1 + a2
int largest; (a1)
// check array sizes
if(size > a2.size) largest = size;
else largest = a2.size;
temp
temp = new Array(largest); (a3)
int data1,data2; // for array values
{
if(i < size) data1 = items[i]; a2.items
else data1 = 0; // pad with zeros
if(i < a2.size) data2 = a2.items[i]; +
else data2 = 0; // pad with zeros this.items
temp.items[i] = data1 + data2;
} =
temp.items
return temp;
}
The isEqual() method tests if two arrays are the same size and all elements equal by checking the
contents of each of the array elements if they are the same. This is different then testing if two
array references refer to the same Array object. (a1 == a2).
{
if(size != a2.size)return false;
for (i = 0; i<size; i++)
if(items[i] != a2.items[i]) return false; // two items not equal
return true;
}
// using the method to test if two arrays have the same data elements
if(a1.isEqual(a2))
Outputs methods must send data to the outside world from the private variables of the object. The
get() method return the array element at the specified index.
// get the data from the array index and returns it to the calling method.
public get(int index)
items
{
return items[index] ; // return data at index
}
index
// using a method to get the value of the data at an array index
a1.get(5);
If instantiate an Array object in another class like the Test class We find out we cannot access
private variables of the Array object but can access the private variables by using the input and
output public methods.
class Test
{
// main method
public static void main(String[] args) throws IOException
{
MyArray a1 = new MyArray(5); // instantiate an array object
int size = a1.size; // use variable to get size of array object
// private variable not accessible
int size = a1.getSize(); // get method to get size of array object
}
On the other hand if class method belongs to the class and receives a parameter from the same
class object type then the private variable are accessible by the method , as shown in the Array
class copy constructor.
{
items = new int[a2.size]; // allocate memory based on a2 size
// copy items
for(int i=0;i<a2.size;i++) temp[ i ]=a2.items[ i ];
size = a2.size; // assign new size
}
main method
The main() method is used to test the Array class. The main method is static, which means the
main method exists before an instance of the class is created. The main method is required to test
and instantiate Array class objects. . The main method will instantiate the Array class objects.
The main method tests the operation of each methods of the array class and reports the results to
the user. The main method is the first method to be called when a class runs. Each class can have
its own main method. By testing each class individually you are guaranteed that all the classes will
operate correctly when the program is used as a whole.
// main method
public static void main(String[] args) throws IOException
{
// size of array
final int Size = 10;
[0 1 2 3 4 5 6 7 8 9]
// make an array of 10 items
MyArray a = new MyArray(Size); the fifth element is: 5
// initialize array using set
for(int i =0;i<Size;i++) a.set(i,i);
finalize method
Finalize may be used to force immediate memory reclamation by forcing garbage collection on an
object. The finalize method belonging to the Object class can be called before the class is destroyed.
Nobody uses finalize method too much because they are unpredictable. Java has automatic garbage
collection facilities to reclaim memory.
finalize()
{
items = null; // set Items null to be garbage collected
}
LESSON 11 QUESTION 1
import java.io.*;
// class Array
class MyArray
{
private int[] items; // array to hold items
private int size; // number of items in array
// default constructor
public MyArray()
{
items = null;
size = 0;
}
// initializing constructor
// make a new array from indicated size
public MyArray(int size)
{
items = new int[size]; // allocate memory for array items
this.size = size; // set number of items in array
}
// copy constructor
public MyArray(MyArray a2)
{
items = new int[a2.size]; // allocate memory for array elements
{
Array temp;
int largest; this
a3 = a1 + a2
(a1)
// check array sizes
if(size > a2.size)
largest = size;
else
largest = a2.size;
return temp;
}
{
// loop till data element found
for(int i=0;i<size;i++)
if(items[i]==data)return i; // if data found return index
return -1; // not found
}
{
// loop till data element found
for(int i=0;i<size;i++)
if(items[i]==data)return true; // data element found
return false; // not found
}
{
// array sizes not equal
if(size != a2.size)return false;
// loop till data element found
for(int i=0; i<this.size; i++)
if(items[i] != a2.items[i]) return false;
return true; // two arrays equal
}
{
String s = "\n\r [";
for(int i=0;i<size;i++)
{
s += get(i));
if(i < size-1)s += " ");
}
s + = "]";
return s;
}
// make array a1
MyArray a1 = new MyArray(NumItems);
for(i=0;i<NumItems;i++)a1.set(i,i); // initialize
4 is element of array
array a1 [0 1 2 3 4 5 6 7 8 9]
program output:
array a2 [0 1 2 3 4]
sum of a1 + a2 [0 2 4 6 8 5 6 7 8 9]
a1 != a2
a1 not equal a2
a1 == a2
array a1 [0 2 4 6 8 5 6 7 8 9]
array a2 [0 2 4 6 8 5 6 7 8 9]
array a1 [0 4 8 12 16 10 12 14 16 18]
array a2 [0 2 4 6 8 5 6 7 8 9]
LESSON 11 EXERCISE 1
Change the Array class to handle String objects. Call your project and running class L11ex1
LESSON 11 EXERCISE 2
Change the Array class to handle any object. Call your project and running class L11ex2
IMPORTANT
You should use all the material in all the lessons to do the questions and exercises. If you do not
know how to do something or have to use additional books or references to do the questions or
exercises, please let us know immediately. We want to have all the required information in our
lessons. By letting us know we can add the required information to the lessons. The lessons are
updated on a daily bases. We call our lessons the "living lessons". Please let us keep our lessons
alive.
E-Mail all typos, unclear test, and additional information required to:
courses@cstutoring.com
students@cstutoring.com
http://www.cscourses.com/java.htm
This lesson is copyright (C) 1998-2006 by The Computer Science Tutoring Center "cstutoring"
This document is not to be copied or reproduced in any form. For use of student only.
File: JavaL12.doc
ABSTRACT CLASSES
An abstract class is a super class that is required to have a derived sub class. The derived sub class
inherits all the variables and methods from the super abstract class. An abstract class contains
methods that are incomplete, meaning there is a method declaration but no code. The abstract class
and abstract methods both have the abstract modifier. Abstract classes are needed to specify
which methods a sub class must contain. Abstract classes may have constructors and other methods
that are complete.
{
public abstract void print(); // ends with a semi colon
}
The code for the abstract methods are to be written in the derived sub class. You may not
instantiate an abstract class. You can only instantiate the derived sub class. An abstract class may
have non-abstract methods. The rule is that the abstract methods should only be the methods
needed in the derived sub class. When you derive a class from an abstract super class you must
include and write the code for all the abstract methods of the abstract super class. All derived
classes will have the same abstract methods.
Why do we need abstract classes ? Abstract classes force all super classes to have a derived class.
The abstract class is like the definition model that all derived sub classes have to follow. Abstract
classes are used mostly in a large team oriented programming project. Abstract classes forces Java
to call derived sub class methods rather than super class methods. With abstract classes you are
always assured the compiler will call the derive class sub method and not the super class method.
There are many situations when you want to only instantiate derived sub classes and not the super
class. This is an ideal situation for abstract classes.
An abstract super class called Animal has an abstract method print() that has no code and ends with
a semicolon. The derived sub class called Donkey also has a method called print(). The sub class
Donkey is derived from the super class Animal. Deriving a class from an abstract class always
assures that the derived method is called. Abstract classes may contain non-abstract methods.
{
public abstract void print();
}
{
System.out.println("I am a donkey"); // abstract method ends with a
semicolon
}
{
Donkey d = new Donkey(); // instantiate a Donkey object
d.print(); // call the print method of the derived class
}
An abstract class that contains only abstract methods is known as an Interface. An interface is a
collection of abstract methods that can be used to specify what methods a class must implement.
By using interfaces you can write a class that will work on many different kinds of objects. All
methods in an interface are abstract meaning they are declarations only and have no code and end
with a semi-colon. You cannot put static methods in an interface. Interfaces cannot be instantiated.
All methods and variables in an interface must have default visibility of public. The default visibility
of variables and methods in an interface are public. All variables in an interface must be public
static final. You use Interfaces just like you would use pure abstract classes. Pure, meaning
abstract classes have all abstract methods. The abstract keyword is optional for methods in an
interface. You declare and define an interface as follows:
Uses of interfaces
Our interface example is ZooAnimal which contains an abstract method called place() that returns
the area where a zoo animal lives. When a class uses an interface it means the class implements
the interface. You specify the interface that your class will implement when you define your class.
{ Interface
variable and methods of class ZooAnimal
methods for interface
}
{ Tiger
private String home; // this is where the Tiger lives
{
this.home = home; // this is where the tiger lives
}
A super class can represent a sub class. An interface can represent any class that implements it.
t1 Tiger
// main method for class Tiger
public static void main(String args[])
{ t2 Tiger
Tiger t1 = new Tiger("by the monkey");
System.out.println("Hello I am a Tiger and I live "+ t1.place());
Notice in the main method we instantiate our Tiger as a Tiger object and as a ZooAnimal object. We
cannot instantiate an interface because an interface is a pure abstract class and all of its methods
are only declarations and contain no code. But we can have our instantiated class having an
Interface object type. Using an Interface as an object type lets us use represent any class
implementing the interface.
You instantiate an instance of your class implementing the interface as you would normally do.
When several different classes implement a common interface, objects that are instances of those
classes can be used wherever variables of the interface are declared. This means you can use the
interface name as variable name of objects implementing the interface. You cannot instantiate an
interface directly. Why? Because the interface has no variables to allocate and no code. Does an
Interface need a Constructor ? Try it see what happens !!! The answer is no. Static final variables
belonging to the Interface must be initialized when they are declared
All methods in an interface must be abstract and public, the default is abstract public,. All variables
inside an interface must be final public static and must be initialized. The default is final public
static. Using interfaces guarantees that your class will have all the required methods. If you do not
implement all the methods in your class required by the interface then you will get concrete
implementation message errors. The above program is rewritten where the interface supplies the
home for the zoo animal as a static interface variable. The tiger class gets to use the static variable
of the ZooAnimal interface because it implements the ZooAnimal interface. Why must variables
declared in an interface be public static ?
{
public Tiger () {} // default constructor
{
return home; Hello I am a Tiger and I live in the Zoo
} Hello I am a Tiger and I live in the Zoo
// main method
public static void main(String args[])
{
Tiger t1 = new Tiger();
System.out.println ("Hello I am a Tiger and I live " + t1.place());
ZooAnimal t2 = new Tiger();
System.out.println ("Hello I am a Tiger and I live " + t2.place());
}
Java does not support multiple inheritance. A Java class cannot inherit more than one class.
Interfaces give Java classes multiple inheritance capability. How ? Any class that implements the
interface will have methods that will support the interface. This means the Java compiler will
recognize your class as being inherited from the interface. If you also derive your class from a super
class then you can inherit a class and an interface.
{
variable and methods of class
methods for interface
}.
In inheritance the arrows go in one direction only. This means the derived sub class inherit or uses
methods and variables from the super class. The super class cannot use methods and variables of
the derived class. The super class knows nothing about the derived class.
Here's the complete program where the Tiger class is derived from Animal and implements the
ZooAnimal Interface.
// ZooAnimal Interface
interface ZooAnimal
{
public String place( );
}
// sub class Tiger is derived from super class Animal and implements the Zoo
interface L12P4
class Tiger extends Animal implements ZooAnimal
{
ZooAnimal
private String home; // this is where the Tiger lives Animal
You will also notice in main method above there is a situation where we have to type cast to Tiger.
The method getName() is in the Tiger class derived from the super class Animal. Reference
variable t2 has object type ZooAnimal. The getName() method is not known to the interface
ZooAnimal. When we type case we force the object type represented by t2 to be a Tiger.
You have just been introduced to the pain and torture using interfaces. Many people find interfaces
very frustrating to work with. Typecasting with Interfaces is unavoidable. The trick is to design your
programs to keep typecasting to a minimum.
Classes may implement multiple interfaces. Although a class can implement multiple interfaces it
may still only be derived from one super class.
{
variable and methods of class
methods for interface 1
methods for intwrface2
} Animal ZooAnimal ZooFood
(super class) (interface1) (interface2)
// interface 1
public Interface ZooAnimal
{
public String place();
}
Tiger
// interface 2 (sub class)
public Interface ZooFood
{
public String eats();
}
{
this.name=name;
}
{
return name;
}
{
private String home; // where the animal lives
private String food; // what the animal eats
// initializing constructor
Tiger(String name,String home, String food)
{
super(name); // initialize super class
this.home = home;
this.food = food;
}
{
return home;
}
{
return food;
}
{
// instantiate a Tiger object type
Tiger t1 = new Tiger("Tony","by the monkey", "ice cream");
System.out.println("Hello I am " + t1.getName() + " and I live "+ t1.place()
+ " and I eat " + t1.eats());
Hello I am Tony and I live by the Monkey and I eat ice cream
Hello I am Tony and I live by the Monkey and I eat ice cream
Hello I am Tony and I live by the Monkey and I eat ice cream
We still have to typecast for the getName() method and also typecast for the eats() and place()
methods because ZooAnimal knows nothing about the eats() method and ZooFood knows nothing
about place() method..
System.out.println (
"Hello I am " + ((Tiger)t2).getName() + " and I live "+ t2.place() + " and I eat " +
((Tiger)t2).eats());
We also have to typecast for the place() method because ZooFood knows nothing about the place()
method defined in the ZooAnimal interface.
System.out.println (
"Hello I am " + ((Tiger)t3).getName() + " and I live" + ((Tiger)t3).place() + " and I eat "
+ t3.eats());
That's right you can derive interfaces from interfaces. One interface extends another interface.
Notice we use the keyword extends to derive an interface from another interface.
{
static final variables;
interface abstract methods;
}
Sometimes you may need to derive interfaces from interfaces. When you have a class that
implements multiple interfaces and these multiple interfaces have common abstract methods. In the
following example program the ZooAnimal interface and the ZooFood interface both want to have
print methods. To avoid duplication we create a Zoo interface that just has a print method. Both
ZooAnimal and ZooFood will extend the Zoo interface. The good thing here is that which ever
interface your class implements you will always be forced to have a print method !
{
void print( );
}
{ Zoo
public String place ( );
}
{
public String eats ( ); ZooAnimal ZooFood
}
Zoo
Animal (super Interface)
(super class) print()
ZooAnimal ZooFood
(derived sub (derived sub
interface1) interface2)
place() eat()
Tiger
(sub class)
print()
{
private String name; // animal name
{
this.name=name;
}
If a class implements an interface it
} also implements the super interface
// return name of animal
public String getName()
{
return name;
}
// class Tiger
class Tiger extends Animal implements ZooAnimal
{
String home; // where tiger lives
String food; // what tiger eats
// constructor
public Tiger(String name, String home, String food)
{
super(name);
this.home = home;
this.food = food;
}
{
return food;
}
{
return home;
}
{
System.out.println
("Hello I am " + getName() + " and I live "+ place() + " and I eat " +
eats());
}
// main method
public static void main(String args[])
{
Tiger t1 = new Tiger("Tony","by the monkey", "ice cream");
t1.print();
Zoo t2 = new Tiger("Tony","by the monkey", "ice cream");
t2.print();
ZooAnimal t3 = new Tiger("Tony","by the monkey", "ice cream");
t3.print();
ZooFood t4 = new ZooFood("Tony","by the monkey", "ice cream");
t4.print();
}
Hello I am Tony and I live by the monkey and I eat ice cream
Hello I am Tony and I live by the monkey and I eat ice cream
Hello I am Tony and I live by the monkey and I eat ice cream
Hello I am Tony and I live by the monkey and I eat ice cream
The advantage of using the super interface with the print method is that now no typecasting is
necessary. You now have the freedom to create Tiger, Zoo, or ZooAnimal objects from the Tiger
class. The tiger class extends the Animal class and implements the ZooAnimal interface. The
ZooAnimal interface extends the Zoo Interface. When we call the print method either from Tiger,
Zoo, or ZooAnimal objects the Java compiler knows where to find the print method in the Tiger
class. This is very powerful. This is possible because the ZooAnimal class get to use the methods of
the Zoo Interface and the Tiger class implements the ZooAnimal Interface.
LESSON 12 EXERCISE 1
Design your own interface super interface with base and derived classes that implement them.
Now you know what interfaces are and how they work, we can now re-write the Array class using
an ArrayData class and an ArrayDataOps interface.
We use the ArrayData class to manages the data for the Array class. By using a separate array
data class, we can represent any data type we want without rewriting the Array class. The ArrayData
class implements the ArrayDataOps interface. The ArrayDataOps interface is used to specify which
methods the ArrayData class must implement. The ArrayDataOps interface defines the methods for
the Array Data class. The ArrayData class holds the array data element for us. By using a separate
class for array data and having a common interface we can represent any data type we want int,
long, float, double or String.
{
public ArrayDataOps add(ArrayDataOps data ); // add data values
public boolean equals(ArrayDataOps data ); // test data values equal
public String toString( ); // convert data value to a string
}
We need a class to represent different data types. We will call this class the ArrayData class. The
Array Data class can represent any data type we want: int, char, double, String etc. The
ArrayData class will implement the ArrayDataOps Interface. The ArrayDataOps interface states what
methods the ArrayData class must implement. The Array class needs an array of numbers. Each
number can be represented by an ArrayDataOps object to represent a number with a certain data
type. We use an array of ArrayDataOps rather than an array of ArrayData's. The reason is this. By
using the ArrayDataOps Interface we can use any class representing the data type we want that
implements the ArrayDataOps interface. If we used the ArrayData class then we would be stuck
with one data type only. The added benefit is, we only type cast in the ArrayData class, no where
else. (very clean). The ArrayData class objects will only be created in the main program. Here's
the array class using the ArrayData class implementing the ArrayDataOps interface:
// constructor
public ArrayData (int data ) {item = data;}
The array class uses the ArrayDataOps Interface to manage the data for its array of elements. Why
do we use the ArrayDataOps Interface rather than the ArrayData class? By using the ArrayDataOps
Interface as our object type for the array of elements, give us the flexibility to use any class that
implements the ArrayDataOps interface. If we just used the ArrayData class we would always be
stuck with this one object type. By using the ArrayDataOps interface we can use any object type for
our array elements: int, char, String etc. Our Array elements will be an array of ArrayDataOp
references. The main method will instantiate ArrayData objects that are stored as ArrayDataOps
objects.
Array class
array of ArrayDataOps ArrayDataOps
references Interface
items
ArrayData
import java.io.*; Class
// class to represent an array of objects
class Array
{
private ArrayDataOps[] items; // array of ArrayDataOps references
private int size; // number of elements in the array
// default constructor
public Array()
{
items = null;
size = 0;
}
// initializing constructor
// make a new array from indicate size
public Array(int size)
{
items = new ArrayDataOps[size]; // allocate memory for array data
Size = size;
}
{
items = new ArrayDataOps[a2.size];
for(int i=0;i<a2.size;i++)item[i]=a2.items[i];
size = a2.size;
}
{
Array temp;
int largest;
{
if(i < size) data1 = items[i];
else data1=new ArrayData(0); // pad to zero
{
return items[index];
}
{
for(int i=0;i<size;i++)
// call equal method from class implementing ArrayDataOps
if(items[i].equals(data))return i;
return -1;
}
{
for(int i=0;i<size;i++)
// call equal method from class implementing ArrayDataOps
if(items[i].equals(data))return true;
else return false;
}
// test if two arrays have same data items and same sizes
public boolean isEqual(Array a2)
{
if(size != a2.size)return false;
{
String s = "\n\r [");
for(int i=0;i<size;i++)
{
s += get(i);
if(i < Size-1)s+= " ";
}
s += "]";
}
{
items[index] = data;
}
// main method
{
final int SIZE = 10;
// initialize array a1
for(int i=0;i<SIZE;i++) a1.set(i,new ArrayData(i));
// print array a1
System.out.println("array a1: ",a1);
// make an array a2
Array a2 = new Array(SIZE/2);
// initialize array a2
for(int i=0;i<SIZE/2;i++)
a2.set(i,new ArrayData(i));
// print array a2
System.out.println("array a2: ",a2);
// test adding
a1 = a1.add(a2);
a1.print("sum of a1 + a2");
// test if equal
if(a1 == a2)System.out.println("a1 == a2");
else System.out.println("a1 != a2");
} /* end main */
} // end Array class
LESSON 12 EXERCISE 1
Add a zero() method to the ArrayDataOps interface that will return a zero value ArrayDataOps.
LESSON 12 EXERCISE 2
Change the ArrayData class to handle String objects update the main method.
LESSON 12 EXERCISE 3
For our ArrayData class we made need different data types to be represented,. We may need
strings, int, double etc. Rather then rewriting the ArrayData class for every data type we need we
will have many derived sub classes,. ArrayDataString, ArrayDataInt etc. Multiple inheritance comes
to the rescue. We have the ArrayData class as the base class, all derive sub classes will inherit the
base class and the interface. Derive a subclass ArrayDataString, ArrayDataInt, ArrayDataDouble
from the ArrayData class to handle String objects int and double respectively.
IMPORTANT
You should use all the material in all the lessons to do the questions and exercises. If you do not
know how to do something or have to use additional books or references to do the questions or
exercises, please let us know immediately. We want to have all the required information in our
lessons. By letting us know we can add the required information to the lessons. The lessons are
updated on a daily bases. We call our lessons the "living lessons". Please let us keep our lessons
alive.
E-Mail all typos, unclear test, and additional information required to:
courses@cstutoring.com
students@cstutoring.com
http://www.cscourses.com/java.htm
This lesson is copyright (C) 1998-2006 by The Computer Science Tutoring Center "cstutoring"
This document is not to be copied or reproduced in any form. For use of student only.
File: JavaL13.doc
VECTOR CLASS
Vectors are like arrays but they are expandable and shrinkable. Why do we need Vectors ? We need
Vectors because we do not want to waste memory. When do we use a vector and when do we use
an array? We use Vectors when we do not know how many items we have. Vectors have methods
to add elements, remove elements get values of the elements in the vector etc. A vector has a step
size. This means it expands and shrinks to a default or specified size. Java has the built in Vector
class located in java.util.* The Java Vector class methods are as follows:
public Vector constructs an empty vector with the specified initial capacity and
(int initialCapacity, int capacityIncrement) capacity increment
public Vector(int initialCapacity) constructs an empty vector with the specified initial capacity and
default capacity increment 0
public Vector() constructs empty vector with default initial capacity 10 and
default capacity increment 0
public final synchronized void copyInto copies the components of this vector into the specified array.
(Object anArray[])
public final synchronized void trimToSize() trims the capacity of this vector to be the vectors current size
public final synchronized void ensureCapacity increases the capacity of this vector
(int minCapacity)
public final synchronized void setSize(int newSize) sets the size of the vector
public final int capacity() returns the current capacity of this vector
public final int size() returns the number of components in this vector
public final synchronized Enumeration elements() returns an enumeration of the components of this vector
public final boolean contains(Object elem) returns true if elm is a component of this vector
public final int indexOf(Object elem) return the index of the first occurrence of
elem else returns -1
public final int indexOf (Object elem, int index) searches for the first occurrence of the Object elem beginning at
the search index
public final int lastIndexOf(Object elem) returns the index of the last occurrence of elem
public final int lastIndexOf (Object elem, int index) searches backwards for the Object elem starting from the
specified index and returns index or -1
public final Object get (int index) returns the component at the specified index
public final Object elementAt (int index) returns the component at the specified index
public final Object firstElement() returns the first component of this vector
public final Object lastElement() returns the last component of this vector
public final void setElementAt Sets the component at the specified index of this
(Object obj, int index) vector the previous value is overwritten
public final void insertElementAt Insert the component at this index, each component from the
(Object obj, int index) index is shifted up
public final void add(Object obj) adds the component at the end of this vector, increasing the
vector size by 1, the capacity is increased if needed
public final void addElement (Object obj) adds the component at the end of this vector, increasing the
vector size by 1, the capacity is increased if needed
public final boolean removeElement(Object obj) removes the first occurrence of the specified object from the
vector and rest of components shifted downward
public final boolean removeElementAt removes the object at the index from the vector and rest of
(int index) components shifted downward
public final void removeAllElements() removes all components from this vector and sets its size to zero
public Object clone() returns a clone of this vector copies vector to allocated memory
The following program makes a vector Object, inserts 4 Integer objects into the Vector. Vectors
only take objects. We use Integer objects to represent numbers. We cannot use int data types
because they are not objects. The Integer class is used to change int into objects. We use the
addElement() method to add objects to the Vector object. We use the elementAt() method to get
the objects stored in the vector at a specified index. We use the setElement() method to put a new
object at a specified location. A Vector is essentially an array of objects. In Java all classes are
derived from the Object class. An Object can represent any Java class. You do not need to type cast
when inserting an object into a vector. You must type class when retrieving an item from a vector.
You must typecast because the Java compiler must know what object type you want from the
Vector.
import java.util.Vector;
class VectorTest
{
// example using vector class
public static void main(String args[])
{
Vector v = new Vector(); // make vector object
v.addElement(new Integer(1)); // add number 1
v.addElement(new Integer(2)); // add number 2
v.addElement(new Integer(3)); // add number 3
v.addElement(new Integer(4)); // add number 4
System.out.println(v); // print out contents of vector
System.out.println(v.size()); // print out number of elements
Integer num1 = (Integer) v.elementAt(1); // get number 1
System.out.println(num1); // print out value
v.setElementAt(new Integer(5),1); // set vector 1 to number 5
num1 = (Integer) v.elementAt(1); // get vector 1
System.out.println(num1); // print out value
}
0 1 2 3 4 5 6 7 8 9
v 1 2 3 4
Program Output:
4
2
5
LESSON 13 EXERCISE 1
Instantiate a Vector objects and fill it with 10 numbers 1 to 10. Instantiate a second Vector object
Remove 5 objects from the first Vector and put them in the second vector. Print out the contents of
both Vectors.
When you use the Vector class with Java 1.5 you must specify the data type it contains in triangle
brackets <>
This makes the Vector class easier to use because type casting is no longer needed
Specify the data type also makes sure the Vector object only contains the data type you have
specified. If you do not specify the data type when using the Vector class you will get a compiler
warning. (very annoying)
It will tell you where the warnings occur. Here is the same Vector Test program using specified data
type.
import java.util.Vector;
class VectorTest2
{
You can use an for loop to print out the vector element values.
System.out.println(num);
java 1.5 has a for each loop to printout elements of a object. You specify the element data type a
variable name and the collection object.
System.out.println(num);
ENUMERATIONS
Java has lots of predefined interfaces that you can implement. Interfaces declare the methods a
class must implement. Interfaces also represent classes implementing the interface. By using
predefined interfaces your programs can integrate easily with other programs. One of the most
common interfaces used is the Enumeration interface located in java.util.Enumeration. An
Enumeration will let the user retrieve objects one by one from objects stored in another object. The
objects stored are usually stored in some kind of array or a list. The user does not have to be
concerned how the objects are stored, they just want to get the objects one by one. The
Enumeration interface just has two methods:
method description
It is very easy and convenient to use the enumeration interface. The class that stores the data
usually has a method that returns an enumeration object. For example the Vector class located in
java.util.Vector has the elements() method that returns an enumeration object. The following
example program constructs a Vector objects and initializes it with its own index. The elements()
method of the Vector class is called that returns an Enumeration of the elements stored in the
Vector object. An Enumeration object stores an array of objects and releases then one by one. .As
long as the enumeration has more elements the next element of the enumeration is printed out.
import java.util.Enumeration;
class EnumerationTest
{
// Enumeration example using vector class L13P1
public static void main(String args[])
{
// using a enumeration interface using the Vector class
final int Size = 10;
{
Object obj = e.nextElement(); // get element object
System.out.print(obj.toString() + " "); // print out object
}
It is quite easy to make your own class implementing the Enumeration Interface. Your class has a
method that returns an Enumeration object. Your class would store objects in an array of objects.
Since all classes in Java are inherited from the Object class., an array of objects can store any
object. A index would keep track of the current object and the index would advance to the next
object every time an object was requested.
import java.util.Enumeration;
{
Object[] array; // array to enumerate on
int current = 0; // Current element index
int size = 0; // index of the last element in the array
{
this.array = array; // store array
this.size = size; // last element in array
}
{
return current < size; // return true if not last element
}
{
return array[current++]; // return current item in array
}
To use the ArrayEnumeration class you would provide its constructor with some array and the size
of the array. You get a reference to each object in the Enumeration one by one.
import java.util.Enumeration;
class ArrayEnumerationTest
{
{
// initialize an array of String items to put into vector
String[] a = {"1","2","3","4","5","6","7","8","9","10");
{
Object obj = e.nextElement(); // get element object
System.out.print(obj.toString() + " "); // print out object
}
} 1 2 3 4 5 6 7 8 9 10
}
LESSON 13 EXERCISE 2
Iterator (java.util)
An iterator access each element one by one. An iterator is much like an enumerator. Some iterators
let you remove or change elements. The Iterator is located in java.util. and is an abstract class to be
implemented by an object holding data elements like a Vector object. The vector class has the
iterator() method that returns a Iterator object.
Here is our test program that uses an Iterator to print out the contents of a Vector object.
import java.util.Vector;
import java.util.Iterator;
class IteratorTest2
{
// example using iterator
public static void main(String args[])
{
Vector v = new Vector(); // make vector object
To use the Itrerator with Java 1.5 we must specify the data type for the Vector and Iterator.
import java.util.Vector;
import java.util.Iterator;
class IteratorTest2
{
while(itr.hasNext())
{
Integer num = itr.next();
System.out.println(num);
}
IMPORTANT
You should use all the material in all the lessons to do the questions and exercises. If you do not
know how to do something or have to use additional books or references to do the questions or
exercises, please let us know immediately. We want to have all the required information in our
lessons. By letting us know we can add the required information to the lessons. The lessons are
updated on a daily bases. We call our lessons the "living lessons". Please let us keep our lessons
alive.
E-Mail all typos, unclear test, and additional information required to:
courses@cstutoring.com
students@cstutoring.com
http://www.cscourses.com
this lesson is copyright (c) 1998-2006 by the computer science tutoring center "cstutoring"
this document is not to be copied or reproduced in any form. for use of student only.
File: JavaL14.doc
ArrayList
An ArrayList is like a Vector but has fewer methods. It is easier to use and most people use it
instead of the Vector object. Here are the ArrayList methods.
void add(int index, Object element) Inserts the specified element at the specified position in this list.
boolean add(Object o) Appends the specified element to the end of this list.
boolean addAll(Collection c) Appends all of the elements in the specified Collection to the end of
this list, in the order that they are returned by the specified
Collection's Iterator.
boolean addAll(int index, Collection c) Inserts all of the elements in the specified Collection into this list,
starting at the specified position.
boolean contains(Object elem) Returns true if this list contains the specified element.
void ensureCapacity(int minCapacity) Increases the capacity of this ArrayList instance, if necessary, to
ensure that it can hold at least the number of elements specified by
the minimum capacity argument.
Object get(int index) Returns the element at the specified position in this list.
int indexOf(Object elem) Searches for the first occurrence of the given argument, testing for
equality using the equals method.
int lastIndexOf(Object elem) Returns the index of the last occurrence of the specified object in
this list.
Object remove(int index) Removes the element at the specified position in this list.
protected void Removes from this List all of the elements whose index is between
removeRange(int fromIndex, int toIndex) fromIndex, inclusive and toIndex, exclusive.
Object set(int index, Object element) Replaces the element at the specified position in this list with the
specified element.
Object toArray() Returns an array containing all of the elements in this list in the
correct order.
Object toArray(Object[] a) Returns an array containing all of the elements in this list in the
correct order; the runtime type of the returned array is that of the
specified array.
void trimToSize() Trims the capacity of this ArrayList instance to be the list's current
size.
import java.util.ArrayList;
import java.util.Iterator;
class ArrayListTest
{
import java.util.ArrayList;
import java.util.Iterator;
class ArrayListTest
{
// example using ArrayList class
public static void main(String args[])
{
ArrayList<Integer> list = new ArrayList<Integer>(); // make arraylist object
list.add(new Integer(1)); // add number 1
list.add(new Integer(2)); // add number 2
list.add(new Integer(3)); // add number 3
list.add(new Integer(4)); // add number 4
}
}
EXCEPTION HANDLING
Exceptions occur when an abnormal error is caused when your program is running. The most
common ones are divide by zero, type a letter for a number on the keyboard, file not found etc.
When a Exception occurs your program will report the exception and stop running. The following
program stops running at divide by zero.
class ExceptionTest
{
// method will catch I/O errors for you
public static void main (String[] args) program output:
{
int x = 10;
x = x / 0; Exception in thread "main"
} java.lang.ArithmeticException / by zero
at ExceptionTest2.main (ExceptionTest2.java:9)
}
Exceptions need to be caught when they happen before your program stops running. The
mechanism to do this is known as a try catch block. Try meaning try something and catch
meaning catch the exception before your program stops running.
try
{
code that might cause an exception
}
catch(ExceptionType e)
{
handler for this exception
}
The following code shows how to catch an Arithmetic exception divide by zero. e is the Exception
type object that caused the exception. You can use the printStackTrace() method belonging to the
Exception class to print out all the methods called before the exception occurred.
class ExceptionTest2
{
// method will catch I/O errors for you
public static void main (String[] args)
program output:
{
int x = 10;
try java.lang.ArithmeticException
{
java.lang.Throwable()
x = x / 0; java.lang.Exception()
} java.lang.RuntimeException()
java.lang.ArithmeticException()
catch(ArithmeticException e ) void ExceptionTest.main(java.lang.String [])
{ java.lang.ArithmeticException
// report exception java.lang.ArithmeticException / by zero
e.printStackTrace();
System.out.println(e);
}
LESSON 14 EXERCISE 3
Try out the above programs. Which one do you like the best ?
EXCEPTION HIERARCHY
The Exception class is found in java.lang.*. An Exception is always a class derived from
Throwable. Error and Exception classes are derived from Throwable. The Error class describe
internal and memory allocation errors and not to be used by programmers. The Exception class is to
be used by programmers. There are two type of Exceptions IOExceptions and
RuntimeExceptions. Run time errors occur because of a programming error when your program is
running. For example: when your program access a out of bounds index of an array or a null
reference access. An IO exceptions occurs when a character is entered for a number, reading past
the end of a file etc.
Throwable
Error Exception
IOException RunTimeException
Exception is the super class where these exception classes are derived from.
ClassNotFoundException java.lang when an application tries to load in a class through its but no
definition for the class with the specified name could be found.
CloneNotSupportedException java.lang the clone method in class has been called to clone an object,
but that the object's class does not implement the interface.
(a clone copies an existing object)
IllegalAccessException java.lang (1) when an application tries to load in a class but the currently
executing method does not have access to the definition of the
specified class, because the class is not public or is in another
package.
Runtime java.lang run time exceptions, null reference, array out of bounds
IOExceptions are caused by programming error or I/O device failure. IOExeceptions are also known as checked exceptions.
This means the compiler checks if you have used a try/catch block or declared your methods with throws IOException. If you
did not the compiler reports a compile error. Here is a list of derived IOException classes.
Runtime Exceptions occur when your program is running. runtime exceptions are caused by programming errors or hardware
failure.. Here is a list of derived RuntimeException classes.
NullPointerException java.lang when an application attempts to use null in a case where an object is
required.
ArrayStoreException java.lang Thrown to indicate that an attempt has been made to store the wrong type
of object into an array of objects.
ClassCastException java.lang Thrown to indicate that the code has attempted to cast an object to a
subclass of which it is not an instance.
ArithmeticException java.lang when an exceptional arithmetic condition has occurred. For example, an
integer "divide by zero" throws an instance of this class.
IllegalArgumentException java.lang indicate that a method has been passed an illegal or inappropriate argument.
IllegalMonitorStateException java.lang indicate that a thread has attempted to wait on an object's monitor or to
notify other threads waiting on an object's monitor without owning the
specified monitor.
IllegalStateException java.lang Signals that a method has been invoked at an illegal or inappropriate time.
In other words, the Java environment or Java application is not in an
appropriate state for the requested operation.
When you use methods that generate checked IOExceptions you must use a try/catch block or your
method must be declared of returning the checked exception.
The following method must be declared of throwing a IOExceptioon. The IOException originates from
the readLine() method of the BufferedReader class.
import java.io.*;
class CheckedTest
{
public static void main (String[] args) throws IOException
{
while(true)
{
System.out.println("enter a number: ");
int x = Integer.parseInt(in.readLine());
System.out.println(x);
System.out.println(10/x);
}
}
}
LESSON 14 EXERCISE 4
Re-write the above program using a try/catch block. Call your class CheckedTestTry
If an error is found while your code is running and you want to terminate your method early you
may want to throw a pre-defined Java exception. You first need to determine what exception you
need to throw and then instantiate an object of that exception class with the new operator and then
throw it. Don't forget the new operator.
You may be reading a file and you come to the end unexpectedly, so you may want to throw an end
of file exception immediately. Every method that throws an checked exception must be declared to
throw that exception in the method header.
import java.io.*;
class ThrowTest
{
public static void main (String[] args) throws IOException
{
BufferedReader in = new BufferedReader(new
InputStreamReader(System.in),1);
while(true)
{
System.out.println("enter a number: ");
int x = Integer.parseInt(in.readLine());
System.out.println(x);
if(x == 0) throw new ArithmeticException("x is 0");
System.out.println(10/x);
}
} called method
}
return
exception call method
Throwing an exception is like a
return statement. You are returning object
an exception object to the calling
method. A method can return a value
or a exception object. calling method
LESSON 14 EXERCISE 5
Re-write the above program using a try/catch block. Call your class ThrowTestTry
You can create your own exception class. For example if you have an Array class and some idiot tries
to write past the end of your array, you should generate your own index out of bounds exception.
You derive your class from Exception or IOException. Use the IOException class for I/O
exceptions and the Exception class for non I/O exceptions. An example for a non I/O Exception is
the array out of bounds. You need to use a try/catch block when calling methods that throw your
exception. If you do not use a try/catch block then you need to include the throw exception clause in
your method that calls the method that generated the e4xception. You also need to include the
throws exception clause in your method that your throw your exception in.
We can use our ArrayException in our MyArray class from previous lessons.
// class MyArray
class MyArray
{
int[ ] items; // reference to an array of integers
int size; // size of array
// initializing constructor
MyArray(int size)
{
items = new int[size]; // create array of integers
this.size = size; // store size of array
}
// main method
public static void main(String args[])
{
MyArray a = new MyArray(5); // create Array object
try
{
put(5,10); // write 5 to array at index 10
}
catch(ArrayException e) // catch exception
{
System.out.println(e); // report index out of bounds
}
}
}
LESSON 14 EXERCISE 6
Write the ArrayTest class for the MyArray class. Test it with many different indexes.
INHERITING EXCEPTIONS
You may need more specialized exceptions from your exception class. A good example would be to
have a separate ArrayIndexException that would be more specialized. In this example
ArrayIndexException would inherit ArrayException.
We can now expand our MyArray class to have more specific exceptions. We now use the
ArrayException in the constructor to handle negative sizes. We replace the excerption in the put
method with the ArrayIndexException when the array index is out of bounds.
// class MyArray
class MyArray
{
int[ ] items; // reference to an array of integers
int size; // size of array
LESSON 14 EXERCISE 7
Write the ArrayTest class for the MyArray class. Test it with by creating arrays of all different sizes.
You can have more than 1 catch block. One catch block can be used for specific exceptions, another
for any other exception and one for general exceptions. The rule is a more specific catch block
must proceed a more general one. A specific exception always inherits a general exception. When
you have many catch blocks only one catch block is executed. The first one applicable is executed.
A sequence of catch blocks may end with a finally block. A finally block is always executed even if
an exception does not occur. Finally blocks are usually used to close a file or do some sort of
cleanup. A good example of a specific exception is the ArrayIndexException. The general
exception would be the ArrayException . The other exception could be a ArithmeticException etc.
// specific exception
catch(ArrayIndexException e)
// other exception {
catch(specific exception e) System.out.println(e); // report index out of bound
{ }
}
// other exception
catch(ArithmeticException e)
{
System.out.println(e); // report arithmetic exception
}
// general exception
catch(ArrayException e) // catch exception
{
System.out.println(e); // report array exception
}
// always executed
finally
{
System.out.println("done!");
}
}
}
LESSON 14 EXERCISE 8
Type in the MyArrayTest and now test for the index out of bounds and create arrays of negative
sizes.
When you are deriving classes an overridden method cannot throw a exception greater then that
declared for the original method. A greater exception is the super exception class of a sub exception
class. Notice we have two hierarchies. The classes that you are defining and the exception classes
they are using. This means if a super class method throws a super class exception (SE) then a sub
class method can only through a super class exception (SE) or a sub class exception (SubE)
SE
super class super exception
method() class
SE
SubE
sub class
sub exception
method()
class
If a super class method throws a sub class exception then a sub class method that overrides the
super class method can only throw sub class exception (SubE) . The sub class method cannot throw
a super class exception.
SubE
sub class sub exception
method() class
We can derive a ExpandArray class from our Array class. The put method of the ExpandArray class is
overridden to expand the size of the array elements once it is filled up. We put an upper bound on
the array size and generate an ArrayFilledException if the upper bound is exceeded. Since the Array
put method throws an ArayIndexException the put method of the ExpandArray class cannot throw an
ArrayException it can only throw n ArrayFilledException or a ArrayIndexException.
ExpandArray class
Here is the code for the ExpandArray class. Notice the put method is declared to throw two
exceptions the ArrayFilledException and he ArrayIndexException. We need to declare the
ArrayIndexException in the ExpandArray constructor because we call the put method from the super
class.
LESSON 14 EXERCISE 9
Write the ExpandArrayTest class with the main method that tests the ExpandArray class. The catch
block should have the ArrayException, ArrayIndexException and the ArrayFilledException . Change
the put method of the MyArray class just to throw an ArrayIndexException and the put method() of
the expandable Array class to throw a ArrayException.. Repeat for ArrayIndexException and
ArrayFilledException. When a sub class method overrides a super class method the exceptions
thrown must be greater or equal to the exceptions thrown in the super class overridden method. The
UncompatibleException thrown message is generated in this situation by the compiler.
ArrayException
MyArray
class
ArrayIndexEception
Expandable
Array class
ArrayFilledException
IMPORTANT
You should use all the material in all the lessons to do the questions and exercises. If you do not
know how to do something or have to use additional books or references to do the questions or
exercises, please let us know immediately. We want to have all the required information in our
lessons. By letting us know we can add the required information to the lessons. The lessons are
updated on a daily bases. We call our lessons the "living lessons". Please let us keep our lessons
alive.
E-Mail all typos, unclear test, and additional information required to:
courses@cstutoring.com
students@cstutoring.com
http://www.cscourses.com/java.htm
this lesson is copyright (c) 1998-2006 by the computer science tutoring center "cstutoring"
this document is not to be copied or reproduced in any form. for use of student only.
File: JavaGuide15.doc
Write a base class that represents categories of items for sale. For each category make
derived classes like videos, computers, CD's. You need to figure out what is common about
the items. (Part number, description, quantity and price).
price 29.95
quantity 5
back order 0
You need to keep track of the quantity. Every time an item is bought the quantity lowers.
When the quantity is 0 then you need to back order more items. You need to figure out
what is unique about each category. (Sales tax, delivery charge, quantity discounts etc).
Each derived class should have a getPrice() method to calculate the final price.
StoreItem
videos cd's
computer
s
You need to make a Store class that will hold all the items for sale in one array of objects.
You can make the array to hold 100 items. The store class will have methods to add items,
remove items, buy items, search an item by part number, list items for sale by category
and report inventory levels.
Store class
array of
item
Make a menu that will enable someone to operate your store. Each menu may or may not
have a submenu.
Store
-------
(1) add item
(2) remove item
(3) buy item
(4) search for item
(5) list items for sale
(6) exit
array of
Customers
You will have the following classes. Put the main() function in the Store class.
class files:
Store.java
StoreItem.java
Video.java
CD.java
Computer.java
Customer.java
(3) Write each classes one at a time. Test each class one by one.
Each class should have its own main method()
(4) Once all clases are working separately then integrate the whole project
You should use all the material in all the lessons to do the questions and exercises. If you
do not know how to do something or have to use additional books or references to do the
questions or exercises, please let us know immediately. We want to have all the required
information in our lessons. By letting us know we can add the required information to the
lessons. The lessons are updated on a daily bases. We call our lessons the "living lessons".
Please let us keep our lessons alive.
E-Mail all typos, unclear test, and additional information required to:
courses@cstutoring.com
students@cstutoring.com
http://www.cscourses.com/javagui.htm
This lesson is copyright (C) 1998-2006 by The Computer Science Tutoring Center "cstutoring"
This document is not to be copied or reproduced in any form. For use of student only.