Java eBook

258
www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring 1 THE COMPUTER SCIENCE TUTORING CENTER www.cscourses.com JAVA PROGRAMMING COURSE E-BOOK Lesson 1 JAVA PROGRAMMING COMPONENTS AND VARIABLES Lesson 2 JAVA CLASSES AND REFERENCE VARIABLES Lesson 3 JAVA OPERATORS, BINARY NUMBERS AND CONDITIONS Lesson 4 JAVA STRING OBJECTS AND ARRAYS Lesson 5 JAVA METHODS Lesson 6 OBJECT ORIENTED PROGRAMMING Lesson 7 JAVA PROGRAMMING STATEMENTS Lesson 8 JAVA INPUT AND OUTPUT STREAM CLASSES Lesson 9 INHERITANCE AND ENCAPSULATION Lesson 10 POLYMORPHISM Lesson 11 JAVA CLASS COMPONENTS Lesson 12 ABSTRACT CLASSES AND INTERFACES Lesson 13 VECTORS , ENUMERATIONS AND ITERATORS Lesson 14 ARRAYLIST AND EXCEPTIONS Lesson 15 JAVA PROJECT 1

Transcript of Java eBook

Page 1: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

1

THE COMPUTER SCIENCE TUTORING CENTER

www.cscourses.com

JAVA PROGRAMMING COURSE E-BOOK

Lesson 1 JAVA PROGRAMMING COMPONENTS AND VARIABLES

Lesson 2 JAVA CLASSES AND REFERENCE VARIABLES

Lesson 3 JAVA OPERATORS, BINARY NUMBERS AND CONDITIONS

Lesson 4 JAVA STRING OBJECTS AND ARRAYS

Lesson 5 JAVA METHODS

Lesson 6 OBJECT ORIENTED PROGRAMMING

Lesson 7 JAVA PROGRAMMING STATEMENTS

Lesson 8 JAVA INPUT AND OUTPUT STREAM CLASSES

Lesson 9 INHERITANCE AND ENCAPSULATION

Lesson 10 POLYMORPHISM

Lesson 11 JAVA CLASS COMPONENTS

Lesson 12 ABSTRACT CLASSES AND INTERFACES

Lesson 13 VECTORS , ENUMERATIONS AND ITERATORS

Lesson 14 ARRAYLIST AND EXCEPTIONS

Lesson 15 JAVA PROJECT 1

Page 2: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

1

JAVA PROGRAMMERS GUIDE LESSON 1

File: JavaL1.doc

Date Started: July 12,1998

Last Update: Dec 28, 2005

Java Version: 1.5

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.

CLASS (definition)

Variables

Methods (Programming Statements)

OBJECT ( computer memory )

Data (storage for variables

Code to access data in object (what object does )

Page 3: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

2

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:

Title Author(s) Publisher Web page

Core Java Volume 1 Gary Cornell, Cay s. Horstmahn SunSoft Press http://www.horstmann.com/corejava.html

PURPOSE OF PROGRAMMING LANGUAGES

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.

LESSONS AND ASSIGNMENTS

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.

Send all solutions to assignments to [email protected] ($15 marking charge)

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 [email protected] for a quote (tutoring starts from $15)

Page 4: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

3

LESSON 1 JAVA PROGRAM COMPONENTS AND VARIABLES

JAVA PROGRAM FORMAT AND COMPONENTS

A Java program is made up programming components usually arranged in a predefined format. By following a proven format, your programs will be more organized and easier to read. A Java program contains packages, import statements, classes, and methods, programming statements, variables and operators. Packages are used to groups classes together that have something in common. Import statements are used to include system or user packages that contain classes that you may need for your program. A class declares and defines the variables and methods needed by an object. A class defines an object. Variables are used to store and retrieve data values. Methods are what the class object uses to perform the tasks it needs to do. Methods are made up of variables and programming statements. Programming statements are instructions used to direct the flow of program execution. Statements are made up of variables and operators. Operators perform operations on variables like addition and subtraction. Think that a Java program has many different layers each depending on each other: A Java program is an organized collection of components.

Comments describe what the

program does

Package (optional) contain classes

Import Statements include packages

Classes contain variables and

methods

Java Program

Class variables shared between all

methods in class

Variables

collection of Methods

Package collection of classes

group of Classes

Page 5: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

4

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.

package

class

variables

methods

Methods collection of statements

Temporary Variables

Programming Statements

Variables and

Operators

Programming Statements instructions telling the computer what to do

programming statements

temporary variables

and operators

Page 6: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

5

JDK (Java Development Kit)

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.

Program Translates Execution JDK (standalone)

Java source file --> compiler --> class execution file Running

*.java MyClass.java

JDK javac MyClass.java

*.class java MyClass

Web Browser (applet)

The typed in Java program that contains all the packages, classes variables and methods.

Translates the Java source code into execution byte code

Contains execution code (Byte Code) and reserved memory locations for data variables

The JDK calls the main or init method from the execution class file and the program runs

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.

Page 7: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

6

Compile time and run time

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 ?

additional memory requested by running program

memory allocated for objects when your program is

running

memory for OBJECTS

(always changing)

*.javatyped injava

program

*.class

class file created in compile time

class file loaded by JDK into your computer memory to run program (contains all class code)

memory reserved for your program when it is loaded

contains all class code and STATIC variables

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.

JAVA PROGRAM COMPONENTS

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.

Page 8: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

7

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

/* My first Java coment */

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.

Importing Java pre-built classes

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.*;

program using a package

package

class

class

class

class

a class in a program importing a package to use

a package contains many

classes

Page 9: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

8

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.

writing your own package

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.

importing your own package

You can also import your own packages. To use your own package you must also use the import statement.

import user_package_name .*;

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 package_name . class_name;

import student.Calculate;

Page 10: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

9

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.

visibility class class_name

{ variables methods }

// example class public class L1p1 { public static void main ( Strings[ ] args ) { System.out.println("hello"); }

}

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.

class visibility description

public means all other classes can access this class

friendly (default)

means only classes in the package or file can access this class (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.

class

method

method

main method

variables

access public classes file or package

public class

friendly class

friendly class

some other class in a different package

cannot access friendly classes

some other class in same package

can access friendly classes

Page 11: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

10

class name, variables and methods

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.

methods

variables

class visibility

public or friendly

Visibility is like a protection mechanism allowing only certain objects to enter

Page 12: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

11

// example class public class L1p1 { // main method public static void main ( String[ ] args )

{ System.out.println("hello"); }

}

Program output:

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:

System.out.println("hello"); // print "hello" on computer screen

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

class L1P1

main method

hello

Page 13: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

12

Compiling and running classes defined in packages

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;

// example class using packages public class L1p2 { // main method public static void main ( String[ ] args )

{ System.out.println("hello"); }

}

step 2: put the file L1p2.java in a subdirectory called student

step 3: compile the program in the parent directory

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.

java -classpath . student/L1p2

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.

Page 14: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

13

importing your own package

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

// example class public class L1p3

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

javac -classpath \student; L1p3.java

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.

java -classpath \student; L1p3

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.

L1p3 L1p2

main main

Page 15: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

14

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.

public class L1p1 { // main method public static void main ( String[ ] args )

{ 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

modifier return data _type

method name

parameter_type parameter_name

public static void main ( String[ ] args )

method visibility

Methods have visibility public, friendly and private.

method visibility description

public means all other classes can access this method

friendly (default)

can be accessed by classes in the same package or file(classes defined in the same file are 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.

access friendly method only if in same package

another class in a different package

access public methods

some public class

public method

friendly method

private method

cannot access private methods

some method

method

method

another class in same package

some method

method

method

Page 16: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

15

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 ?

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.

java myprogram myfile.dat

The argument "myfile.dat" will be placed into an array of Strings referred to by the parameter args.

(String[] args) array of strings receive

information from command line

void does not return

a value

command line arguments (optional) input values to main method

java Myclass myfile.dat

static placed in program

memory ready to be used

public everyone can

use this method

main name of

the method

args[0]

args[1]

args[2]

program memory loaded classes

object memory additional memory for objects

Class static variables static methods non static methods

Class Execution file

Page 17: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

16

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

java L1Ex2 tom

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.

character: 'A' numeric: 9 decimal: 10.5 character string: "hello"

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"

code description code description

\b backspace \0 end of string terminator

\n new line \\ backslash

\r carriage return \v vertical tab

\t horizontal tab \a bell

\" double quotation mark \o octal constant

\' single quotation mark \x hexadecimal constant

Hello Tom

Page 18: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

17

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.

Signed Positive numbers start with a 0. 0 1 1 0 1 0 0 1

Signed Negative numbers start with a 1 1 1 1 0 1 0 0 1

range of a signed number

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.

The range of a number is calculated for an 8 bit signed number where:

= = =

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 ?

0

127

(N-1) (N-1) - 2 to (2 - 1)

(8-1) (8-1) - 2 to 2 - 1

7 7 - 2 to 2 - 1 -128 to 127

-1

-128

The positive numbers start at 0 and end at 127

The negative numbers start at -1 and end at -128

Each has 128 numbers

N is the number of bits in the number. N=8

sign bit

Page 19: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

18

VARIABLES AND DATA TYPES

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.

Java data types signed range

type bytes N bits example - 2exp(N-1) to 2exp(N-1)-1

byte 1 8 45 -128 to 127

short 2 16 1234 -32,768 to 32,767

int 4 32 123467 -2147483648 to 2147483647

long 8 64 123456788 -2**63 to 2**63-1

float 4 32 34.56f +/- 3.40282347E+38

double 8 64 23.23333333 +/-1.79769313486231570E+308

char 2 16 'A' (unicode) 16 bit character set

boolean 1 8 true or false false true

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 number representation

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.

Page 20: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

19

1 8 23 32 bit floating point number (float)

sign bit exponent fraction (mantissa)

(-1)**sign * 2 exp (exponent-127)*(mantissa)

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

1 16 47 64 bit floating point number (double)

sign bit exponent fraction (mantissa)

(-1)**sign * 2 exp (exponent-127)*(mantissa)

- 12 .12365 1.2365 * 10 12

Declaring variables

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.

data_type variable_name; unititialized variables

int y; // declare variable y of data type int y U 0

char ch; // declare variable c of data type char. ch U '\0'

double d; // declare variable d of data type double d U 0.0

Variables store data

Page 21: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

20

You may declare more than one variable at a time if it is the same data type, by separating the variable names by commas.

data_type variable_name_list; unititialized variables

int i, j, k; // declare a variable's i , j and k having data type integer i U 0

j U 0

k U 0

declaring and initializing variables

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.

data_type variable_name = value;

int x = 5; // declare x and initialize to the value 5 x 5

double d = 10.5; // declare d and initialize to the value 10.5 d 10.5

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

int m=1, n=2, p=3; n 2

p 3

String Objects

Character strings are groups of letters enclosed by double quotes:

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

Page 22: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

21

You declare a String variable as follows:

String s; // declare variable s having a object type of String s U null

The String variable s will store the location of a String object. s is known as a reference to a string variable. Right now variable s does not refer to any String object and is undefined or null. A string variable in a method is undefined a string variable in a class definition gets the default value null. null means no known object location. The best thing to do is to declare a String variable and assign a String object to it. The String object will store the character string.

String s = "hello"; // declare and initialize s to "hello" s h e l l o

The String variable s does not contain the character string "hello" but contains the location where the string object is.

String s = "hello";

Assigning values to variables

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;

x = 3; // variable x gets the value of 3 x 3

y = x; // variable y gets the value of x which happens to be 3 y 3 (x)

ch = 'A'; // variable ch gets the character constant 'A' ch 'A'

s1 = "today"; // the String object s gets the character string "hello" s1 today

s

"hello"

A String is an object that stores a character string.

String Object

The variable s contains the location of the string object.

Page 23: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

22

Printing out variable values

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

To print out a variable value you just include the variable name.

System.out.println(x); // print a variable value to the screen

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.

hellohello hello

3

the value of x is: 3 join messages together

Page 24: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

23

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:

[email protected]

E-Mail all attached files of your completed exercises to:

[email protected]

Order your next lesson from

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

Page 25: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

1

JAVA PROGRAMMERS GUIDE LESSON 2

File: JavaL2.doc

Date Started: July 12,1998

Last Update: Dec 28, 2005

Java Version: 1.5

LESSON 2 CLASSES AND OBJECTS

CLASSES, CONSTRUCTORS AND INSTANCES

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.

class definition

P1 P4

many objects made from the same class definition

P2 P3

Page 26: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

2

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 { private String name; // name of person // constructor to initialize variable name public Person(String name) { 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.

visibility class_name(paramater_type paramater_identifier);

public Person(String name)

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.

// initializing constructor public Person(String name)

{ this.name = name; }

Person Class

Variables

Constructor

Constructors are used to initialize variables defined in the class when the object is created

this

the this reference refers to the class you are defining or the presently executing object.

Page 27: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

3

default constructor

A default constructor initializes the variables defined in a class with default values.

// default constructor public Person()

{ name = "Ed"; }

classes without constructors

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 { String name = "Ed"; // name of person }

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.

declaring a reference to a object

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

int x; // declare a variable

Person Class

Variables

There are two ways to initialize the variables defined in a class

1. in a constructor

2. when the variables are declared

A default constructor initializes the variables defined in a class with default values.

this

Page 28: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

4

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;

Person p; // declare a reference to Person object p p U null

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.

creating an instance of a class

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.

data_type variable_name = value;

int x = 5;

Except the value is the location of an object.

object_reference = new class constructor(argument_list);

p = new Person("Tom"); // create Person object assign to p

object reference

allocate memory for object

call constructor

values passed to constructor

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.

p

Person object

object reference

x 5

Tom

Page 29: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

5

It is always a two step process to create an object.

(1) declare an object reference Person p; // declare reference variable p

(2) create an instance of the class, assign the created Person objects location to the object reference p

p = new Person("Tom"); // assign Person object to 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.

object_type object_name = new class constructor_name(argument_list);

Person p1 = new Person("Tom");

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.

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.

// create vanilla cake Cake c1 = new Cake("vanilla");

// create chocolate cake Cake c2 = new Cake("chocolate");

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.

Person p = new Person ("Tom");

p1 Tom

p2 Ed

c1 vanilla

c2 chocolate

object variable and

type

allocate memory for object using

new operator

program calls

constructor

constructor initializes variables belonging to

the object

Page 30: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

6

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.

Tom

Person object's String object's (declared in Person class)

name

name

Person class

main method (static)

p1

p2

"Tom"

"Ed"

static variables and methods means permanent memory initialized at load time.

What is the difference between the Person class and a Person object?

Person object references

An object is allocated memory for variables defined in the class definition.

Page 31: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

7

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 a string representation of the object public String toString()

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

System.out.println(p1); // print out string representation of this object

or if you like typing so much then you can use the object name, the dot operator and the toString method name.

System.out.println(p1.toString()) // print out string representation of this object

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 { private String name; // name of person

// default constructor public Person() { this.name="Ed"; // initialize variable name to "Ed" }

a class may have more than 1 constructor this is called overloading

Page 32: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

8

// initializing constructor public Person(String name) { this.name = name; // assign user value to variable name }

// main method to create Person Objects public static void main ( String[ ] args )

{ Person p1 = new Person(); System.out.println(p1); Person p2 = new Person("Tom"); System.out.println(p2); }

// return a string representation of this object public String toString()

{ return "my name is: " + name; }

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.

my name is: Ed

my name is: Tom

program output:

Ed

Tom

p1

p2

Page 33: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

9

LESSON 2 QUESTION 1

1. What is the difference between a class and an object. 2. What is an object ? 3. What is the difference between a data type and an object type ? 4. What is a Constructor and what does it do ? Give an example using a constructor. 5. Do we always need a Constructor ? 6. What is the new operator used for ? 7. What is meant by "an instance of a class " ? 8. What is a main method used for ? 9 Who calls the main method ? 10. What does a toString method do? 11. How do you call a toString method ? 12. What is the difference between an object type and an object reference ?

class components

A class list all the variables and methods for a object. A class is defined as follows:

visibility class name {

variables // store and retrieve data for the class

final variables // variables once initialized the value cannot change (read only)

static variables // shared variables between all instances of this class

constructor(s) // initialize and allocate memory for variables

methods // contains programming statements

main method // creates i/o streams, creates classes and call's class methods

toString method // string representation of this object

}

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.

Page 34: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

10

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.

visibility data_type variable_name

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 variables accessed by all classes

friendly variables accessed by classes in same package levels of visibility for

variables declared in a class private variables only accessed by this class

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)

private variables M

M M

M

M M

private variables M

M M

M

M M Exchange data

through methods

access public variables public class

public variable

friendly variable

private variable

some other class different package

cannot access private variables

some other class same package

CLASS A CLASS B

Page 35: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

11

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.

variables in a method (temporary)

variables in a class (permanent)

variables are temporary and are only known to

method cannot be declared as public or

private (local)

variables known to all methods in class. Variables

known to other classes depends on visibility (private or public)

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 data_type variable_name = constant;

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

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.

One static variable is shared between all objects

class

Methods

variables shared by all Methods

Page 36: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

12

To declare a static variable:

static data_type variable_name;

static int num=0; // declare static variable num

Each object may have it’s own same name instance variablebut there is only one staric 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.

static int num=0; // declare static variable num

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.

num = 5; // assign 5 to static variable num declared in class Person int x = num; // assign to x the value of the static variable num.

What is the value of x ?

access inside class

What is the difference between a static variable and an instance variable ? What is another name for a static variable ?

program memory class loaded into, memory:

static variable

Code for method

Object Instance Variable

Object Instance Variable

Object Instance Variable

Page 37: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

13

When accessing a static variable outside the class definition, you must use the class name not the instance name or object reference name.

class_name . static_variable_name

Person.num = 5; // assign 5 to static variable num declared in class Person int x = Person.num; // assign to x the value of the static variable num.

What is the value of x ?

Here is the person class defined with a static variable:

// 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) { this.name = name; num = num + 1; }

// main method public static void main ( String[ ] args )

{ Person p1 = new Person(); System.out.println(p1); Person p2 = new Person("Tom"); System.out.println(p2); }

// return a string representation of this object public String toString()

{ return "my name is: " + name + " there are " + num + " persons"); } }

my name is: Ed there are 1 persons

my name is: Tom there are 2 persons program output:

Ed

Tom

main:

p1

num

p2

class Person (static) Person

Objects

access outside class

Page 38: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

14

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.

int x; // declare an integer variable x

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;

String s2; // declare a unutilized reference to a String object s2 U null

If you try to access a reference variable and it does not refer to an object, then you will get an runtime unitialized variable exception. An exception is a condition that stops your program from running. It occurs when an error is detected while your program is running. Java is kind, most other languages will crash your computer. Java keeps track of all runtime errors for you automatically by means of exceptions and kindly tells you about them. The reference variable refers to an objects location in computer memory.

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 s3 = null; // reference variable refers to no object s3 null

For Strings some people assign the empty string to it.

String s4 = "" ; // reference variable refers to string object that is empty s4 ""

What is the difference between s3 and s4 ?

s3 does not refer to any object where s4 refers to a string object that is empty.

s3 null s4 ""

Page 39: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

15

You are used to assigning string objects to references as follows:

String s5 = "Hello"; // declare and initialize a string object s5 "Hello"

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.

assigning object references to other object references

Existing objects may be assigned to other object reference variables. Let's make another string object called s6.

String s6 = "Goodbye"; // declare and initialize a string object s6 "Goodbye"

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

goodbye // both s5 and s6 refer to "goodbye"

s5 = s6;

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:

System.out.println("Lesson 2 Exercise 1"); // print a message to screen System.out.println("x = " + x); // print a message and a value System.out.println("s1 = " + s1); // print a message and a object value

Page 40: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

16

1. Declare an integer variable x and assign the value of 5 to it 2. What is the value of x ? 3. Declare an integer variable y and assign the value of x to it.. 4. What is the value of y ? 5. Declare a String object reference s1. 6. Assign the string "hello" to s1. 7. Declare a String object reference s2 and assign the String object reference s1 to it. 8. Assign the character string "world" to s1. 9. What is the value of s1 ? 10. What is the value of s2 ? 11. Why does s1 and s2 have different character strings ?

EXAMPLE USING DIFFERENT TYPES OF VARIABLES DEFINED IN A CLASS

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.

object_type object_name = new class_constructor;

L2p1 test = new L2p1(); // create a L1p2 object assign to test

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.

object_name . variable_name = expression;

test.name = "Hello"; // access variable name belonging to object test "hello"

The ". " dot operator states the variable name belongs to the object referred by test.

Here is the example class L2p1

// public class public class L2p1

{ public final int Max = 5; // final variable public String name; // public variable reference private int count; // private variable

private static int Num=0; // static variable

Page 41: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

17

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

}

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.

Hello 5 0

object memory

object L2p1

Max: 5 name: Hello count: 0

class memory

class L2p1

Num: 0

Main test x: 5

Program Output:

Page 42: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

18

location name modifier value type

@xxxx Max final 5 int

name public Ed String objects

Computer

Data

Memory count private 0 int

main test reference @xxxx L2P1

x variable 5 int static

Computer

Program

Memory L2p1 Num static 0 int

LESSON 2 EXERCISE 5

Make a memory model for your Person class, instantiate at least 2 Person objects in your main method.

Page 43: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

19

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:

[email protected]

E-Mail all attached files of your completed exercises to:

[email protected]

Order your next lesson from

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.

Page 44: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

1

JAVA PROGRAMMERS GUIDE LESSON 3

File: JavaL3.doc

Date Started: July 12,1998

Last Update: Dec 28, 2005

Java Version 1.5

LESSON 3 JAVA OPERATORS, BINARY NUMBERS AND CONDITIONS

OPERATORS

Operators are symbols that are used to do operations on variables. The operations may be adding or comparing the values of variables. etc.

operand operator operand

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.

variable = operand operator operand;

x = x + 5; // assign to x the value of x plus 5

arithmetic operators

You are already familiar with arithmetic operators + - * / %(mod) Evaluate the following for x = 10; y = 5;

+ addition x = x + 5; 15

- subtraction x = x – 5; 5

* multiplication x = x * y; 50

*/ division x = x / 5; 2

% modulus (remainder) x = x % y; 0

expression

To find the modulus of a number: you multiply the remainder after division by the denominator.

For example: 13 mod 12 is 13/12 = 1.0833333... Multiply remainder by denominator 0.0833333.. * 12 = 1 (13 mod 12) = 1 or continually subtract 13-12 = 1

3 9

11 12 1 (13)

6

(15)

Page 45: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

2

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.

INCREMENT AND DECREMENT OPERATORS

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.

increment after y++ x = y++; x gets value of y then y increments by 1 x = y; y = y + 1; ++

increment before ++y x = ++y; y increments by 1 and then x gets value of y y = y + 1; x = y;

decrement after y - - x = y - -; x gets value of y then y decrements by 1 x = y; y = y - 1; - -

decrement before - - y x = - - y; y decrements by 1 and then x gets value of y y = y - 1; x = y;

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.

Page 46: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

3

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)

(expression relational operator

expression)

( x > 5)

The test condition is evaluated as true or false. Evaluate the following for x = 5; y = 5;

> greater than (x > 5) false

>= greater than or equal (x >= 5) true

< less than (x < y) false

<= less than or equal (x <= y) true

You can print to the screen the value of a test condition. It will say true or 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";

= = compares if equal (x == 5) true

! = is not equal (x != 5) false

instanceof test if an variable is an instance of a class

(s instanceof String) true

false

Page 47: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

4

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.

What is the difference between x = 5; and (x == 5) ?

x = 5; assigns the numeric value 5 to the variable x.

(x==5) tests if x is equal to the value of 5.

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.

((condition) logical operator (condition))

((x == 5) && (x != y))

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

| | logical OR either ( (x == 5) | | (x != y) ) test if x is equal to 5 or x is not equal to y true

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.

Page 48: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

5

BINARY AND HECXADECIMAL NUMBERS

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

binary (base 2)

hexadecimal (base 16)

decimal (base 10)

binary (base 2)

hexadecimal (base 16)

decimal (base 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

Page 49: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

6

converting from binary base 2 to decimal base 10

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

power of 2 2 exp 3 2 exp 2 2 exp 1 2 exp 0

weight 8 4 2 1

binary number 1 0 1 1

multiply bit by power 1* 8 0 * 4 1 * 2 1 * 1

add up result 8 + 0 + 2 + 1 = 11

Convert the binary number 1101 to a Decimal number

converting from decimal base 10 to binary base 2

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.

rem base ans

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

Convert decimal number 13 to its binary number equivalent

Page 50: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

7

bit wise operators and truth table

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.

bit wise operator purpose truth table

& bitwise AND clear bits to zero 0 & 0 = 0 0 & 1 = 0 1 & 0 = 0 1 & 1 = 1

| bitwise inclusive OR set bits to one 0 | 0 = 0 0 | 1 = 1 1 | 0 = 1 1 | 1 = 1

^ bitwise exclusive XOR clear/set bits 0 ^ 0 = 0 0 ^ 1 = 1 1 ^ 0 = 1 1 ^ 1 = 0

~ one's complement toggle bits ~0 = 1 ~1 = 0

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.

AND OR XOR complement

1011 1011 1011

& 0001 | 0001 ^ 0001 ~1011

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 ?

Page 51: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

8

Example using bit wise & operator to test if a number is even or odd :

((num & 0x01) ==1) // x means hexadecimal

((num % 2) ==0) // take mod 2 of number

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.

testing if a number is even or odd

Example using bit wise & operator to test if a number is even or odd:

int result = (num & 0x01); // x means hexadecimal

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.

int result = ((num % 2)==0); // x means hexadecimal

encryption and decryption using xor

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

Shift operators let you multiply or divide by powers of 2. There are three types of shift operators:

(1) left shift << x = x << N; // shift x left by N bits multiply by 2n

(2) right shift >> x = x >> N; // shift x right by N bits divide by 2n

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

Page 52: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

9

shifting bits left << (multiply by powers of 2)

variable = variable << N;

x = x << 1; // shift x left by 1 bit multiply x by 2 ( 21 = 2)

x = x << 2; // shift x left by 2 bits multiply x by 4 (24 = 4)

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.

before after

0101 (5) 1010 (10)

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!

class ShiftLeft { /* shift number left */ public static void main(String[] args) { int x = 5; System.out.println(x); x = x << 1; System.out.println(x); } }

Try shifting 0011 left by 1 bit. What happens when you shift a signed negative number left ?

signed shift bits right >> (divide by powers of 2 )

variable = variable >> N;

x = x >> 1; // shift x right by 1 bit

x = x >> 2; // shift x right by 2 bit s

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.

2 N

2 N

add an extra 0 here

this bit will get lost

5 10

program output:

when you shift bits left add a zero to right side

Page 53: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

10

positive number signed shift right

before after

0101 (5) 0010 (2)

negative number signed shift right

before after

1011 (-5) 1101 (-3)

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

Here is an example program to shift positive and negative numbers right.

/* shift positive number right */ class ShiftRight { public static void main(String[] args) { int x = 5; System.out.println(x); x = x >> 1; System.out.println(x);;

/* shift negative number right */ int x = -5; System.out.println(x); x = x >> 1; System.out.println(x); }

remove bit

positive sign bit

5 2

-5 -3

remove bit

negative sign bit

The bit on the left is known as the sign bit.

add sign bit (0)

add sign bit (1)

If the number is positive the sign bit is a 0

The bit on the left is known as the sign bit.

If the number is negative the sign bit is a 1

Page 54: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

11

Try shifting 0110 right by 1 bit Try shifting 1110 signed right by 1 bit Try shifting 1111 signed right by 1 bit

unsigned shift right >>> (divide by powers of 2 )

Unsigned numbers are always positive. The MSB can be 0 or 1. If you shift right an unsigned number then the left most added bit would always be 0. Example shift 0101 left by 1 bit. Blue represents the sign bit. Red represents the right most bit that will be lost when we shift right. Green represents the shifted bits and violet represents the signed extended bit after we shift right.

msb = 0 unsigned shift right

msb = 1 unsigned shift right

before after before after

0101 (5) 0010 (2) 1011 (11) 0101 (5)

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) { /* shift unsigned number right */ int x = -5; System.out.println(x); x = x >>> 1; System.out.println(x); } }

Try shifting 1110 unsigned right by 1 bit

remove bit

msb is 0

remove bit

negative sign bit

2 N

65531 (-5) 32765

add 0 bit

add 0 bit

Page 55: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

12

representing signed numbers

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

-2**(N-1) to 2**(N-1)-1 out range is -2 ** 3 to 2 **3 -1 = -8 to 7

-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 = 8 11111011 byte -5

N = 16 1111111111111011 short -5

converting to/from negative binary numbers

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.

Convert 5 to negative -5 to positive 3 to negative -3 to positive

number 0101 (5) 1011 (-5) 0011 (3) 1101 (-3)

1's complement 1010 (-6) 0100 (4) 1100 (-4) 0010 (2)

add 1 0001 0001 0001 0001

result 1011 (-5) 0101 (5)

1101 (-3) 0011 (3)

Why does 1011 represent -5 for a 4 bit binary number ? For the signed right shift why is the answer (-3) rather than (-2) ? For the unsigned shift right why is the answer 5 ?

Page 56: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

13

LESSON 3 QUESTION 3

Fill in the boxes.

shift left signed shift right

unsigned shift right

1011 << 1 1011 >> 1 1011 >>>1

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;

&= x &= 5; x = x & 5; |= x |= 5; x = x | 5; >>>= x >>>= 2 x = x >>> 2

<<= x <<= 2; x = x << 2;

>>= x>>=2 x = x >> 2;

Page 57: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

14

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.

Examples forcing precedence and using precedence are as follows

int a=1, b=2, c=3, d=4;. x = a + b * c + d; // Which operations are done first ? // b * c then + a + b //

What is the value of x ?

x = (a+b) * (c + d); // Which operations are done first ? // a + b then c + d then //

What is the value of x ?

precedence table:

operator level associativity operator level associativity

[ ] . (method call) ( ) 1 (high) left to right & 8 left to right

! ~ ++ -- (cast) 2 right to left ^ 9 left to right

* / % 3 left to right | 10 left to right

+ - 4 left to right && 11 left to right

<< >> >>> 5 left to right || 12 left to right

< <= > >= instanceof 6 left to right ?: 13 left to right

= = != 7 left to right , 15 left to right

= += -= *= /= %= &= |= ^= <<= >>= >>>= 14 (low) right to left

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.

Page 58: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

15

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.

definition one statement

more than one statements

if(expression)

true statements

if (x==0)

y = x;

if (x==0)

{ y = x; x=x+1; }

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

else

false statements

if (x==0)

{ y = x; x=x+y; }

else

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

(condition) ? true expression : false expression;

int y = (x == 5) ? x+1 : x-1;

This means if x is equal to 5 assign x + 1 to y else assign x - 1 to y.

if(x == 5) y = x + 1;

else y = x - 1;

if(x == 0)

y = x;

T

F

if(x==0)

x = 1; y = x; x = x + y;

T F

? if

: else

Skips statements if condition false

Page 59: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

16

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.

Typecasting and Assignment Conversion

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.

char

int long float double

byte short

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

char

double float long int

short byte

It is possible to force a double to be an int by type casting

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.

int

double

double

int

Page 60: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

17

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.

byte b = -64; byte -64 11000000

b >>> 4; convert to int -64 11111111 11111111 11111111 11000000

shift unsigned 4 bits 2684435452 00001111 11111111 11111111 11111100

(byte) b >>> 4 convert to byte -4 11111100

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.

The following example demonstrates arithmetic promotion.

s * i >= f / d

int double

int double

double

boolean

LESSON 3 EXERCISE 9

Write a program to solve the error only by type casting.

byte b = 5;

b = b * b;

Call your class and program L3ex9.java.

byte

byte b = -64;

-64

int

b >>> 4;

2684435452

byte

(byte) b >>> 4

-4

Page 61: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

18

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:

[email protected]

E-Mail all attached files of your completed exercises to:

[email protected]

Order your next Lesson from :

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.

Page 62: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

1

JAVA PROGRAMMERS GUIDE LESSON 4

File: JavaL4.doc

Date Started: July 12,1998

Last Update: Dec 28, 2005

Java Version: 1.5

LESSON 4 JAVA STRING OBJECTS and ARRAYS

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;

String s; // declare a String variable s U null

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

String s = null; // declare an object variable to a string object s null

You may want to assign an empty string object to your String reference. A String object is created from the empty string.

object type object name = string;

String s = ""; // declare and assign an empty s " "

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:

s ="hello"; // declare and assign a string object s "hello"

The String object is created by the compiler and the String object location is assigned to the String variable s.

Page 63: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

2

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.

s = s + "goodbye"; // join two strings together s "hellogoodbye"

using String methods

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

int len = s.length(); // assign length of string to len

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:

String s2 = s.substring(0,6); // get the first 5 characters from s2

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.

Testing if two strings are equal

Let's say you have 2 strings:

String s1 = "Hello". // assign "Hello" to s1 s1 --> "Hello"

String s2 = "Goodbye"; // assign "Goodbye to s2 s2 --> "Goodbye"

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 object. We are testing if both string references refer to the same String Object location.

(s1 == s2) test location

joining operator new String object

Page 64: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

3

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.

String s1 = "Hello";

String s2 = "Hello";

String references s1 and s2 now refer to the same String object.

creating String objects in run time.

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.

String s1 = new String("Hello");

String s2 = 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

(1) different data contents different locations

String s1 ="Hello"; s1 "Hello" data location

(s1.equals(s2)) (s1 == s2)

String s2 ="Goodbye"; s2 "Goodbye" false false

"Hello"

s1

s2

"Hello"

"Hello"

s1

s2

Page 65: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

4

(2) same data contents same locations

Now let assign "Hello" to s2, notice the data contents are the same but the locations are same

String s1 ="Hello"; s1 data location

"Hello" (s1.equals(s2)) (s1 == s2)

String s2 ="Hello"; s2 true true

(3) same data contents different locations

Now let assign "Hello" to s2, notice the data contents are the same but the locations are different.

String s1 = new String("Hello"); s1 "Hello" data location

(s1.equals(s2)) (s1 == s2)

String s2 = new String("Hello"); s2 "Hello" true false

(4) same location obviously same data contents

Now let assign s2 to s1, s1 = s2; notice the data contents are the same and the locations are the same

s1 data location

"Hello" (s1.equals(s2)) (s1 == s2)

s2 true true

What happen to the String object pointed to by s1 ?

What is the difference between s1 = s2 and s1 = = s2 ?

using String class

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 System.out.println("s1: " + s1 + " s2: "+ s2); // print out s1 and s2

s1: Hello s2: Goodbye

Page 66: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

5

if(s1.equals(s2))System.out.println("s1 is equal to s2"); // test if s1 equal to s2 else System.out.println("s1 is not equal to s2"); if(s1==s2)System.out.println("s1 == s2"); // test if s1 same location s2 else System.out.println("s1 != s2");

// case 2: same data contents same locations s2 = "Hello"; // assign "Hello" to s1 System.out.println("s1: "+ s1 +" s2: " + s2); // print out s1 and s2

if(s1.equals(s2)) System.out.println("s1 is equal to s2"); // test if s1 equal to s2 else System.out.println("s1 is equal to s2"); if(s1==s2)System.out.println("s1 == s2"); // test if s1 == to s2 else System.out.println("s1 != s2");

// case 3: same data contents different locations s1 = new String("Hello").; // assign "Hello" to s1 s2 = new String("Hello"); // assign "Hello to s2 System.out.println("s1: " + s1 + " s2: "+ s2); // print out s1 and s2

if(s1.equals(s2))System.out.println("s1 is equal to s2"); // test if s1 equal to s2 else System.out.println("s1 is not equal to s2"); if(s1==s2)System.out.println("s1 == s2"); // test if s1 same location s2 else System.out.println("s1 != s2");

// case 4: same locations obviously same data contents s1 = s2; // assign string object referred to by s1 to string variable s2 System.out.println("s1: "+ s1 + " s2: " + s2); // print out s1 and s2

if(s1.equals(s2)) System.out.println("s1 is equal to s2"); // test if s1 equal to s2 else System.out.println("s1 is not equal to s2"); if(s1==s2)System.out.println("s1 == s2"); // test if s1 == to s2 else System.out.println("s1 != s2"); }

} common String class methods

The following chart lists some common String class methods and examples in how to use them:

Declare a String object reference variable String s3; s3 U

Declare and initialize a String object reference String s4 = "Hello"; s4 "Hello"

Assign the String object s3 to s4 s3 = s4; s3 "Hello"

Join to strings together s3 = s3 + s4; s3 "HelloHello"

Get length of string int len = s3.length(); len 10

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

s1 is not equal to s2 s1 != s2

s1: Hello s2: Hello

s1 is equal to s2

s1 == s2

s1: Hello s2: Hello

s1 is equal to s2

s1 != s2

s1: Hello s2: Hello

s1 is equal to s2

s1 == s2

Page 67: Java eBook

www.cstutoring.com E-Learning, E -Books, Computer Programming Lessons and Tutoring

6

What happens if you assign s3 to s4 from the Strings in the above chart ?

s4 = s3; // Both s3 and s4 refer to the same string object

s3 s3.equals (s4) ; // test if the data is equal true

s4 "HelloHello"

(s3 == s4); // tests if refer to same string object true

What happens if you assign "HelloHello" to s4 ?

s4 = "HelloHello"; // s3 and s4 refer to separate string objects

s3 "HelloHello" s3.equals (s4) ; // test if the data is equal true

s4 "HelloHello" (s3 == s4); // tests if refer to same string object false

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

1. Declare 2 String references s1 and s2 initialized to your favorite words.

2. Assign s1 to a String reference variable called s3

3. Test if s1 and s3 have the same data contents

4. Test if s1 and s3 have the same location

5. Assign s2 to s1

6. Test if s2 and s3 have the same data contents

7. Test if s2 and s3 have the same location

Page 68: Java eBook

www.cstutoring.com E-Learning, E -Books, Computer Programming Lessons and Tutoring

7

ARRAYS

ONE DIMENSIONAL ARRAYS

An array is a group of consecutive same data types or object types sequentially allocated in memory and accessed by a common name.

int int int int int

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.

temperature 33 37.5 38.2 36 35.4

using arrays

To use an array object in Java you first must:

(1) Declare an array reference variable that refers to an Array object.

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

int[] a; // declare an array variable a U a null

You may want to assign null to a1 when you declare it to indicate it does not refer to any object yet.

int[] a=null; // declare an array variable a null

allocating memory for a one dimensional array object

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.

array_name = new data_type [size_of_array];

a = new int[5]; // allocate memory for 5 integers

Page 69: Java eBook

www.cstutoring.com E-Learning, E -Books, Computer Programming Lessons and Tutoring

8

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.

col 0 col 1 col 2 col 3 col 4

a1 -----> int int int int int

0 0 0 0 0

It is always a 2 step process using arrays

(1) declare an array variable: int[] a;

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

data_type[ ] array_name = new data_type [size_of_array];

int[] a = new int [5] // declare an array variable and allocate 5 integers

accessing array elements .

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]

To store a value at an array element at a specified index:

array_name[index] = expression;

a[2] = 5; // array element at index 2 gets the value 5

a[0] a[1] a[2] a[3] a[4]

0 0 5 0 0

assigning: (1) Go to array (2) give a value to the array element at the specified index

array elements are initialized to zero for primitive data types and

to null for object types.

Page 70: Java eBook

www.cstutoring.com E-Learning, E -Books, Computer Programming Lessons and Tutoring

9

To read a value at an array element at a specified index:

variable = array_variable[index] ;

x = a[2]; // variable x will get array value at index 2

What is the value of x ?

variable array indexes

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

It should be obvious that this is equivalent to:

x = a[2]; // v gets the value of array location at column index 1

What is the value of x ? 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.

assigning arrays to other arrays

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.

int[ ] a2 = a; // array a2 refers to location of array a1

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.

x = a2[2]; // integer variable x will get the value of array a2 at index 2

x = a[2]; // integer variable x will get the value of array a at index 2

What would be the value of x in both cases ?

reading: (1) Go to array (2) get array element value at index and give to variable

Page 71: Java eBook

www.cstutoring.com E-Learning, E -Books, Computer Programming Lessons and Tutoring

10

Testing if 2 arrays are equal

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

If you use the equals method :

if(a.equals(a2))

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.

Size of one dimensional arrays

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

What is the value of the variable len ? One dimensional array of objects

You can create a 1 dimensional array of object reference variables. First step is to make an array of object reference.

String[] a3 = new String[2]; // allocate memory for 2 String variables

Array a3 will be an array of string object reference variables, each element initialized to null.

a3 ------> String reference String reference

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

a3 -----> a3[0] a3[1]

"hello" "goodbye"

You can retrieve the String object also from your array of string variables.

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.

What is the value of s ?

Each element refer's to a String object. The location of the string objects are stored in the array.

Test if 2 array objects refer to the same location

Test if 2 array objects refer to the same location not data contents

length of one dimensional array

a.length

s

Page 72: Java eBook

www.cstutoring.com E-Learning, E -Books, Computer Programming Lessons and Tutoring

11

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.

An Example would be: System.out.println(a1[a2[0]]);

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.

TWO DIMENSIONAL ARRAYS

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;

int[ ][ ] b; // declare a variable to a 2 dimensional array

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.

array_variable = new data_type [number of rows][number of columns];

b = new int[3][4]; // allocate memory for a 2-D array

You may combine the above two steps into one:

data_type [ ][ ] array_variable = new data_type [number of rows][number of columns];

int[ ][ ] b = new int[3][4]; // declare and allocate memory for a 2-D array

col 0 col 1 col 2 col 3

b ---> Row 0

int int int int

Row 1

int int int int

Row 2

int int int int

A two dimensional array of integers is created having 3 rows and 4 columns All rows a nd columns refers to indexes starting at zero

b has the location of the 2 dimensional Array Object

number of rows

number of columns

Page 73: Java eBook

www.cstutoring.com E-Learning, E -Books, Computer Programming Lessons and Tutoring

12

accessing elements of 2 dimensional arrays

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.

array name [row_index][column_ index] col 0 Col 1 col 2 col 3

b[1][2] b ---> row 0 b[0][0] b[0][1] b[0][2] b[0][3]

row 1 b[1][0] b[1][1] b[1][2] b[1][3]

which row which column row 2 b[2][0] b[2][1] b[2][2] b[2][3]

To write a value to a two dimensional array you must specify the row and column index.

array_variable_name[row index][column_index] = expression;

b [1][2] = 5; // write a value to array at location row 1 column 2

Can you find the 5 ?

col 0 col 1 col 2 col 3

b -----> row 0 0 0 0 0

row 1 0 0 5 0

row 2 0 0 0 0

To read a value from a two dimensional array:

variable = array_variable_name[row index][column_index];

x = b[1][2]; // get the array value at location row 0 column 3 What is the value of x ?

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.

assigning: (1) Go to array (2) give a value to the array element at the specified row and column index

reading: (1)Go to array (2) get element value at row and column index and give to variable

Page 74: Java eBook

www.cstutoring.com E-Learning, E -Books, Computer Programming Lessons and Tutoring

13

2 dimensional arrays of object reference variables

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.

String[][] b2 = new String[2][2]; // declare a 2 by 2 two dimensional array of strings

b2 ---> col 0 col 1 col 0 col 1

row 0 b2[0] b[0][0] b[0][1] row 0 reference to a string object

reference to a string object

row 1 b2[1] b[1][0] b[1][1] row 1 reference to a string object

reference to a string object

The next step is to assign objects to the array reference variables.

b2[0][1] = "Hello";

b2[1][1] = "Goodbye";

col 0 col 1

b2 -------> row 0 b2[0] reference to string object

reference to string object

row 1 b2[1] reference to string object

reference to string object

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.

referring to an array row

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.

b2[0] refers to row 0 b2[1] refers to row 1

"hello"

"goodbye"

Page 75: Java eBook

www.cstutoring.com E-Learning, E -Books, Computer Programming Lessons and Tutoring

14

Array reference r refers to the first row of array b2.

String [] r = b2[0]; // r refers to a array of String variables at row index 0

r[0] r[1]

r ---> b2[0] variable variable

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

r[1] = new String("hello"); // assigns a value to array at location row 0 column 1 String s = r[1]; // get the value of array at location row 0 column 1

What does s refer to ? What is the difference between a String[ ] and a String ?

What is the value of s ? col 0 col 1

b2 -------> row 0 b2[0] reference to string object

reference to string object

row 1 b2[1] reference to string object

reference to string object

using variables as indices in 2 dimensional arrays

You can also use variable indexes to access elements of a 2 dimensional array.

i = 1; j = 2; // set i and j to any location to access x = b2[i][j]; // x gets the value of array location row index i column index j

It should be obvious that this is equivalent to:

x = b2[1][2]; // x gets the value of array location row index 1 column index 2

Size of two dimensional arrays

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

What is the value of rowSize ?

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

What is the value of colSize ?

"hello"

"goodbye"

specifies which row

r[0] r[1] A row of a two dimensional array is actually a 1 dimensional array

Page 76: Java eBook

www.cstutoring.com E-Learning, E -Books, Computer Programming Lessons and Tutoring

15

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:

System.out.println(b[0][0] + " " + b[1][0]); System.out.println(b[0][1] + " " + b[1][1]); System.out.println(b[0][2] + " " + b[1][2]);

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:

int [ ] a4 = {10,12,34,21,24}; a4 ----> 10 12 34 21 24

To declare and initialize a 2 dimensional array of size 3 by 4 integer elements:

45 46 23 29

56 23 76 52

int [ ][ ] b3 = {{45,46,23,29},{56,23,76,52},{12,45,32,26}}; b3 ---->

Notice that additional groups of curly brackets are needed to group individual rows. If you do not include the curly brackets around each row, you will get the partially bracketed warning message from the compiler. 10 12 34 21

initializing arrays of String objects You can even initialize a 1 dimensional array to hold references to String objects.

String a4[ ] = {"hello","goodbye"}; // 1 dimensional array a4

"hello" "goodbye"

Page 77: Java eBook

www.cstutoring.com E-Learning, E -Books, Computer Programming Lessons and Tutoring

16

And initialize a 2 dimensional array to hold references to String objects.

String b5[ ][ ] = {{"hello","goodbye"},{"tomorrow","today"}}; b3

// 2 dimensional array of String objects

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.

Object[] objs = {"Hello", {"Goodbye","Hello"}}; // array of objects

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)

object_type object_reference = (type cast) original_object_reference;

String s = (String)objs[0]; // type cast to string variable

String [] strs = (String[])objs[1]); // typecast to string array

Using incrementers and decrementers with Arrays

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.

operation description step 1 step 2

x = a [i++]; post increment array index i by 1 after the assignment x = a [i]; i = i + 1;

x = a [++i]; pre increment array index i by 1 before the assignment i = i + 1; x = a [i];

x = a [i--]; post decrement array index i by 1 after the assignment x = a [i]; i = i - 1;

x = a [--i]; pre decrement array index i by 1 before the assignment i = i - 1; x = a [i];

"tomorrow"

"goodbye"

"today"

"hello"

Page 78: Java eBook

www.cstutoring.com E-Learning, E -Books, Computer Programming Lessons and Tutoring

17

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.

statement i before assignment

x = a[i] i after assignment

x = a [i++]; 2

x = a [++i];

x = a [i--];

x = a [--i];

Using array an element as a variables (optional material)

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.

int[] a5 = new int[1]; // declare an array of 1 integer data type

You next assign a value to the 1 dimensional element array and put a value into the array at index 0:

a5[0] = 5; // assign 5 to the array at index 0

or retrieve a value from the 1 element array at array index 0:

x = a5[0]; // retrieve a value from the array at index 0

a ----> 5

Page 79: Java eBook

www.cstutoring.com E-Learning, E -Books, Computer Programming Lessons and Tutoring

18

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

System.out.println("Lesson 4 Exercise 6"); // print a message

System.out.println("x = " + x); // print a message and a variable value

System.out.println("s1 = " + s1); // print a message and an object value

1. Declare an integer variable x and assign the value of 5 to it. 2. Declare and allocate integer array reference variable y of 1 dimension 3. Assign the value x to the array reference variable y. 4. Declare a integer array reference variable called z and assign y to it. 5. Assign 3 to the array reference variable z. 6. What does x hold ? 7. What does y[0] hold ? 8. What does z[0] hold ? 9. Declare a 1 dimensional array of 5 element initialized to your favorite numbers. Without using a lop print reveres the contents of the array, Print out the contents of the array after you have reveres the array contents.

Page 80: Java eBook

www.cstutoring.com E-Learning, E -Books, Computer Programming Lessons and Tutoring

19

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:

[email protected]

E-Mail all attached files of your completed exercises to:

[email protected]

Order your next Lesson from

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.

Page 81: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

1

JAVA PROGRAMMERS GUIDE LESSON 5

File: JavaL5.doc

Date Started: July 12,1998

Last Update: Dec 28,2005

Java Version: 1.5

LESSON 5 JAVA METHODS

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.

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.

visibility class name {

variables // store and retrieve data for the class

constructor // initialize and allocate memory for variables

methods // contains programming statements

main method // creates i/o streams, creates classes and call's class methods

toString method // return a string representation

}

method

programming statements

class

variables

methods

program

class

class

temporary variables

Page 82: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

2

send data to

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.

// example class calculate public class Calculate

declaring and defining a method

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.

(data_ type parameter_ name) (int x) // parameter

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.

(data_ type parameter_name1, data_type parameter_name2, data_ type parameter_name3)

( int x, int y, float f) // 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.

calling method

called method

parameters receive values

Page 83: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

3

visibility return_data_type method_ name ( parameter_list )

{ variable declarations and statements optional return statement }

// calculate square of a number public int square (int x)

{ return x * x; // return square of x }

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.

// method does not return a value void putValue(int x)

{ System.out.println("the value is: " + x); }

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

methoda(5); // call methoda with argument value of 5

methodb(x+y); // call methodb with argument expression x+y

methodc(methodd(5)); // call methodc with argument mrthodd(5) // methodd returns a value to method c

putValue(int x)

square(int x) return a int value

receive a int value

Page 84: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

4

send data (argument) to called method

Some methods calls require no arguments

method_ name ( );

methodb(); // call methodb pass no arguments receive no values

If more than one argument is needed then the arguments are separated by commas.

method_ name (argument 1, argument 2, argument n)

methodc ( x, y, 10 ); // call method c with 3 arguments, receive no value

assigning the return value from a method call to a variable

An assignment statement is used to assign the return value of a method to a variable in the calling method.

variable_ name = method_name (argument_list);

x = square(5); // variable x gets the value of square of 5 (25)

In Java it is convenient to declare and use variables when we need them.

data_type variable_ name = method_name (argument_list);

int x = square(5); // variable y gets the value of square of 5 (25).

What is the value of x ?

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

/* instantiate class and call sine method */ public static void main(String args[])

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

int square(int x) x

5

25

calling method

called method

return data

Page 85: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

5

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:

object_type object_name = new class_constructor;

Calculate calc = new Calculate(); // instantiate class

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.

data _type variable_name = object_name . method_name (arguments);

int x = calc.square(5); // variable x gets square of 5 */

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.

5

25

Calculate class

main method (calling)

calc.square(5);

Calculate object

calc

square method (called)

x

Page 86: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

6

Here's the complete program for the Calculate class:

LESSON 5 PROGRAM 1 // example class calculate public class Calculate

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

// calculate square of a number public int square(int x)

{ return x * x; // return square of x }

} // end class Calculate

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

int square( int x ) (2) The parameter x receives the value of 5 from the calling method. The square method calculates the square of a number and returns the results

x (25) (3) The calling method gets the results from the square method, and assigns the

returns value to the variable x. The main method continues executing statements

(4) program prints out value of x

Why must the main method be static ? Why do we instantiate the Calculate class ? Why do we need to instantiate classes ?

square of 5 is = 25

program output:

Page 87: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

7

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.

// method square receives an int returns an int int square(int x)

{ return x * x; // return square of x }

// method square receives an double returns a double double square(double x)

{ return x * x; // return square of 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.

// method square receives a double returns an int int square(double x)

{ return x * x; // return square of 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 !

passing parameters to a method

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.

int square(double x)

double

int

int square(int x)

int int

int square(double x)

double double

Page 88: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

8

calling method argument list

( a, b, c ) (arguments) values sent

actual values passed 5 2 3 (actual parameters) values received

called method parameter list

( int x, x = a;

float y, y = b;

double z = c;

); (formal parameters) stored values

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.

passing values to methods

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.

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.

10

class PassValueTest { public static void main(String[] args) { int x = 5; funcv(x); }

void funcv(int x) { x = 10; } }

x 5

x 5

Called function

Calling function

Page 89: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

9

pass by Object reference

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.

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.

10

class PassReferenceTest { public static void main(String[] args) { String s = "Hello"; funcr(x); }

void funcr(String s) { x = 10; } }

s

s

Called function

Calling function "Hello"

10

class PassReferenceTest { public static void main(String[] args) { String s = "Hello"; funcr(x); }

void funcr(String s) { x = 10; } }

s

s

Called function

Calling function "Hello"

"Goodbye"

Page 90: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

10

EXAMPLE PASSING VARIABLES USING POINT CLASS

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

// class to receive object references and change them class Change { // constructor to change values of parameters p and s public Change(Point p, String s)

{ p.x++; p.y++; p = new Point(p.x,p.y); p.x++; p.y++; s = "goodbye"; }

}

// point class has two public member variables x and y class Point { public int x=0;int y=0;

// initializing constructor public Point (int x, int y ) { this.x = x; this.y = y; }

6,11

p

s "hello"

7,12

"goodbye"

Page 91: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

11

// main method, create point class, create change class // print out results public static void main(String args[])

{ Point p = new Point(5,10); System.out.println(p); String s = "hello"; Change c = new Change(p,s); System.out.println(p); System.out.println(s); }

// get results public String toString( )

{ return "x = " + x + " y = " + y; }

}

LESSON 5 EXERCISE 3

Type in the above program and print out the values in the Change constructor line by line;

Passing by array reference (optional material)

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.

// program to demonstrates passing and receiving individual values

class Surprise { public static void main(String args[])

{ // 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]); }

x = 5 y = 10

x = 6 y = 11

hello

program output:

5, 10 p

s

c

"hello"

s p

a[0]

update(int[] x)

Page 92: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

12

// method to assign new value to array element private static void update(int[ ] x) { x[0] = 5; // change value to 5 } }

The following table summarizes all passing parameters passing types.

pass by direction comment calling method called method

value

input pass value of variable to method

int x = 5; putValue(x);

putValue(int x)

object reference

value

input pass copy of object reference to method

String s = "hello" putValue(s);

putValue(String s)

array reference

input/output values passed through an array

int [ ] a = new int[1]; a[0] = 5; putValue(a);

putValue(int[] a)

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.

RETURNING VALUES FROM METHODS

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;

return x; // terminate method and return a value

calling method receives return value <------------- method returns value

to calling method

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;

return; // force the method to return (terminate)

the value before is: 0

the value after is: 5

Page 93: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

13

Examples of method declarations using different passing methods.

Primitive data types like int and float are passed by value, arrays and object are passed by object reference

// pass by value, return by value int methoda ( int i )

{ return i + i; }

// pass by object reference value , return by value boolean methodb ( String s )

{ return true; }

// pass by object reference value, return by object reference String methodc ( String s )

{ return s + s; }

// pass by array reference value , return by array reference int[] methodc ( int[] a )

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

// method does not return any value void methoda ( int i, )

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

// these statements are equivalent and do not except any arguments

int methodb(void)

{ return num; }

int methodb()

{ return num; }

Page 94: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

14

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.

method call y x a[0] s1 s2

start

methoda

methodb

methodc

methodc

// class to test pass by value and pass by reference class L5q1

{ // 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 int[] a = new int[1]; // declare an array of 1 column a[0]=x; // assign the value of x to the array index 0 // What is the value of a[0] ? // 5 y = methodb (a); // pass by reference // what is the value of y ? // 6 // what is the value of x ? // 5 // What is the value of a [0] ? // 6

Page 95: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

15

String s1 = "hello"; // what is the value of s1 ? // "hello"

methodc(s1); // pass by value // 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

// method pass by value return by value public static int methoda(int i )

{ // what is the value of i ? i++; // what is the value of i ? return i; // what value does the method return ? }

// method pass by array reference return by value public static int methodb(int[] i )

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

// pass by object reference return by object reference public static String methodc(String s )

{ // what is the value of s ? s = "goodbye"; // what is the value of s ? return s; // what value does the method return ? }

} // end class MethodTest

PASSING ARRAYS TO METHODS

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.

Page 96: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

16

An array reference is indicated by the[ ] on the data type : int[] a. The following method has a array reference as its parameter:

void method(int[] a); // a 1 dimensional array reference

When an 1 dimensional array is passed to a method only the name is used, because an array name is a reference.

x = method(a); // call a method and pass an array as an argument

The following example program initializes a 1 dimensional array and has a method that returns an array value at a specific index..

// class to demonstrate passing arrays to methods class L5p4 { // main function public static void main(String[] args)

{ int a[]={1,2,3,4,5}; int value = getValue(a,1); System.out.println("The array value at index 1 is: " + value); }

// method to return value of array at specified index public static int getValue(int[] a, int i)

{ return a[i]; } }

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

passing 2 dimensional array reference to a method

You use two square brackets [][] to specify a data type as a 2 dimensional arrays reference.

void method( int[][] b); // a 2 dimensional array reference

When an 2 dimensional array is passed to a method only the name is used, because an array name is a reference.

x = method(b); // call a method and pass an 2 - D array as an argument

The array value at index 1 is: 2

1 2 3 4 5

Page 97: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

17

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.

// class to demonstrate passing arrays to methods class L5p5

{ // main function public static void main(String[] args)

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

// method to return value of array at specified index // return value from array at specified prow and column index public static int getValue(int[][] a, int i, int j)

{ return a[i][j]; }

}

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

ARRAYS AS A RETURN DATA TYPE

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

int[] a2 = method(a1); // pass and receive a 1 dimensional array reference.

The following program calls a method that receives a 2 dimensional array reference and returns a 1 dimensional array reference.

The array value at row index 1 column index 2 is: 6

1 2 3

4 5 6

Page 98: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

18

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

public static void main(String[] args)

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

Page 99: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

19

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:

[email protected]

E-Mail all attached files of your completed exercises to:

[email protected]

Order your next Lesson from

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.

Page 100: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

1

JAVA PROGRAMMERS GUIDE LESSON 6

File: JGuideL6.doc

Date Started: July 12,1998

Last Update: Dec 28, 2006

Java Version 1.5

LESSON 6 OBJECT ORIENTED PROGRAMMING

Object Oriented programming allows a programming language to represent everyday objects with attributes and actions. Attributes describe an object and are represented as variables that store and retrieve data. Action is what an object does and is represented by methods. Methods are a collection of programming statement used to instruct what a computer is to do. An example of an object is a vehicle. A Vehicle has properties or attributes make, model, color and year. A vehicle also has action they run, fall apart and get smashed etc. A programming language uses data to represents attributes and has programming statements to perform actions. Data is stored in a computer memory and the location where the data is stored is represented by a variable name. Programming statements are grouped together into a method. A method allows the program to execute these statements sequentially represented by the method name. A class is the definition for an object having data represented by variables and code represented by a collection of methods. Methods may also have temporary variables for doing calculations. The data is memory for the variables defined in the class. The allocated memory is the Object. The methods become the code that accesses the data in each object. You can have many objects all created from the same class definition. The sane code will be used for all of the same type objects. The Object Oriented Programming approach will enable you to organize your programs so that your programming tasks will be easier to accomplish.

OBJECT CLASS

Variables

Methods

Temporary variables and Programming

Statements

Data

(allocated memory for variables declared in class)

Code for objects (what the object does)

A class is used to define an object

(what a object has)

A class Definition lists all the Variables and Methods that are needed by the object

Page 101: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

2

You need to define a class before you can use it. A class definition is like the recipe to bake a cake. You need a recipe before you can bake a cake. A class defines variables and methods needed to create an object. Just like a cake needs ingredients and instructions to bake the cake. Variables are used to store and retrieve data. Methods contain programming statements that instruct the computer what to do.

Class Definition

variables Classes are use to declare and define variables and methods. class

methods

Classes are defined by an access modifier, the keyword class and a class name.

access modifier class 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

class visibility description

public means all classes can use the variables and methods belonging to this class

friendly default visibility access by classes only in same package

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:

Page 102: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

3

variables description

String make; make of vehicle

String model; model of vehicle

String color; color of vehicle

int year; year vehicle was made

static int num; number of vehicle objects created

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.

int x. // declare an int data type variable called x

The only difference instead of a data type we have a object type. The object type is the class name.

Vehicle v1; // declare an reference to an Vehicle object

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.

object_reference = new constructor(parameter list);

v1 = new vehicle("Ford","Mustang","red",1989); // create a vehicle

Page 103: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

4

The location where the object is created in memory is assigned to the Vehicle object reference.

When an object is created it is known as an instance of a class. Each created object is assigned to an object reference. The object reference refers to this object. Just like after a cake is baked , it gets a name name: cake1, cake2 cake3 etc. The object you are making is a cake, but each individual cake made is known separately. Many objects may be created from one class definition, just as there can be many cakes made from the same recipe. The class is the basic definition that instances are created from. Each instance will have its own properties. Just like each cake can have its own properties. Chocolate cake, vanilla cake etc. This is the highlight of Object Oriented Programming. where a class provides a common definition and many objects are created from that definition with distinguishable properties or attributes.

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

v1 = new Vehicle ("Ford","Mustang","red",1989);

v2 = new Vehicle ("Toyota","Swift","green",1989);

Toyota Swift green 1995

Ford Mustang

red 1989

Ford Mustang

red 1989

v1

Vehicle

Page 104: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

5

Each object gets distinguishable properties when the object is created and the variables are initialized by calling their constructor. A program is made up of many different classes. By organizing your program into classes, where each class represents a particular object to do a specific task, then your programs will be highly organized and efficient. The object oriented programming approach will let you write complicated programming tasks very easy and fast.

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.

access_modifier data_type variable_name;

private int x;

variable visibility description

public means everybody can use the variables belonging to this class

friendly means classes in same package can use these variables

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.

final variables (initialized only once)

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

access_modifier final data_type label = constant;

private final int CurrentYear = 1999; // final variable initialized to current year

Page 105: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

6

static variables (shared between all objects)

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.

static data_type variable_name;

static int num=0; // declare static variable num

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.

num++; // increment instance counter

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.

Object Instance variable

program memory class loaded into, memory:

static variable

Code for method

Object Instance variable

Object Instance variable

Page 106: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

7

Final variables defined in a class definition may also be declared static because memory for the static final variable is only needed to allocated once..

private static final int CurrentYear = 1999; // final variable initialized

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.

Variables storage and retrieval of data belonging to class

Constructor set variables and allocate memory

this ---->

main() method is first method called and used to instantiate classes

receive Data from outside world ----> set Methods store input data in variables of class

Process Methods calculate values and store in variables of class

get data from variables in class get Methods -----> send Data to outside world

toString() method return string representation of this object

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.

Here is the vehicle class starting definition:

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

Page 107: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

8

Constructors have the same name as the class. Constructors are only called once when the class is instantiated. Constructors are optional and are only required if variables have to be initialized and memory has to be allocated. There are many types of constructors each distinguishable by different parameter lists. It is possible to have many constructors of the same name due to method overloading. Method overloading allows you to have methods with same name but different parameter data types.

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

{ this.color = color; // initialize color this.year = year; // initialize year num++; // increment instance counter }

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.

Vehicle

color year

Vehicle

Page 108: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

9

// conversion constructor public Vehicle (String color, String year )

{ this.colour = color;// initialize vehicle color this.year = Integer.parseInt(year); // convert year 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 ) { this.colour = v2.colour;// initialize vehicle color this.year = v2.year; // convert year 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.

access_modifier return_data_tyoe method_name(paramater_list);

Methods defined in the class have visibility of private. friendly or public.

method and variable visibility

description

private Only the class can access

friendly only classes in same package can access

public all classes can access

Vehicle

color year

Vehicle v2

Vehicle

Page 109: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

10

There is no keyword friendly. friendly visibility is the default. if you do not specify a visibility then you get friendly.

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:

declaring and instantiating a object

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.

object_type object_reference = new constructor(argument_list);

Vehicle veh = new Vehicle("red",1989); // make a red 1989 vehicle object

veh "red" color

1989 year

methods

private

variables private

variables

methods

methods methods

exchange data

class A class B

Page 110: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

11

accessing variables and methods in a class

Member variables and methods are accessed by the "." dot operator which means "belongs to"

object_name . variable = expression;

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.

this . variable = expression;

this.colour = colour; // accessing color variable

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.

object _name . method( )

veh.setColor("red");

If the method returns a value then you can assign this value to a variable.

variable = object _name . method( ) int year = veh.getYear(); // accessing getYear() method

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.

// make a string of vehicle information // Java calls this method automatically to represent the object public String toString( )

{ String s = "\n" + "Vehicle info " + "\n"; s += "colour: " + colour + "\n"; s += "year: " + year + "\n"; s += "number of vehicles: " + num + "\n"; return s; }

The toString() method is automatically called by using a reference of your object.

System.out.println(v1); // print vehicle info

Page 111: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

12

main() method

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.

The main method is declared as follows. public static void main(String[] args)

{ variables and statements }

// Vehicle class main method public static void main(String args[])

{ 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

Page 112: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

13

// default constructor public Vehicle ( )

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

// copy constructor copy existing vehicle object public Vehicle (Vehicle v2 )

{ this.colour = v2.colour;// initialize vehicle color this.year = v2.year; // convert year }

// set vehicle colour public void setColour(String colour )

{ this.colour = colour; // set colour }

// set vehicle year public void setYear(int year )

{ this.year = year; // set year }

Page 113: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

14

// get vehicle color public String getColor ( )

{ return color; // return color }

// get vehicle year public int getYear( )

{ return year; // return year }

// verify vehicle year, return true or false private boolean verifyYear(int year)

{ return(year <= CurrentYear); // check if year is valid }

// make a string of vehicle information // Java calls this method automatically to represent the object public String toString( )

{ String s = "\n" + "Vehicle info " + "\n"; s += "colour: " + colour + "\n"; s += "year: " + year + "\n"; s += "number of vehicles: " + num + "\n"; return s; }

// Vehicle class main method public static void main(String args[])

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

} // end class Vehicle

Page 114: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

15

Draw bubble diagrams for the main method. As each vehicle object is created draw the object reference pointing to a bubble representing the object. Fill the bubble with the objects variable values, Bubble diagrams helps you keep track of created objects and which reference points to them. Example for vehicle object v1.

program output:

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.

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

red

1989 v1

Page 115: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

16

LESSON 6 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. In your main method test your student class by making student objects and printing them out.

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

name

id

mark

Student

Page 116: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

17

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:

[email protected]

E-Mail all attached files of your completed exercises to:

[email protected]

Order your next Lesson from

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

Page 117: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

1

JAVA PROGRAMMERS GUIDE LESSON 7

File: JGuideL7.doc

Date Started: July 12,1998

Last Update: Dec 28, 2001

Java Version: 1.5

LESSON 7 JAVA PROGRAMMING STATEMENTS, LANGUAGE AND UTILITY CLASSES

PROGRAMMING STATEMENTS BY EXAMPLE

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;

class Method

Temporary Variables

Programming Statements

We now look at java programming statements. 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 statements use for intermediate calculations. In the 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 statements.

Page 118: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

2

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.

definition one statement more than one statement

if(condition) true statement(s)

if (x==0) y = x;

if (x==0) { y = x; x=x+1; }

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) true statement(s)

else

false statement(s)

if (x==0) { y = x; x=x+1; } else x=1;

nested if-else statements

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)

{ true statement (s) if (expression) true statement(s) else false statement(s) }

else

false statement(s)

if (x == 2)

{ if(x == y) y = 2; else y = x++; }

else

y = x;

if(x == 0)

y = x;

if(x==0)

T

F

x = 1; y = x; x = x + y;

T F

if

if

else

else

Page 119: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

3

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.

while(condition)

statement(s)

i = 0; // initialize before entering loop

// loop while i is less than num while(i < MaxSize)

{ System.out.println(i); i++; }

System.out.println("I got:" + i + " items");

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.

do statement

while ( condition );

i = 0; // initialize before entering loop do

{ System.out.println(i); i++; } while ( i < MaxSize)

System.out.println ("I got:" + i + " items");

T

F

T

i < MaxSize

i++

i < MaxSize

i++

F

if(x==2)

y = x;

T F

if(x==y)

y = x++; y = 2;

T F

i = 0

i = 0

Page 120: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

4

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.

for(initializing expression; testing expression ;incrementing expression)

statement

for( int i = 0; i < MaxItems; i++)

System.out.println(i);

All expressions in the for statement are optional. When there are no expressions then would be an infinite loop.

for ( ; ;); /* loop for ever */

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.

for(int i = 0, j = numItems-1; i < numItems; i++, j--) a [ i ] = b [ j ]; /* copy reverse of an another array */

T

i < MaxItems

i = 0;

F

i++

If the for loop has more than one statement then curly brackets must be used to enclose the statements belonging to the for loop.

for(int i = 0;i<num;i++)

{ System.out.println(i); }

System.out.println ("I got:" + i + " items");

Initialize Index Counter

Test Condition

Increment index

System.out.println(i);

Page 121: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

5

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.

/* loop till break condition encountered */ x = 0; while(true) { System.out.println(i + " " ); if(x==5)break; /* exit loop if test condition true */ x=x+1; }

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;

/* loop till i greater than Num */ for(i = 0; i < Num; i++)

{ if ((i >= 3) && (i <= 4)) continue; /* skip for 3 and 4 x=x+i; /* this statement skipped of condition true */ System.out.println(i + " " ); }

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.

nested for statements

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

/* outer loop for number of rows */ for (int i = 0 ;i < a.length; i++)

{ /* inner loop for number of columns */ for(int j =0 ; j < a[i].length; j++)

System.out.println(a[i][j] + " "); /* print out array element */

System.out.println(); / * start a new line for each row */ }

0 1 2 3 4 5

0 1 2 5 6 7 8 9 10

Outer Loop

Inner Loop

Page 122: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

6

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 )

j i j

1 2 3 0 0, 1, 2

i 4 5 6 1 0, 1, 2

7 8 9 2 0, 1, 2

printing out diagonal of a square array

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 rows */ for( int i = 0; i < a.length; i++)

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

j i j

3 0 0, 1, 2

i 5 1 0, 1, 2

7 2 0, 1, 2

rows

columns

How would you print out the reverse diagonal ?

Page 123: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

7

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.

if(expression) if(x == y)

statement x=1;

else if(expression) else if(x < y)

statement x = 2;

else if (expression) else if(x > y)

statement x = 3;

else else

statement; 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( expression)

{ case constant 1: statements break;

case constant 2: statements break;

case constant N: statements break;

default: statements break; }

switch(x) { case 0 : { System.out.println("first item is " + items[0] ) ; break; } case 1: case 2: { System.out.println("the items are: " + item[1] + " " + item[2]); break; } case 3: { System.out.println("the third item is: " + item[3] + " " + item[2]); break; } default: break; }

T

F

F

F T

T

(x == y) x = 1;

x = 2;

x = 3

x = 4

(x < y)

(x > y)

Page 124: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

8

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:

sharing data between classes

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.

// data manager class class DataManager { private DataManager reference;

// nobody can instantiate class only itself private DataManager() {}

static public DataManager getInstance() { if (reference == null) reference = new DataManager(); // create instance of this class

return reference; // return reference to instance of class }

}

How can another class get a reference to the DataManager class ?

DataManager dm = DataManager.getInstance();

I got 5 items I got 6 items

11 12 13 21 22 23 31 32 33

11----- --22--- -----33

Page 125: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

9

CONVENTIONS TO MAKE YOUR PROGRAMMING LIFE EASIER

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 class names should be capital Test

All method names should be lower case getDay()

All method parameters and should be lower case (int x)

All method local variables and should be lower case int x;

Avoid underscores between letters in class, method or variable names

new_word

Use capitalization to distinguish words in a name newWord

All static or global variables should start with be Uppercase

Num

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.

Page 126: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

10

LANGUAGE AND UTILITY CLASSES java.lang, java.util

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

protected Object clone() Creates and returns a copy of this object

public boolean equals(Object obj) Indicates whether some other object is "equal to" this one.

protected void finalize() Called by the garbage collector on an object when garbage collection determines that there are no more references to the object. A subclass overrides the finalize method to dispose of system resources.

public final native Class getClass(); Returns the runtime class of an object.

public native int hashCode(); Returns a hash code value for the object.

public String toString() Returns a string representation of the object.

STRING CLASS (java.lang)

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.

s1 = s1.toUpperCase(); // change string s1 to upper case

Here are the methods belonging to the String class:

string method description example using

= assigning a empty string String s1 = "";

= assigning a message to a string s1 = "hello";

+ joining a message and a string String s2 = " s1 + there "; // " hellothere "

+ joining two strings together s1 = s1 + s2; //"hellohellothere"

Page 127: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

11

char charAt(int index) getting a character of a string at index i char c = s1.charAt(0); // 'h'

void getChars (int srcBegin, int srcEnd, char[ ] dst, intdstBegin)

copies characters from this string into the destination character array

s1.getChars(0,5,a,0); // a = "hello"

int length() getting the length of a string. int len = s1.length(); // 5

String substring(int start) get substring of this string from start to end of string

s2 = s1.substring(3); // "lo"

String substring(int start, int end) get substring of this string from start to end-1

s2 = s1.substring(0,4); // "hell"

boolean equals(String str) test if two strings have the same message (data contents)

if( s1.equals(s2) ) // false

boolean equalsIgnoreCase (String str) test if two strings have the same message ignoring upper/lower case

if( s1.equalsIgnoreCase(s2) ) // false

int compareTo(String str) compares two strings less than < 0, equal == 0 or greater > 0

if( s1.toCompare(s2) ) // > 0

= = test if two string references refer to the same string object location

if (s1 = = s2) // false

int indexOf(int ch) returns the index (position)of the first occurrence of the specified character

int index = s1.indexOf('l'); // 2

int lastIndexOf(int ch) returns the index of the last occurrence of the specified character

int index = s1.lastIindexOf('l'); // 3

String replace (char old, char new) returns a new String resulting from replacing all occurrences of the old character with the new character

s1 = s1.replace ( 'h' , 'j' ); // "jello"

String concat(String str) returns the concatenation of two strings (joins two strings together)

s3=s1.concat(s2+" "); //"helljello "

String toLowerCase() changers all characters to lower case s1 = s1.toLowerCase(); //"helljello "

String toUpperCase() changers all characters to upper case s1 = s1.toUpperCase(); //"HELLJELLO "

String trim() removes white space from both ends of this string

s1 = s1.trim(); //"HELLJELLO"

static String valueOf (type variable) converts a variable or constant into a string

String s4 = s1.valueOf(5); //"5"

Page 128: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

12

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

Write a Java program to print out words in a sentence in reverse.

STRINGBUFFER CLASS (java.lang)

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:

string method description example using

StringBuffer() constructs an empty string buffer (default capacity is 16 characters)

StringBuffer sb = new StringBuffer();

StringBuffer (int length) constructs a string buffer with an initial capacity of 80 characters

StringBuffer sb = new StringBuffer(80);

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 ensureCapacity (int m); enlargers the buffer to m characters sb.ensureCapacity(100);

StringBuffer insert (int offset, String str)

the string is inserted starting at the offset sb.insert(5,s);

StringBuffer reverse() return characters in reverse sb.reverse();

void setLength(int n); set length of string discarding characters or '\0' padding

sb.setLength(50);

void setCharAt (int index, char ch)

the character at the specified index is set to ch sb.setCharAt(2, 'x');

String toString() returns a string pointing to the buffer data contents

System.out.println(sb.toString());

Page 129: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

13

String String (StringBuffer buffer);

makes a string pointing to buffer data contents String s = new String(sb);

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 wrappers classes for primitive data types. (java.lang)

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.

primitive data type

Wrapper Object class

creating wrapper objects using valueOf method

byte Byte Byte b = new Byte(5); Byte b = Byte.valueOf(5);

boolean Boolean Boolean b = new Boolean(true); Boolean b = Boolean.valueOf(true);

char Char Char c = new Char('a'); Char c = Char.valueOf('a');

int Integer Integer i = new Integer(9); Integer i = Integer.valueOf("9");

float Float Float f = new Float(10.5); Float f = Float.valueOf("10.5");

double Double Double d = new Double(0.0008); Double d = Double.valueOf("0.0008");

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.

String s = "1234" ; // make string "1234"

int x = Integer.parseInt(s); // convert a string to an integer 1234

x = new Integer(s).intValue();

// convert String to Integer, get value

1234

float f = new Float(s).floatValue();

// convert string to a float 1234.0

double d = new Double(s).doubleValue();

// convert string to a double 1234.0

Page 130: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

14

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 intValue(); return the int value

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

public String toString(); returns a String representation of this object

RANDOM NUMBER GENERATOR (java.util.*)

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 .

method description example

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 between 0 and max

int i = r.nextInt(100);

double nextGaussian() returns the next gaussian distributed value with mean 0.0 and standard deviation 1.0 (bell curve)

double g = r.nextGaussian()

void setSeed(long seed); sets the seed of this random number generator g.setSeed(1000);

Example program using Random number generator class:

// Lesson 7 Program 5 - L7p5.java import java.util.*; class L7p5() { public static void main(String args[ ]) { Random r = new Random(); // make a random number object // print out a random number between 1 and 100 System.out.println((r.nextDouble() * 100 )+ 1); // print out a random number between - 100 and 100 System.out.println((r.nextInt() % 100 )+ 1); // print out a gaussian random number between 1 and 100 System.out.println((r.nextGaussian()) * 100 )+ 1); } }

Page 131: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

15

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.

MATH CLASS (java.lang.math)

The math class located in java.lang supplies static methods for commonly used mathematical operations.

static method returns example using

double abs(double a) absolute value double x = Math.abs(x);

double acos(double arg1); arc cos double x = Math.acos(x);

double asin(double arg1); arc sin double x = Math.asin(x);

double atan(double arg1); arc tan double x = Math.atan(x);

double ceil(double arg1); largest whole number double x = Math.ceil(x);

double cos(double arg1); cosine in radians double x = Math.cos(x);

double exp(double arg1); e to power x double x = Math.exp(x);

double floor(double arg1); smallest whole number double x = Math.floor(x);

double log(double arg1) natural log double x = Math.log(x);

double max(double a, double b) max of a and b double x = Math.max(a,b);

double min(double a, double b) min of a and b double x = Math.min(a,b);

double pow(double arg1, double arg2); x to power y double x = Math.pow(x,y);

double random() random number between 0 and 1 double x = Math.random();

long round(double a) closest whole number double x = Math.round(x);

double sin(double arg1); sin in radians double x = Math.sin(x);

double sqrt(double arg1); square root of a number double x = Math.sqrt(x);

double tan(double arg1); tan in radians double x = Math.tan(x);

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.

Page 132: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

16

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:

[email protected]

E-Mail all attached files of your completed exercises to:

[email protected]

Order your next Lesson from

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.

Page 133: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

1

JAVA PROGRAMMERS GUIDE LESSON 8

File: JGuideL8.doc

Date Started: July 12,1998

Last Update: Dec 29, 2005

Java Version: 1.5

LESSON 8 I/O STREAM CLASSES

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.

System.out.print("hello"); // print "hello" with out a new line System.out.println("hello"); // print "hello" without a new line at end

You can join (concatenate) other string or variables together by using the + operator:

System.out.println ("hello" + "today"); // join two strings together

You can also print out a variable value on the screen:

int x = 5;

System.out.println (x); // print out value of x

Better yet you can print out a message and a variable:

System.out.println ("hello " + x); // join a string and a variable

hellohello

hellotoday

5

hello 5

Program

Computer Screen

System.out

Page 134: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

2

input data streams

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.

public DataInputStream(InputStream in); // data stream for keyboard "System.in" DataInputStream din = new DataInputStream(System.in);

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.

char ch = din.read(); // get message from keyboard assign to ch

We can also read a message from the keyboard using the readLine() method and assign it to a String:

String name = din.readLine(); // get message from keyboard assign to name

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.

// Lesson7 Program 1 - L8p1.java import java.io.*;

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

{ // instantiate data input stream DataInputStream din = new DataInputStream (System.in); // Ask user to enter a message System.out.println("please enter a message:"); // read message from keyboard String msg = din.readLine(); // print message to screen System.out.println("you have entered: " + msg); }

}

Program DataInputStream Keyboard

please enter a message:

Hello there

you have entered: Hello there

System.in

Program output:

Page 135: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

3

Buffered Reader Class (java.io.*)

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.

BufferedReader(InputStream in) in = InputStream

BufferedReader(InputStream in, int n) in = InputStream n = buffer size

InputStreamReader(InputStream in) in = InputStream

To create a buffered reader:

BufferedReader bin = new BufferedReader(new InputStreamReader(System.in),1);

To use a buffered reader to get a message from the keyboard

String s = bin.readLine(); // read a line from keyboard

Scanner class (java.util.*) (available in java 1.5)

The scanner class located in java.util.* makes it a little easier to read data from keyboard. To create a Scanner object:

Scanner sc = new Scanner(System.in);

With the scanner object you can read strings, ints floats doubles etc.

String s = sc.nextLine(); // read a line from keyboard

int x = sc.nextInt(); // read a int from keyboard

float f = sc.nextFloat(); // read a float from keyboard

double d = sc.nextDouble(); // read a double from keyboard

note: you should always use sc.nextLine(); if you want to read data from the next line.

Program BufferedReader Keyboard InputStreamReader

Page 136: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

4

BufferedWriter Class (java.io.*)

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.

BufferedWriter(OutputStream out) out = OutputStream

BufferedWriter(OuputStream out, int n) out = OutputStream n = buffer size

OutputStreamWriter(OutputStream out) out = OutputStream

To create a buffered writer

// create a buffered writer BufferedWriter bout = new BufferedWriter(new OutputStreamWriter(System.out), 1);

To use a buffered writer to write a message to the screen

// print to screen using buffer bout.write(s);

An example program using a Buffer Reader and Buffer Writer:

using buffered reader and writer

// Lesson 8 Program 2 - L8p2.java import java.io.*;

class L8p2

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

{ // create a buffer reader BufferedReader bin = new BufferedReader (new InputStreamReader(System.in),1);

// create a buffered writer BufferedWriter bout = new BufferedWriter (new OutputStreamWriter(System.out),1);

// Ask user to enter a message using buffer reader bout.write("please enter a message:");

Program BufferedWriter Screen OutputStreamWriter

Page 137: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

5

// read a line from keyboard String msg = bin.readLine();

// print to screen using buffer writer bout.write("you have entered: + msg"); }

}

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.

StringTokenizer Class (java.util.*)

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.

It is a cloudy day it is a cloudy day

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.

please enter a message: It is a cloudy day

you have entered: It is a cloudy day

StringTokenizer (convert messages into words)

message

words

Program output:

Page 138: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

6

method parameters and return values

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)

boolean hasMoreTokens() returns true if any more tokens left

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.

// Lesson 8 Program 3 - L8p3.java import java.io.*; import java.util.*; class L8p3 { public static void main(String args[])throws IOException

{ // create a buffer reader BufferedReader bin = new BufferedReader (new InputStreamReader(System.in),1);

System.out.println("Enter a message" ); // ask for a message String s = bin.readLine(); // get message from keyboard StringTokenizer t = new StringTokenizer(s); // create tokenizer

System.out.println(t.countTokens()); // number tokens

// loop till all tokens extracted while(t.hasMoreTokens())

{ String word = t.nextToken(); System.out.println(word); }

} }

5 it is a cloudy day

it is a cloudy day

Page 139: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

7

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.

Using scanner class to separate a message into individual words.

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 {

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

// create a scanner object Scanner sc = new Scanner (System.in);

// ask for a message System.out.println("Enter a message" );

// loop till all tokens extracted while(sc.hasNext()) {

String word = sc.next(); // get next token

System.out.println(word); // print token to screen } }

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.

Page 140: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

8

methods

canRead() Tests if the application can read from the specified file.

canWrite() Tests if the application can write to this file.

delete() Deletes the file specified by this object.

equals(Object) Compares this object against the specified object.

exists() Tests if this File exists.

getAbsolutePath() Returns the absolute pathname of the file represented by this object.

getCanonicalPath() Returns the canonical form of this File object's pathname.

getName() Returns the name 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.

getPath() Returns the pathname of the file represented by this object.

hashCode() Computes a hashcode for the file.

isAbsolute() Tests if the file represented by this File object is an absolute pathname.

isDirectory() Tests if the file represented by this File object is a directory.

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.

mkdir() Creates a directory whose pathname is specified by this File object.

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.

toString() Returns a string representation of this object.

Page 141: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

9

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

.. up one directory

. current directory

\ root directory

// program to list all directories and files import java.io.*;

class Lister

{ public Lister(File f)

{ System.out.println(f.getAbsolutePath()); list(f,0); }

public void list (File dirfile, int depth)

{ // 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(" ");

// add file name to test area System.out.print(contents[i] + "\n");

File child = new File(dirfile, contents[i]); if(child.isDirectory()) list(child, depth+1); // method calls itself }

}

public static void main(String[] args)

{ // current directory File f = new File("."); Lister list = new Lister(f) }

}

You can use the following symbols to specify the starting directory or use a hardcoded path like "c:\mydirectory"

Page 142: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

10

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.

File Output Stream

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

// make a file output steam and open a file for writing DataOutputStream fout = new DataOutputStream(new FileOutputStream("test.dat"));

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)

// make a file output steam and open a file for writing DataOutputStream fout = new DataOutputStream(new FileOutputStream("test.dat",true));

To write a byte to a file we use the write() method:

fout.write('A'); // write byte to output file

There are additional methods writeByte(int), writeBytes(String), writeChar(int), writeInt(int), writeFloat(float), writeDouble(double), writeChars(String s) etc to write these data types to a file. The difference between write byte and write char is write byte will write 1 byte where write chars writes 2 bytes for the Unicode format. WriteBytes will write a string to a file byte by byte. The method writeChars() writes a string to a file in Unicode (2 bytes).

fout.writeBytes(s); // write a string to file each character as 1 byte fout.writeChars(s); // write a string to file each character as 2 bytes (Unicode)

When you finished using a file for writing you have to close it.

fout.close(); // close file

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.

Program DataOutputStream file FileOutputStream.

Page 143: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

11

file writers

FileWriters are dedicated to Unicode characters.

It is easy to construct a FileWriter object using a file name.

FileWriter fw = new FileWriter("test.dat");

Here is a test program using a FileWriter that writes sentences to a file,

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

}

buffered file output

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 BufferedWriter fbout = new BufferedWriter(new FileWriter("test.dat"),1);

Program BufferedWriter file FileWriter

Program file FileWriter

Page 144: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

12

Here is a sample program that uses a BufferedWriter to write a sentence to a file.

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.

PrintWriter pw = new PrintWriter(new FileWriter("test.dat"));

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.*;

public class PrintWriterTest { public static void main(String arg[])throws IOException

{ FileWriter fout = new FileWriter("test.dat"); PrintWriter pw = new PrintWriter(fout); pw.println(s+"hello\n"); pw.close(); }

}

Program PrintWriter file FileWriter

Page 145: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

13

File Input Stream

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.

// make a file input steam and open a file for reading DataInputStream fin = new DataInputStream(new FileInputStream("test.dat"));

We use the read() method to read a binary byte from a file

int x = fin.read(); // read byte from input file

There are additional methods readByte(), readChar(), readInt(), readFloat(), readDouble() to read these data types from a file. We can also use the readLine() method to read a string from a file

String s = fin.readLine(); // read a string from input file

When you finished using a file for reading you have to close it.

fin.close(); // close file

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

File readers are dedicated to Unicode characters.

It is easy to construct a FileReader object using a file name.

FileReader fr = new FileReader("test.dat");

Program DataInputStream file FileInputStream.

Program file LineNumberReader FileReader

Page 146: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

14

There is also a LineNumberReader class that keeps track of the line number read.

LineNumberReader lnr = new LineNumberReader(fr);

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

buffered file input

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.

It is easy make a BufferedReader using a FileReader object to open a file for reading BufferedReader fbin = new BufferedReader(new FileReader("test.dat"),1);

Here is a sample program that users a BufferedReader to read a sentence to a file.

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

Program BufferedReader file FileReader

Page 147: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

15

example program to write and read a file

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.

// program Lesson 8 Program 4 L8p5.java import java.io.*;

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

{ // create a buffer reader BufferedReader bin = new BufferedReader (new InputStreamReader(System.in),1);

// make a file input steam and open a file for reading DataOutputStream fout = new DataOutputStream(new FileOutputStream("test.dat")); System.out.println("Enter a message: "); // get a message String s = bin.readLine(); // read a string from keyboard fout.writeBytes(s); // write string to file fout.close(); // close input file

// make a file input steam and open a file for reading DataInputStream fin = new DataInputStream(new FileInputStream("test.dat"));

// read string from file s = fin.readLine();

// print message out on screen System.out.println(s);

fin.close(); // close output file }

}

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.

Enter a message: It is a cloudy day

It is a cloudy day

Page 148: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

16

Using Scanner class to read a file

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.

sc = new Scanner(new FileReader("test.dat"));

We have taken the above program and used Scanner and Print Writer objects.

import java.io.*;

import java.util.*;

public class L8p3 {

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

// create a scanner object Scanner sc = new Scanner(System.in);

// make a print writer PrintWriter pw = new PrintWriter(new FileWriter("test.dat"));

System.out.println("Enter a message: "); // get a message

String s = sc.nextLine(); // read a string from keyboard

pw.println(s); // write string to file

pw.close(); // close input file

// make a file input steam and open a file for reading sc = new Scanner(new FileReader("test.dat"));

// read string from file s = sc.nextLine();

// print message out on screen System.out.println(s);

sc.close(); // close output file }

}

Enter a message: It is a cloudy day

It is a cloudy day

Page 149: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

17

random access files

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.

RandomAccessFile raf = new RandomAccessFile("out.dat","rw");

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.

long len = raf.length();

Finally the long getFilePointer() method returns the current position within a file in bytes .

long pos = raf.getFilePointer();

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.

Page 150: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

18

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.

ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("test.dat"));

Next you create some objects like the Person object and write to the file using the writeObject(Object obj) method

Person p1 = new Person(); out.writeObject(p1);

You then need to create an ObjectInputStream using a FileInputStream

ObjectInputStream in = new ObjectInputStream(new FileInputStream("test.dat"));

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.

Object obj = in.readObject();

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.*;

public static void main(String[] args) throws IOException, ClassNotFoundException { // create object output stream ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("test.dat"));

// make person objects print and write to file Person p1 = new Person(); System.out. println(p1); out.writeObject(p1); Person p2 = new Person ("Tom",34,456,78); System.out.println(p2); out.writeObject(p2); Person p3 = new Person("Jeeva",56,87,678) System.out.println(p3); out.writeObject(p3); out.close();

Page 151: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

19

// make object input stream ObjectInputStream in = new ObjectInputStream(new FileInputStream("test.dat"));

// read objects from file and print out p1 = (Person)in.readObject(); System.out. println(p1); p2 = (Person)in.readObject(); System.out. println(p2); p3 = (Person)in.readObject(); System.out. println(p3); } }

Your Person class must implement the Serializable interface:

import java.io.*;

class Person implements Serializable { private String name="ed"; private int age; private double height,weight; private static int num = 0; // default constructor public Person(){num = num + 1;} // initializing constructor public Person(String name, int age, double height,double weight) { this.name= name; this.age = age; this.height = height; this.weight = weight; num = num + 1; } // main method public static void main (String[ ] args ) { Person p1 = new Person(); System. out. println(p1); Person p2 = new Person ("Tom",34,456,78); System.out.println(p2); Person p3 = new Person("Jeeva",56,87,678); System.out.println(p3); } // return a string representation of this object public String toString() { String s = "my name is: " + name +" there are "+ num + " persons "; s += "I am " + age + " weigh " + weight + " and am " + height + " tall"; return s; }

}

Page 152: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

20

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

int[ ] a; reference to a array

int size; size of array

Num(int size); initializing constructor

void get(); get array elements from keyboard

void reorder(); exchange array elements

String toString(); make a String of array elements

void static main(); main function

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.

Page 153: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

21

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:

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.

Page 154: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

22

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.*; /* test program /* nested comment */ first comment continued */ class L8p9 { public static void main(String[] args)

{ Random r = new Random(); // make a random number generator

/* print out random number /* between */*/ 0 and 99 */ System.out.println((r.nextDouble() * 100);

/* random number between 1 and 100 System.out.println((r.nextDouble() * 100) + 1); }

}

The result file would be:

import java.util.*; class L8p9 { public static void main(String[] args)

{ Random r = new Random(); System.out.println((r.nextDouble() * 100);

error line 10: comment unbalanced error line 15: file ended but comment started line 12 not finished

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

4 5 6

1 4

2 5

3 6

Page 155: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

23

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

(2) repeat until a multiple of n squares are in place: add one to k, move left one square and up one square and insert k

(3) add one to k

(4) move down one square from the last position and insert k.

(5) go back to step 2 until all squares are filled

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.

6 1 8 7 5 3 2 9 4

Page 156: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

24

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.

Page 157: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

25

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:

[email protected]

E-Mail all attached files of your completed exercises to:

[email protected]

Order your next Lesson from:

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.

Page 158: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

1

JAVA PROGRAMMERS GUIDE LESSON 9

File: JavaL9.doc

Date Started: July 12,1998

Last Update: Dec 28, 2005

Java Version: 1.5

LESSON 9 ESCAPULATION AND INHERITANCE

CLASSES AND ESCAPULATION

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.

Page 159: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

2

class model

this ---> Private Variables data for storage and retrieval

Constructor initializes variables and allocates memory

Data from outside world --> Set Methods (mutator)

put data into private variables

Process Methods calculate values using variables of class

get data from private variables Get Methods (accessor) -->

send Data to the outside world

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:

object

class definition

object object

object

Objects are created from a class definition

Page 160: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

3

PERSON CLASS

We will now present an example class the Person class. The Person class keeps track of the persons name, address and age.

class Person { private String name; // plant name

private String address; // plant status "operating" or "closed"

private int age; // number of vehicles ready for delivery

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.

// default constructor, initialize to default values public Person()

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

// initializing constructor, initialize vehicle plant variables public Person(String name, String address, int age)

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

Page 161: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

4

// conversion constructor, initialize vehicle plant variables public Person(String name, String address, String age) { this.name = name; // person's name this.address = address; // person's address this.age=Integer.parseInt(age); // convert String to int }

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.

// copy constructor, initialize vehicle plant variables public Person(Person p2) { name = p2.name; // copy name address = v2.address; // copy address age = p2.age; // copy age }

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.

object_type object reference = new class_construtor(optional_paramater_list);

Person p1 = new Person("Tom","121 College St",25); // make a Person 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:

String name = vp1.getName(); // get name of plant

Private variables

M M

M

M

M

The variables defined in a class are private, and the methods are used to exchange data between objects,

Page 162: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

5

Person class code

A class to represent a Person is defined as follows:

// Person.java import java.io.*;

// vehicle plant class class Person

{ private String name; // persons name private String address; // persons address private int age; // persons age

// default constructor, initialize to default values public Person()

{ name = ""; // person's name status = "operating"; // persons address age = 0; // person's age }

// initializing constructor, initialize vehicle plant variables public Person(String name, String address, int age)

{ this.name = name; // person's name this.address = address; // person's address this.age=age; // person's age }

// conversion constructor, initialize vehicle plant variables public Person(String name, String address, String age) { this.name = name; // person's name this.address = address; // person's address this.age=Integer.parseInt(age); // convert String to int }

// copy constructor, initialize vehicle plant variables public Person(Person p2) { name = p2.name; // copy name status = v2.address; // copy plant status numVehicles = p2.age; // copy numVehicles }

Page 163: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

6

// return persons name public String getName() { return name; }

// return persons address public String getAddress() { return address; }

// return persons age public int getAge() { return age; }

// put all information about Student into a string public String toString()

{ String s = " name: " + name + "\n"; s += "address: " + status + "\n"; s += "age: " + age + "\n"; return s; }

} // end class Person

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.

Page 164: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

7

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.

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.

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

double[] marks = new double[MAX_MARKS] ;

Mark[] marks = new Mark[MAX_MARKS];

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.

marks[i] = new Mark(34,"History");

You will also have a calcAvg() method in the student class to calculate the marks from the Mark class objects. From the mark object stored in the array you can call the getMark() method directly.

double calcAvg() { double sum = 0; sum = sum + marks[0].getMark() + marls[1].getMark() + marks[2].getMark() + marks[3].getMark();

return sum/numMarks; }

Mark class mark

course

name

id

mark

Student

name

id

marks

Student

Page 165: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

8

Don't forget to have a toString method to print out all the entered marks and average.

Your object model will now be like this:

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

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

String ID String name Mark marks[] int numMarks;

Student class

student(String id,String name, int name); String getId(); String getName(); double getMark(int index); void setMark(double mark, int index); double calcAvg(); Sting toString();

double mark String course

Mark class

Mark (double mark, int index); double getMark(int index); String getCourse(); String toString();

Course class:

Page 166: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

9

Your object model will be more like this now:

LESSON 9 EXERCISE 5

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:

Mark class double mark; Course course;

Student class String name Mark marks[ ]

String ID String name Mark marks[ ]

Student class

student(String id,String name, int name); String getId(); String getName(); double getMark(int index); void setMark(double mark, int index); double calcAvg(); Sting toString();

double mark Course course

Mark class

Mark (double mark, int index); double getMark(int index); String getCourse(); String toString();

String name String description String number

Course class

Course (String name, String description, String number); String toString();

School Class main()

Course class String name; String description; String number;

The School class in the main method instantiates all the required objects

Page 167: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

10

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.

super class

derived sub class total methods and variables

available to programmer

Person

Student

super class: common things name address age

sub class: unique things id

Page 168: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

11

Super and Derived classes

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 class_name extends super_class_name { variables and methods }

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.

derived sub class constructors

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.

Student (String name, String address, int age, String id)

{ // initialize super class with parameters from sub class super(name, address, age); this.id = id; // initialize student id }

Page 169: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

12

For the copy constructor you pass the sub object reference to the super class.

Student(Student s2) { super(s2); // pass to super class

this.id = id; // initialize student id }

instantiating sub classes

You intantiate sub classes just the way you instantate any class.

object_type object_reference = new constructor(optional_argument_list);

Student s1 = new Student("Tom","121 College St",25,"S3454");

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

S1.incAge(); // access method of super class Student

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

SC NSC SC NSC SC NSC SC NSC

P X X P X X P X X P

NP X X NP X NP NP

public protected friendly private super class

modifiers Sub = Sub class, C = not sub class, P = package, NP = Not Package

Page 170: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

13

overriding methods of the super class

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.

Person p1 = new Person("Tom","123 College Street",25."S3456");

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.

sub_class_object_reference . overriden_method_name ( argument_list ); s1.toString(); // call overridden string method

rules for overriding super class methods

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.

possible sub class access visibility modifiers super class

private friendly protected public private

friendly protected public friendly

protected public protected

public public

calling overridden methods of the super class

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

super . overriden_method_name ( argument_list ); super.toString(); // sub class calls the super to string method

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.

Page 171: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

14

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 // Student class derived from Person class class Student extends Person

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

Student (Student s2)

{ super(s2); // pass to super class }

// return id public String getId()

{ return id; }

//send out vehicle plant info public String toString()

{ String s = "\n" + "id: " + id + "\n"; s += super.toString(); // get super class info return s; }

} // end class student

Page 172: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

15

LESSON 9 EXERCISE 6

OVERRIDING OVERLOADED METHODS

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.

// overriding overloaded functions

// base class class Base { public int square(int x)

{ System.out.println("base int" ); return x*x; }

public double square(double x)

{ System.out.println( "base double" ); return x*x; }

}

// derived class class Derived extends Base { public double square(double x)

{ System.out.println( "derived double" ); return x*x; }

}

base int the square of 5 is: 25 derived double the square of 5.5 is: 30.25

Program Output:

Person

Student

Write a Student class that inherits a Person class. The Person class gets a name, address and phone. The student class get a student id and an array of marks. Write constructors and set() , get() and a toString() method foe each class.

Page 173: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

16

// test derived class class Driver {

public static void main(String[ ] args)

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

if(this instanceof DerivedClass)

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

Page 174: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

17

// base super class class Animal { String name = "I am a Animal";

// base function belonging to animal class public void baseMethod() { System.out.println(name); print(); // call overridden function // test and call derived class function if(this instanceof Cat)

{ ((Cat)this).derivedMethod(); // call sub method System.out.println(((Cat)this).name); // call sub variable }

}

public void print() { System.out.println( " I am an animal");} }

// derived sub class class Cat extends Animal

{ String name = "I am a Animal"; public void derivedMethod() {print();} public void print() {System.out.println(name);} }

// test driver public static void main(String[] args)

{ Animal a = new Animal(); // create an animal object a.baseMethod(); // call base function Animal c = new Cat(); // create a cat object c.baseMethod(); // call base function }

}

I am a Animal I am a Animal I am a Animal I am a cat I am a cat I am a cat

program output:

Animal

Cat

a

c

Page 175: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

18

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:

[email protected]

E-Mail all attached files of your completed exercises to:

[email protected]

Order your next lesson from:

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.

Page 176: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

1

JAVA PROGRAMMERS GUIDE LESSON 10

File: JavaL10.doc

Date Started: July 12,1998

Last Update: Dec 28, 2005

Status: proof

LESSON 10 POLYMORPHISM

Inheriting other sub classes

You may inherit classes from other sub classes.

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.

Students

History

Geography

Science

Math

Person

Page 177: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

2

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.

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[] students = new Student[maxStudents]; // array of Student object references

students Student reference

Student reference

Student reference

--->

Student reference

Student adjust()

History adjust()

Geography

adjust() Science adjust()

Math adjust()

Array of Student object references

Page 178: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

3

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.

numStudents = 0; // set number of plants to zero

The length of the Array object can be used to tell us the maximum number of Student objects.

students.length // maximum number of Student objects in array

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.

// instantiate History object and assigned to student table. students[numStudents++] = new History("Bill","32 Eglington St",22,"S4564");

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.

Student reference ----> History object

Student reference ----> Geography object

Student reference ----> Math object

Student reference ----> Science object

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.

Page 179: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

4

3 ways to refer to a object

base class reference refers to a base class

sub class reference refers to a sub class

base class reference refers to a sub class

Student v = new Student(); History h = new History(); Student s = new Student();

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.

int x = 5;

double d = x;

downward object conversions

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.

v c

Student

v History

Student

History

Student

widening conversion.

History

Student

s

h upward conversion

History h = new History();

Student s = h;

double

int

Page 180: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

5

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.

double d = 10.5;

int x = (int)d;

If the conversion cannot be made a ClassCastException is thrown.

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.

// loop through all students for (int i = 0; i < numStudents; i++)

{ 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

Geography object

Science object

Array of

Student references

Math object

History

Student

h

s downward conversion Student s = new History();

History h = (History) s;

narrowing conversion

double

int

Page 181: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

6

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.

abstract methods and classes

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.

abstract visibility return_type method_name(); // abstract method

abstract public void adjust(); // abstract method

Once your class has an abstract method you need to declare the class as abstract too:

abstract class Student // declare class as abstract

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.

MORE POLYMORPHISM EXAMPLES

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 raise() 0 % Managers

raise() 5 %

Workers raise()

2%

Sales raise()

commission

Page 182: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

7

The super class code would be like this:

abstract class Employee { private String name; private String address; protected double salary;

public Employee(String name, String address, double salary) { this.name = name; this.address = address; this.salary = salary; }

public double raise(); // abstract method }

The derive classes would be like this:

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

Page 183: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

8

// 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() 15%

Condominiums taxes() 10%

Rental taxes()

0%

Page 184: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

9

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.

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.

Rental price

Cars $24.95 per day

unlimited

Trucks $19.95 per day

10 cents per mile

Bank Account Customer

Checking Account calculate interest()

Savings Account calculate interest()

Page 185: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

10

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:

[email protected]

E-Mail all attached files of your completed exercises to:

[email protected]

Order your next lesson from:

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.

Page 186: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

1

JAVA PROGRAMMERS GUIDE LESSON 11

File: JavaL11.doc

Date Started: July 12,1998

Last Update: Dec 28, 2005

Java Version: 1.5

LESSON 11 JAVA CLASS COMPONENTS

Now we get into real JAVA Programming.

RELATIONSHIPS BETWEEN CLASSES

Class may use, contain and inherit other classes.

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 has a class B

Class B

class A super class

class B sub derived class is a derived from

class A

Page 187: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

2

The following statement demonstrates the relationship between classes.

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.

Here is the test program:

// Lesson 11 program 1

// Animal class "is a" abstract class Animal { Sound sound; // place to hold sound object abstract public void peas ( ); abstract public void speaks( ); }

// cat class inherits animal class class Cat extends Animal { Litter litterBox; // place to hold pee

public Cat (Litter litterBox ) { this.litterBox = litterBox; // use litter box sound = new Sound("meow"); }

public void peas ( ) { // test if litter box empty if(litterBox.isEmpty()) litterBox.fill(); else System.out.println("please empty the litter box") }

public void speaks( ) { sound.make(); }

}

Page 188: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

3

// litter box class "uses a" class Litter { boolean full=false; public void empty ( ) { full = false; System.out.println("the litter box is now empty"); }

public void fill( ) { full = true; System.out.println("the litter box is now full"); }

public boolean isEmpty ( ) { return !full; } }

// sound class "has a" class Sound { String sounds;

public Sound (String sound ) { this.sound = sound; }

public void make( ) { System.out.println( sounds ); }

}

// driver class class L10p1 { public static void main(String args[]) { Litter litterBox = new Litter(); Cat c1 = new Cat(litterBox); c1.speaks(); c1.peas(); c1.peas(); litterBox.empty(); }

}

main()

Cat

litterBox

Litter "uses a"

Animal "is a"

meow

the litter box is now full

please empty the litter box

the litter box is now empty

Sound "has a"

program output:

c1

Page 189: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

4

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"

"An employee i s a person that has a job and uses a machine"

CLASS DESIGN HINTS

1. Always use private variables and public methods to access them.

2. Always initialize variables to 0 and reference variables to null in your class definition. int x = 0; // set variables to zero String s = ""; // set strings to empty strings Point pt = null; // set reference objects to null

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

class system model

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

Page 190: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

5

this --> Private Variables data for storage and retrieval

Constructor initializes private variables and allocates memory

get data from outside world --> Set Methods (mutator)

put in private variables

Process Methods calculate values using private variables

get data from private variables Get Methods (accessor) -->

send data to outside world

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.

this MyArray class

int [ ] items -------> array of integers

int size number of items in array

constructor initialize number of items and allocate memory for array of items

main methods instantiate and test array class

Set methods <------ get array data from outside world

process methods do operations on array elements

---->

Get methods ------> send array data to outside world

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.

Page 191: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

6

visibility class name {

variables // store and retrieve data for the class

final variables // variables initialized once, value cannot be changed (read only)

static variables // shared variables between all instances of this class

constructor // initialize and allocate memory for variables

methods // contains variables and programming statements

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.

class visibility access

public any class can access this class

friendly only classes in the same package can access this class

protected only sub classes can access this class

instantiating a class

Classes are instantiated (created) by using the new operator.

object_type object_reference = new class_constructor.

MyArray a = new MyArray(5); // instantiate an array object of 5 elements

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.

MyArray Object a

Page 192: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

7

accessing variables and methods of a class 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 .variable_name = expression; a.size = 0; // assign 0 to the private variable belonging to the Array object

variable = object _name .variable_name; size = a.size; // assign 0 to the private variable belonging to the Array object

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.

public final class MyArray { // variable and method definition's here }

this reference to 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.

this.x = x; //assign a parameter x to the private variable x defined in the class. this.getSize(); // refers to the method getSize() defined in 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 }

Page 193: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

8

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

friendly variables only accessible by classes in same package

public variable accessible by all classes

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.

final int NumItems = 10;

static and instance variables

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 ?

Page 194: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

9

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.

class name . variable_name

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

// instantiating the Array class using a default constructor MyArray a = new MyArray();

default constructor a

Page 195: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

10

initializing constructor

Initializing constructors have a parameter list to initialize the private variables of a class to specified value.

MyArray(int size)

{ Items = new int[size]; // allocated memory for array this.size = size; // store array size in private variable }

// instantiating a class using an initializing constructor MyArray a = new MyArray(50); // set size of array to 50 items

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.

MyArray(int size, String[] v)

{ items = new int[size]; // allocated memory for array this.size = size; ; // store array size in private variable for(int i =0;i<size;i++) items[i] = Integer.intParse(v(i)); }

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

// copy constructor definition public MyArray(MyArray a2)

{ items = new int[a2.size]; // allocate memory based on a2 size

// copy items for(int i=0;i<a2.size;i++) items[ i ]=a2.items[ i ]; size = a2.size; // assign new size }

// using copy constructor MyArray a2 = new MyArray(a1);

a2 copy

constructor

class object a1

initializing constructor

argument values

conversion constructor

argument values

a2

a

a

Page 196: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

11

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.

method_visibiliy modifier return_data_type method name(paramater_list)

{ variables and statements; optional return statement }

// return index of data item if found else return -1 public int Index(int data)

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

method visibility

Methods may be public, protected or private. If they do not have a visibility modifier then they are friendly.

visibility description

private only accessible inside the class defined in

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

public accessible by all classes

static method modifier

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.

receive data values

return data values

programming statements

Page 197: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

12

return_data_type static method_name ( parameter list ) { variables and statements; }

int static count( ) // static method { 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.

int final count( int x ) // final method { return x + x; }

Set methods (mutator)

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.

// set the array an index and item value public set(int index, int data) { items[index] = data; // put data into array }

// using method set a1.set(8,33); // set the array index 8 to the value 33

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

// test if item is in the array, return true of data item if found public boolean isItemOf(int data)

{ for(int i=0;i<size;i++) if (items[i]==data) return true; // return true if item found else return false; }

// using method isItemOf a1.isItemOf(33);

Page 198: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

13

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.

// return index of data item if found public int index(int data)

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

// using method index a1.index(33);

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.

// 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; int largest;

// check array sizes if(size > a2.size) largest = size; else largest = a2.size;

temp = new Array(largest); int data1,data2; // for array values

// add two arrays for(int i=0;i<largest;i++)

{ if(i < size) data1 = items[i]; else data1 = 0; // pad with zeros if(i < a2.size) data2 = a2.items[i]; else data2 = 0; // pad with zeros temp.items[i] = data1 + data2; }

return temp; }

// using method to add two arrays a1 = a1.add(a2); a3 = a1 + a2;

temp holds the largest array

=

+

a2.items

this.items

temp.items

temp (a3)

a3 = a1 + a2

a2

this (a1)

Page 199: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

14

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

// test if two Arrays are equal public boolean isEqual(Array 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))

Get methods (accessor)

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)

{ return items[index] ; // return data at index }

// using a method to get the value of the data at an array index a1.get(5);

example instantiating an array class:

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 }

}

items

index

Page 200: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

15

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.

// copy constructor definition public MyArray(MyArray a2)

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

class_name object_name = new class_constructor;

MyArray a1 = new MyArray(); // create empty array object a1 MyArray a2 = new MyArray(5); // create an Array object a2 with 5 elements

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;

// make an array of 10 items MyArray a = new MyArray(Size);

// initialize array using set for(int i =0;i<Size;i++) a.set(i,i);

// print out array using get for(int i =0;i<Size;i++) System.out.println(a.get(i)); // print out array System.out.println(a);

// test get again System.out.println("the fifth item is: " + a.get(5)); }

[0 1 2 3 4 5 6 7 8 9] the fifth element is: 5

Page 201: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

16

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

1. Why do we need a constructor ? 2. Do we need a finalize method ? 3. Who calls the constructor ? 4. What is a default constructor ? 5. What is an initializing constructor ? 6. What is a conversion constructor ? 7. What is a copy constructor ? 8. What is the this variable ? 9. Where is the this variable ? 10. Why can't you change the this variable ? 11. What happens if you assign two classes references to each other ?

MyArray Class Code

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 }

Page 202: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

17

// copy constructor public MyArray(MyArray a2)

{ items = new int[a2.size]; // allocate memory for array elements

// copy elements one by one for(int i=0;i<a2.size;i++) items[i]=a2.items[i]; this.size = a2.size; }

// add two arrays // make a new array if one array is larger // pad excess items with zero's public MyArray add(MyArray a2)

{ Array temp; int largest;

// check array sizes if(size > a2.size) largest = size; else largest = a2.size;

temp = new Array(a2.size);

int data1,data2;

// add two arrays for(int i=0;ilargest;i++)

{ if(i < size) data1 = items[i]; else data1 = 0; // pad with zeros if(i < a2.size) data2 = a2.items[i]; else data2 = 0; // pad with zeros temp.items[i] = data1 + data2; }

return temp; }

// return array element value at this index public int get(int index)

{ return items[index]; }

items

index

=

+

a2.items

this.items

temp.items

temp (a3)

a3 = a1 + a2

a2

this (a1)

Page 203: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

18

// return index of data item public int index(int data)

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

// test if item is in the array public boolean isItemOf(int data)

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

// test if two arrays have same data items // returns true if they are the same sizes public boolean isEqual(MyArray a2)

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

// print out array public String toString()

{ String s = "\n\r [";

for(int i=0;i<size;i++)

{ s += get(i)); if(i < size-1)s += " "); }

s + = "]";

return s; }

Page 204: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

19

// set item at index public void set(int index,int data) { if(index >= size)return; items[index] = data; }

// the main method is used to test the array class. public static void main(String[] args) { final int NumItems = 10; int i;

// make array a1 MyArray a1 = new MyArray(NumItems); for(i=0;i<NumItems;i++)a1.set(i,i); // initialize

// test get method System.out.println("the fifth index item is: " + a1.get(5));

// test isItemOf method if(a1.isItemOf(4)) System.out.println("4 is item of array"); else System.out.println("4 is not item of array"); System.out.println("array a1: "),a1);

// make and initialize array a2 MyArray a2 = new MyArray(NumItems /2); for(i=0;i< NumItems /2;i++)a2.set(i,i); // set index to value System.out.println("array a2: "),a2);

// test add method a1 = a1.add(a2); System.out.println(("sum of a1 + a2",a1);

// test object references if(a1 == a2) System.out.println("a1 == a2"); else System.out.println("a1 != a2");

// test isEqual method if(a1.isEqual(a2)) System.out.println("a1 equals a2"); else System.out.println("a1 not equal a2");

// test object references a2 = a1; if(a1 == a2) System.out.println("a1 == a2"); else System.out.println("a1 != a2"); System.out.println("array a1: "),a1); System.out.println("array a2: "),a2);

// teat add again a1 = a1.add(a1); System.out.println("array a1: "),a1); System.out.println("array a2: "),a2); } /* end main */

Page 205: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

20

} // end class Array

program output:

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

the fifth element is: 5 4 is element of array array a1 [0 1 2 3 4 5 6 7 8 9] 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]

Page 206: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

21

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:

[email protected]

E-Mail all attached files of your completed exercises to:

[email protected]

Order your next Lesson from:

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.

Page 207: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

1

JAVA PROGRAMMERS GUIDE LESSON 12

File: JavaL12.doc

Date Started: July 12,1998

Last Update: Dec 28, 2005

Java Version: 1.5

ABSTRACT CLASSES AND INTERFACES

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 class class_name

{ variables, methods or abstract methods }

// example abstract class L12p1 public abstract class Animal

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

abstract super class

derived sub class

derived sub class

A class becomes an abstract class if it has 1 or more

abstract methods

Page 208: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

2

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.

Abstract Class Example

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.

// example abstract class L12p1 public abstract class Animal

{ public abstract void print(); }

// derived sub class class Donkey extends Animal

{ // pint out info public void print()

{ System.out.println("I am a donkey"); // abstract method ends with a semicolon }

// main method public void static main(String[] args)

{ Donkey d = new Donkey(); // instantiate a Donkey object d.print(); // call the print method of the derived class }

}

I am a donkey

Animal

Donkey

Page 209: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

3

INTERFACES

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:

public interface interface_name

{ static final variables; interface abstract methods; }

public interface ZooAnimal

{ public String place(); // place where animal lives }

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.

class class_name implements interface

{ variable and methods of class methods for interface }

// class implements interface ZooAnimal L12P2 class Tiger implements ZooAnimal

{ private String home; // this is where the Tiger lives

ZooAnimal

Tiger

Interface

An Interface is a pure Abstract class

Uses of interfaces

1. define what methods a class must have

2. representing many clases implementing the interface

Page 210: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

4

// constructor for derived class Tiger public Tiger(String home)

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

// main method for class Tiger public static void main(String args[])

{ Tiger t1 = new Tiger("by the monkey"); System.out.println("Hello I am a Tiger and I live "+ t1.place());

ZooAnimal t2 = new Tiger("by the monkey"); System.out.println("Hello I am a Tiger and I live "+ t2.place()); }

// where tiger lives public String place( )

{ return home; }

} // end class Tiger

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.

instantiating classes that implement interfaces You instantiate an instance of your class implementing the interface as you would normally do.

class_name object_name = new Constructor()

Tiger t1 = new Tiger("by the monkey");

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

Hello I am a Tiger and I live by the Monkey Hello I am a Tiger and I live by the Monkey

Tiger t1

Tiger t2

Page 211: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

5

interface_name object_name = new Constructor();

ZooAnimal t2 = new Tiger ("by the Monkey");

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 ?

// interface with a static variable L12P3 interface ZooAnimal

{ public static final String home = "in the Zoo"; public String place(); }

// class implements interface ZooAnimal class Tiger implements ZooAnimal

{ public Tiger () {} // default constructor

// where this animal lives public String place()

{ return home; }

// 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()); }

multiple inheritance using an interface

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.

Hello I am a Tiger and I live in the Zoo Hello I am a Tiger and I live in the Zoo

Main purpose of a interface is to represent objects that

implement it.

Variables declared in a interface must be public static final. They must be

initialized when they are declared. They cannot be changed once initialized.

Page 212: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

6

class class_name extends super_class_name implements 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( ); }

// base super class Animal class Animal { private String name; // name of animal

public Animal (String name ) // initialize name { this.name = name; }

// return name of animal public String getName() { return name; }

} // end class Animal

derived class extends super class

implements interface

super class interface

Tiger

ZooAnimal Animal

Page 213: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

7

// sub class Tiger is derived from super class Animal and implements the Zoo interface L12P4 class Tiger extends Animal implements ZooAnimal { private String home; // this is where the Tiger lives

// constructor for derived class Tiger public Tiger(String name, String home) { super(name); // give name to super class Animal this.home = home; // this is where the tiger lives }

// where tiger lives public String place( )

{ return home; }

// main method for class Tiger public static void main (String args[])

{ // instantiate a Tiger object type Tiger t1 = new Tiger ("Tony","by the monkey"); System.out.println("Hello I am " + t1.getName() + " and I live "+ t1.place());

// instantiate as a ZooAnimal object type ZooAnimal t2 = new Tiger ("Tony","by the monkey"); System.out.println("Hello I am " + ((Tiger)t2).getName() + " and I live "+ t2.place()); }

} // end class Tiger

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.

System.out.println("Hello I am " + ((Tiger)t2).getName() + " and I live "+ t2.place());

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.

Hello I am Tony and I live by the Monkey Hello I am Tony and I live by the Monkey

Notice we have to typecast to a Tiger

Tiger

Animal ZooAnimal

Interface types can represent derived objects

Page 214: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

8

implementing multiple interfaces

Classes may implement multiple interfaces. Although a class can implement multiple interfaces it may still only be derived from one super class.

class class_name extends super_class_name implements interface1, interfcace2

{ variable and methods of class methods for interface 1 methods for intwrface2 }

// interface 1 public Interface ZooAnimal

{ public String place(); }

// interface 2 public Interface ZooFood { public String eats(); }

// super class L12P5 public class Animal() { private String name; // animal name

Animal(String name) // initializing constructor

{ this.name=name; }

// return name of animal public String getName()

{ return name; }

} // end class Animal

// class that implements multiple interfaces class Tiger extends Animal implements ZooAnimal, ZooFood

{ private String home; // where the animal lives private String food; // what the animal eats

Tiger (sub class)

ZooFood (interface2)

ZooAnimal(interface1)

Animal (super class)

Page 215: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

9

// initializing constructor Tiger(String name,String home, String food)

{ super(name); // initialize super class this.home = home; this.food = food; }

// where tiger lives public String place( )

{ return home; }

// what tiger eats public String eats( )

{ return food; }

// main method for class Tiger public static void main(String args[])

{ // 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());

// instantiate as a ZooAnimal object type ZooAnimal t2 = new Tiger("Tony","by the monkey", "ice cream"); System.out.println( "Hello I am " + ((Tiger)t2).getName() + " and I live "+ t2.place() + " and I eat " +((Tiger)t2).eats());

// instantiate as a ZooFood object type ZooFood t3 = new Tiger("Tony","by the monkey", "ice cream"); System.out.println( "Hello I am " + ((Tiger)t3).getName() + " and I live" + ((Tiger)t3).place() + " and I eat " + t3.eats()); }

} // end class Tiger

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

Page 216: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

10

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

DERIVING INTERFACES FROM INTERFACES

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.

public interface interface_name extends 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 !

interface Zoo // base super interface

{ void print( ); }

interface ZooAnimal extends Zoo // derived sub interface

{ public String place ( ); }

interface ZooFood extends Zoo // derived sub interface

{ public String eats ( ); }

Zoo

ZooAnimal ZooFood

Page 217: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

11

// super class L12P6 public class Animal()

{ private String name; // animal name

Animal(String name) // intitializing constructor

{ this.name=name; }

}

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

Tiger (sub class)

print()

ZooFood (derived sub interface2)

eat()

ZooAnimal (derived sub interface1)

place()

Animal (super class)

Zoo (super Interface)

print()

If a class implements an interface it also implements the super interface

Page 218: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

12

// constructor public Tiger(String name, String home, String food)

{ super(name); this.home = home; this.food = food; }

// what this animal eats public String eats ( )

{ return food; }

// where this animal lives public String place( )

{ return home; }

// print out info about this animal public void print( )

{ 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(); }

} // end class tiger

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

Page 219: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

13

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.

APPLICATION USING INTERFACES

ARRAYDATA CLASS AND ARRAYDATAOPS INTERFACE

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.

array class rewritten

using ArrayDataOps

interface for the array items

array data class

implementing ArrayDataOps

interface class

interface class

Array

ArrayData

ArrayDataOps

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.

// array data Operations interface interface ArrayDataOps

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

Page 220: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

14

The methods are:

add add two ArrayDataOps objects

equals test if two ArrayDataOps objects are equal

toString convert an ArrayDataOps object 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:

// array data class class ArrayData implements ArrayDataOps

{ private int item; // array data element

// constructor public ArrayData (int data ) {item = data;}

// add two items public ArrayDataOps add(ArrayDataOps d) { // add the item's and typecast d to ArrayData return new ArrayDataOps(item + ((ArrayData)d).item); }

// test if two data items equal public boolean equals (ArrayDataOps d) { return(item == ((ArrayData)d).item); // test if both items equal }

// convert integer to string public String toString( ) { return Integer.toString(item); }

} // end ArrayData class

All data is passed using ArrayDataOps interface

Page 221: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

15

ARRAY CLASS USING ARRAYDATAOPS INTERFACE

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.

import java.io.*;

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

Array class

items

ArrayDataOps Interface

ArrayData Class

array of ArrayDataOps references

Page 222: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

16

// copy an Array object public Array(Array a2)

{ items = new ArrayDataOps[a2.size]; for(int i=0;i<a2.size;i++)item[i]=a2.items[i]; size = a2.size; }

// add two Array objects // make a new array if one array is larger // pad excess items with zero's public Array add(Array a2)

{ Array temp; int largest;

// compare size of two arrays if(size > a2.size)largest = size; else largest = a2.size;

temp = new Array(largest);

// store array item values ArrayDataOps data1,data2;

// add two arrays for(int i=0;i<largest;i++)

{ if(i < size) data1 = items[i]; else data1=new ArrayData(0); // pad to zero

if(i < a2.size) data2 = a2.items[i]; else data2=new ArrayData(0); // pad to zero

// call add method from class implementing ArrayDataOps temp.items[i] = data1.add(data2); }

return temp; // return Array object }

// get item at index public ArrayDataOps get(int index)

{ return items[index]; }

Page 223: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

17

// return index of data item public int index(ArrayDataOps data)

{ for(int i=0;i<size;i++) // call equal method from class implementing ArrayDataOps if(items[i].equals(data))return i; return -1; }

// test is item is in the array public boolean isItemOf(ArrayDataOps data)

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

for(int i=0; i<size; i++) // call equal method from class implementing ArrayDataOps if(!(items[i].equals(a2.items[i]))) return false; return true; }

// print out array public void toString()

{ String s = "\n\r [");

for(int i=0;i<size;i++) { s += get(i); if(i < Size-1)s+= " "; }

s += "]"; }

Page 224: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

18

// set item at index public void set(int index,ArrayDataOps data)

{ items[index] = data; }

// main method

// the main method is used to test the array class. // we create ArrayData objects to put into our Array object public static void main(String[] args)

{ final int SIZE = 10;

// make a new array object a1 Array a1 = new Array(SIZE);

// initialize array a1 for(int i=0;i<SIZE;i++) a1.set(i,new ArrayData(i));

// print out items from a1 System.out.println("the fifth item is: " + a1.get(5));

// test if data element in array if(a1.isItemOf(new ArrayData(4))) System.out.println("4 is item of array"); else System.out.println("4 is not item of array");

// 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 arrays equal if(a1 == a2) System.out.println("a1 == a2"); else System.out.println("a1 != a2");

Page 225: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

19

// test data equal if(a1.isEqual(a2))System.out.println("a1 equals a2"); else System.out.println("a1 not equal a2");

// set two arrays to each other a2 = a1;

// test if equal if(a1 == a2)System.out.println("a1 == a2"); else System.out.println("a1 != a2");

// print out array a1 System.out.println("array a1: ",a1);

// print out array a2 System.out.println("array a2: ",a2);

// add array a1 to itself a1 = a1.add(a1);

// print out array a1 System.out.println("array a1: ",a1);

// print out array a1 System.out.println("array a2: ",a2); }

} /* end main */ } // end Array class

program output:

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.

the fifth element is: 5 4 is element of array array a1 [0 1 2 3 4 5 6 7 8 9] 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]

Page 226: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

20

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.

Page 227: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

21

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:

[email protected]

E-Mail all attached files of your completed exercises to:

[email protected]

Order your next lesson from:

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.

Page 228: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

1

JAVA PROGRAMMERS GUIDE LESSON 13

File: JavaL13.doc

Date Started: July 12,1998

Last Update: Dec 29, 2005

Java Version: 1.5

VECTORS, ENUMERATIONS and ITERATORS

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:

class method description

public Vector (int initialCapacity, int capacityIncrement)

constructs an empty vector with the specified initial capacity and 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 (Object anArray[])

copies the components of this vector into the specified array.

public final synchronized void trimToSize() trims the capacity of this vector to be the vectors current size

public final synchronized void ensureCapacity (int minCapacity)

increases the capacity of this vector

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 boolean isEmpty() returns true if vector has no components

Page 229: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

2

class method description

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 (Object obj, int index)

Sets the component at the specified index of this vector the previous value is overwritten

public final void insertElementAt (Object obj, int index)

Insert the component at this index, each component from the 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 (int index)

removes the object at the index from the vector and rest of 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

public final String toString() returns a string representation of this vector

Page 230: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

3

USING VECTOR CLASS

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:

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.

4 2 5

Page 231: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

4

Vector class using Java 1.5

When you use the Vector class with Java 1.5 you must specify the data type it contains in triangle brackets <>

Vector<Integer> v = new Vector<Integer>(); // make vector object

This makes the Vector class easier to use because type casting is no longer needed

Integer num1 = v.elementAt(1); // get number 1 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)

Note: F:\courses\java\programs\VectorTest.java uses unchecked or unsafe operations.

Note: Recompile with -Xlint:unchecked for details.

If you compile with

Javac -Xlint:unchecked VectorTest

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 {

// example using vector class public static void main(String args[]) { Vector<Integer> v = new Vector<Integer>(); // 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 = 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 = v.elementAt(1); // get vector 1

System.out.println(num1); // print out value }

}

Page 232: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

5

Printing out Vector values

You can use an for loop to print out the vector element values.

for(int i=0;i < v.size(); i++) {

Integer num = (Integer)v.elementAt(i);

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.

for (Integer num: v) {

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

boolean hasMoreElements(); check if any more objects available

Object nextElement(); get next object stored

// Enumeration Interface located in java.util.Enumeration public interface Enumeration

{ boolean hasMoreElements(); // any items left ? Object nextElement(); // get next item }

Enumeration's let you get object by object from a list of objects

Page 233: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

6

Enumeration example using Vector class object

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;

Vector v = new Vector(Size); // create a vector element

// initialize vector values to its own index for(int i=0;i<Size;i++) v.addElement(new Integer(i+1)); // get reference to enumeration Enumeration e = v.elements();

// iterate through enumeration while(e.hasMoreElements())

{ Object obj = e.nextElement(); // get element object System.out.print(obj.toString() + " "); // print out object }

}

}

Making your own Enumeration 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.

1 2 3 4 5 6 7 8 9 10

Page 234: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

7

import java.util.Enumeration; // class to make your own enumeration L13P2 class ArrayEnumeration implements Enumeration

{ Object[] array; // array to enumerate on int current = 0; // Current element index int size = 0; // index of the last element in the array

// constructor get an array of objects, and number public ArrayEnumeration(Object[] array, int size)

{ this.array = array; // store array this.size = size; // last element in array }

// check if any more objects public boolean hasMoreElements()

{ return current < size; // return true if not last element }

// get current object, then point to next object public Object nextElement()

{ return array[current++]; // return current item in array }

} // end class ArrayEnumeration

using ArrayEnumeration class

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 {

// Enumeration example using vector class public static void main(String args[])

{ // initialize an array of String items to put into vector String[] a = {"1","2","3","4","5","6","7","8","9","10");

// instantiate an ArrayEnumeration object ArrayEnumeration e = new ArrayEnumeration(a,a.length);

Page 235: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

8

// iterate through enumeration while(e.hasMoreElements())

{ Object obj = e.nextElement(); // get element object System.out.print(obj.toString() + " "); // print out object }

}

}

LESSON 13 EXERCISE 2

Add an Enumeration method to the Array class of the last lesson.

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.

Iterator itr = v.iterator();

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

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

Iterator itr = v.iterator();

while(itr.hasNext()) {

Integer num = (Integer)itr.next();

System.out.println(num); } } }

1 2 3 4 5 6 7 8 9 10

Program output:

1 2 3 4

Page 236: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

9

Iterator using java 1.5

To use the Itrerator with Java 1.5 we must specify the data type for the Vector and Iterator.

Vector<Integer> v = new Vector<Integer>(); // make vector object

Iterator<Integer> itr = v.iterator();

Here is the same program using java 1.5

import java.util.Vector; import java.util.Iterator;

class IteratorTest2 {

// example using iterator class public static void main(String args[]) {

Vector<Integer> v = new Vector<Integer>(); // 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

Iterator<Integer> itr = v.iterator();

while(itr.hasNext()) { Integer num = itr.next();

System.out.println(num); }

}

}

Page 237: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

10

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:

[email protected]

E-Mail all attached files of your completed exercises to:

[email protected]

Order your next Lesson from:

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.

Page 238: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

1

JAVA PROGRAMMERS GUIDE LESSON 14

File: JavaL14.doc

Date Started: July 12,1998

Last Update: Dec 29, 2005

Java Version: 1.5

ARRAYLIST and EXCEPTIONS

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.

Class method Description

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.

voidclear() Removes all of the elements from this list.

Object clone() Returns a shallow copy of this ArrayList instance.

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.

Page 239: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

2

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.

boolean isEmpty() Tests if this list has no elements.

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 removeRange(int fromIndex, int toIndex)

Removes from this List all of the elements whose index is between 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.

int size() Returns the number of elements in this list.

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.

Here is our test program from previous lesson using an ArrayList

import java.util.ArrayList; import java.util.Iterator;

class ArrayListTest {

// example using arraylist class public static void main(String args[]) {

Page 240: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

3

ArrayList list = new ArrayList(); // 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

Iterator itr = list.iterator();

while(itr.hasNext()) {

Integer num = (Integer)itr.next();

System.out.println(num);

}

for(int i=0;i < list.size();i++) {

Integer num = (Integer)list.get(i);

System.out.println(num);

}

}

}

Here is the same program using java 1.5

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

1 2 3 4 1 2 3 4

Page 241: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

4

Iterator<Integer> itr = list.iterator();

while(itr.hasNext()) {

Integer num = itr.next();

System.out.println(num);

}

for (Integer num: list) {

System.out.println(num);

}

}

}

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)

{ int x = 10; x = x / 0; }

}

Exception in thread "main" java.lang.ArithmeticException / by zero at ExceptionTest2.main (ExceptionTest2.java:9)

program output:

Page 242: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

5

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)

{

int x = 10; try

{ x = x / 0; }

catch(ArithmeticException e )

{ // report exception e.printStackTrace(); System.out.println(e); }

System.out.println("program still running"); }

}

LESSON 14 EXERCISE 3

Try out the above programs. Which one do you like the best ?

java.lang.ArithmeticException java.lang.Throwable() java.lang.Exception() java.lang.RuntimeException() java.lang.ArithmeticException() void ExceptionTest.main(java.lang.String []) java.lang.ArithmeticException java.lang.ArithmeticException / by zero

program output:

Page 243: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

6

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

exceptions derived from exception class

Exception is the super class where these exception classes are derived from.

derived from Exception class package reason thrown

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.

(2) when an application tries to create an instance of a class and the current method does not have access to the default constructor.

InstantiationException java.lang when an application tries to create an instance of a class but the specified class object cannot be instantiated because it is an interface or is an abstract class.

InterruptedException java.lang when a thread is waiting, sleeping, or otherwise paused for long time and another thread interrupts it using the interrupt method in class Thread

NoSuchMethodException java.lang Thrown when a particular method cannot be found.

Page 244: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

7

derived from Exception class package reason thrown

Runtime java.lang run time exceptions, null reference, array out of bounds

IOException java.io an I/O exception has occurred.

AWTException java.awt an Abstract Window Toolkit (GUI) exception has occurred.

exception classes derived from IOException class

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.

derived IOException class package reason thrown

CharConversionException java.io convert a character

EOFException java.io end of file or data stream

FileNotFoundException java.io file cannot be found

InterruptedIOException java.io I/O operation has been interrupted

SyncFailedException java.io sync operation has failed

UTFDataFormatException java.io a malformed UTF-8 string has been read in a data (UniText Format Error)

MalformedURLException java.net a malformed URL has occurred (Uniform Resource Locator)

ProtocolException java.net indicate that there is an error in the underlying protocol

SocketException java.net there is an error in the underlying protocol

UnknownHostException java.net the IP address of a host could not be determined.

UnknownServiceException java.net indicate that an unknown service exception has occurred.

exception classes derived from RuntimeException class

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.

RuntimeException classes package reason thrown

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.

Page 245: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

8

RuntimeException classes package reason thrown

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.

IndexOutOfBoundsException

java.lang an index of an array, a string or a vector is out of range.

NegativeArraySizeException java.lang if an application tries to create an array with negative size.

using checked exceptions

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.

modifiers return_type method_name (paramater_list) throws checked_exception public static void main (String[] args) throws IOException

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 {

BufferredReader 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); System.out.println(10/x); } } }

Page 246: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

9

LESSON 14 EXERCISE 4

Re-write the above program using a try/catch block. Call your class CheckedTestTry

throwing Java exceptions

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.

throw new Exception_object("optional message");

throw new ArithmeticException("x is 0");

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

}

}

LESSON 14 EXERCISE 5

Re-write the above program using a try/catch block. Call your class ThrowTestTry

Throwing an exception is like a return statement. You are returning an exception object to the calling method. A method can return a value or a exception object.

called method

calling method

return exception object

call method

Page 247: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

10

creating your own exception classes

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.

// derive a class from the exception base class class ArrayException extends Exception { public ArrayException() // default constructor { super(); // initialize super class }

// initializing constructor with exception message public ArrayException(String msg); { super(msg); // print out message describing fault } }

using the array exception class

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 }

// add an array element at specified index public void put(int value, int index)throws ArrayException { // check for index out of bounds if(index <0 | | index > size) throw new ArrayException(( "index out of bounds: " + index); else items[index] = value; // write value to array at specified index }

Page 248: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

11

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

// derive a class from the exception base class class ArrayIndexException extends ArrayException { public ArrayIndexException() // default constructor { super(); // initialize super class }

// initializing constructor with exception message public ArrayIndexException(String msg); { super(msg); // print out message describing fault } }

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

ArrayException

ArrayIndexException

Page 249: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

12

// initializing constructor that throws an ArrayException with a negative size Array(int size)throws new ArrayException { if(size < 0)throw new ArrayException("wrong size: " + size); item = new int[size]; // create array of integers this.size = size; // store size of array } // add array element at specified index, throws an ArrayIndexException when a out of bound array index is found public void put(int value, int index)throws ArrayIndexException { // check for index out of bounds if(index <0 | | index > size) throw new ArrayIndexException("bad index: " + index); else array[index] = value; // write value to array at specified index } } }

LESSON 14 EXERCISE 7

Write the ArrayTest class for the MyArray class. Test it with by creating arrays of all different sizes.

CATCHING MORE THAN 1 EXCEPTION

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.

try { // code to try }

// specific exception catch (specific exception e) {

}

// other exception catch(specific exception e) {

}

class MyArrayTest { // main method public static void main(String args[]) { try { MyArray a = new MyArray(-5); // create MyArray object a.put(5,10); // write 5 to array at index 10 }

// specific exception catch(ArrayIndexException e) { System.out.println(e); // report index out of bound }

Page 250: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

13

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

OVERRIDING EXCEPTION METHODS

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

sub class method()

super exception class

sub exception class

SE

SubE

Page 251: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

14

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.

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.

// expandable array class class ExpandArray extends Array { private int max; private static final int Step = 16; }

// store size and max upper limit ExpandArray(int size, int max) throws ArrayException { super(size); this.max = max; }

// add an array element at specified index, increase array size if necessary

super class method()

super exception class

sub class method()

sub exception class

SubE

SubE

MyArray class

Expandable Array class

Page 252: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

15

public void put(int value, int index)throws ArrayIndexException, ArrayFilledException { // check for index out of bounds if(index > size) { if(size+Step > max) throw new ArrayFilledException("array filled: " + index); int[] temp = new int[size+Step]; for(int i=0;i<size;i++)temp[i]=items[i]; items=temp; size = Step; }

super.put(value,index); // call super class put }

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.

class hierarchy exception hierarchy

MyArray class

Expandable Array class

ArrayException

ArrayIndexEception

ArrayFilledException

Page 253: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

16

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:

[email protected]

E-Mail all attached files of your completed exercises to:

[email protected]

Order your next Lesson from:

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.

Page 254: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

1

JAVA PROGRAMMERS GUIDE LESSON 15

File: JavaGuide15.doc

Date Started: July 24,1998

Last Update: Dec 28, 2005

Java Version 1.5

JAVA CORE COURSE PROJECT PROJECTS = WORK = LEARNING = FUN

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

item name "super ex"

item number 1000765

description 2000 Ghz, 512 MB, 100 Gig drive

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.

Page 255: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

2

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.

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

StoreItem

videos computers

cd's

Store class array of

item

Page 256: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

3

You may need two menu's one for the Customer and the other for the StoreOwner. When a Customer buys an item you may want to keep track of the Customer and what items they have bought. You will need a Customer class to hold information about a customer and what items they have bought. In the Store class add an additional array to keep track of the customers. A customer may buy more than 1 item. If this is the last item then you should print out a bill listing all the items the customer has bought. Your customer class would need an array of item objects bought. The store item class will also be used for the Customer. In this case the quantity will refer to how many items the customer has bought. The back order would represent the number of items this customer has ordered when your store is out of stock. Your store class would now have two arrays of objects. Array of items for sale and an array of customer objects.

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

Store class

array of Customers

Customer class array of

bought items array of

Items for sale

Page 257: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

4

Marking Scheme:

CONDITION RESULT GRADE

Program crashes Retry R

Program works Pass P

Program is impressive Good G

program is ingenious Excellent E

Hints on completing Project:

(1) Sketch a operational model first

(2) Write all the class definitions first

(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

Page 258: Java eBook

www.cstutoring.com E-Learning, E-Books, Computer Programming Lessons and Tutoring

5

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:

[email protected]

E-Mail all attached files of your completed exercises to:

[email protected]

Order your next Lesson from:

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.