Docsity

Java Laboratory Manual - Revised Edition 2002 | EEL 4851, Lab Reports of Electrical and Electronics Engineering

Partial preview of the text

Download Java Laboratory Manual - Revised Edition 2002 | EEL 4851 and more Lab Reports Electrical and Electronics Engineering in PDF only on Docsity!

University of Central Florida

Engineering Data Structures

EEL 4851

JAVA

LABORATORY MANUAL

(Revised edition, 2002)

Maureen Murillo

Avelino González

EEL 4851 – Engineering Data Structures

Introduction to Java – the Language

Java has quickly emerged as one of the most popular languages of the late 1990’s. It has transitioned from a special-purpose language used in Internet applications to a general purpose one used in many cases where C, C++ were once used. This laboratory manual will teach the student the basics of Java, both as a general-purpose language as well as the Internet language. It includes this Introduction Section and 12 laboratory sessions. The most important part of learning any computer language is to use it. This manual forces the reader to do just that. If the reader is not able or willing to implement the laboratory sessions, then he/she should look for an alternative learning instrument.

What has made Java so popular is its ability to run on any hardware platform. Other high-level languages that have become standardized (C, C++, Lisp, Fortran and several others) do in fact have standard source code that, when compiled with a compiler specially designed for a particular hardware platform and operating system, it will run on that platform. When the program is to be ported to another platform, the source code must be re-compiled with a compiler for the new platform. While this avoids having to rewrite the program in a different way if the language were not standard, in practice, however, a long and complex program written in one standard language will require some modifications when compiled for another platform and/or operating system. But object code compiled under one compiler will not run on a platform for which that compiler was not designed. This is because the microprocessors and/or the operating system are designed such that they do not operate exactly the same way. But Java object code will run on (almost) any microprocessor. This is important from the standpoint of the Internet, where one does not always know the type of computer platform and operating system on which an application will be asked to run.

Java originated from an effort in the early 1990’s at Sun Microsystems to write a language that could be run on all home appliances, such as microwave ovens, VCR’s, etc. This is actually a difficult task, as the microprocessors found on such devices are inexpensive and of many variations. Thus, it had to be compatible with many processors. A few years later, it was determined that the approach taken by the developers of Java would be more useful in an Internet environment. The rest is history.

Java embodies portability by “compiling” the source code, not to machine language, but to byte code. Byte code is an intermediate level representation that represents the way in which most microprocessors do things. Such a representation is called the Java Virtual Machine , and is similar to most common microprocessors. Each family of microprocessor (Intel, Motorola, etc.) has a specific way in which they do things – their instructions, memory organization, registers, etc. However, as a whole, they do things much more similarly than they do differently. Java takes advantage of this fact. The byte code is actually representative of most microprocessors – not exactly any one of them, but very similar to all of the most common ones. Thus, only one Java compiler is necessary, as its output will be the same (byte code) regardless of on which machine the Java code will be executed.

But, of course, byte code will not by itself run on any microprocessor. It requires an additional step – the interpretation step. As the byte code is executed, an interpreter will interpret every instruction and convert it into the actual machine representation for

that platform. The advantage is that while compilers are highly complex and expensive systems, byte code interpreters are much easier to write and maintain, since most of the work is already done by the Java compiler. If every computing platform has its own Java byte code interpreter, then Java object code can be run seamlessly.

The drawback is that being an essentially interpreted language, Java can be slower than the fully compiled and optimized C and C++ programs. Other traditionally interpreted languages such as Basic and Lisp lost popularity when commercial applications were being developed partially due to their interpreted nature resulting in slow execution. However, the Java interpretation is faster than that of those older languages because the line of source code is not being interpreted, but rather, an intermediate, and rather low level implementation.

The Java syntax is suspiciously similar to C and C++. In fact, Java is easy to understand if you already know those languages. However, there are several significant differences:

  • Java is completely object-oriented. C++, although it allows (and encourages!) the use of classes, does not require the programmer to do so. Java does.
  • Java does not allow pointers. While this greatly reduces the power of the programmer to dwell at the memory levels, it does provide a level of safety and a program structure that is better in the end. Students everywhere cheer this aspect of Java after they learn C/C++.

This laboratory manual is written with the assumption that the student already knows C++ to the point that he/she can write non-trivial programs in C++.

There exist two types of Java programs: applications and applets. Applications are standalone programs such as would be written in C and C++. This is where the general- purpose aspect of Java comes in. Programs that were previously written in C and C++ can now be written wholly in Java, notwithstanding the accompanying reduction in execution speed.

Applets are similar to applications, but they don't run standalone. Instead, applets adhere to a set of conventions that lets them run within a Java-compatible browser (for example, Netscape or Internet Explorer). This is the special purpose nature of Java (for which it was intended originally).

In this course we will cover both of these aspects of Java. We will begin by showing you how to write and run a simple Java standalone program. This is the same as the “Hello World” that is commonly run in C/C++ courses as the first example. It will teach the student how to write a simple Java program and what the different lines of code mean. In next chapters we will show you the basic differences about the main programming aspects between Java and C++. In chapter 9, we will cover simple applets, with some GUI components. The last chapter introduce you in the topic of data structures, showing you how to build a stack, a queue, a list and a binary search tree.

3. Running the application

Run the program using the Java interpreter. You should see "Hello World!" displayed. Type in the command line:

java HelloWorldApp

The argument to the Java interpreter is the name of the class to run, not the name of a file. In this simple example, they are the same, but this may not be the case other times. Be sure to capitalize the class name exactly as shown above.

4. Understanding your "HelloWorld" application

Now that you've written, compiled and run a simple Java application, let’s discuss what you did so that you might better understand it. What you wrote is a Java application – a stand-alone Java program. This is a program that is capable of running on a computer independent of any other program such as an Internet browser. This is equivalent to a C++ program.

4.1. Comments in Java code.

The Java language supports three kinds of comments:

*1. / text */

  1. /** documentation */
  2. // text**

In the first one, the compiler ignores everything from /* to */. This is as in C.

The second one, a slight variation of the first one, indicates a documentation comment ( doc comment, for short). The compiler ignores this kind of comment, just like it ignores comments that use /* and */. The JDK javadoc tool uses doc comments when preparing automatically-generated documentation.

The third comment format directs the compiler to ignore everything from // to the end of the line. This is as in C++.

4.2. Defining a class.

In object oriented terminology, a function that is a member of a class is called a method. Since Java is completely object-oriented and stand-alone functions are not permitted, all functions are referred to as methods. Furthermore, all variables exist within a class or an object (an instance of a class). The Java language does not support global functions or variables. Thus, the skeleton of any Java program is a class definition.

A class is the foundation of any object-oriented language such as Java. A class is a template that describes all associated with the instances of that class – data members as well as its behavior indicated by the methods. When you instantiate a class you create

an object that resembles other instances of the same class, although with different values.

Defining a class in Java is very similar to C++:

class name {

... }

As in C++, the class keyword begins the class definition of a class named name. All variables and methods are defined within the brackets that form its definition. The "Hello World" application has no variables and only one single method named main.

4.3. The main method.

The entry point of every Java application is its main method. This is the equivalent of the main() function in C/C++. When running an application program, the name of the class to be run must be specified. The interpreter invokes the main method defined within that class. The main method kicks off the execution, and runs any other methods defined in the program as needed. Thus, to begin the Java execution, the name of the class that contains the main method must be invoked. If the class invoked does not contain the main method, the Java interpreter will not execute the program. Once again, it is basically running the main() function in C/C++, except that in Java, it must be contained within a class.

Therefore, every Java application must contain a main method. Its format is as follows:

public static void main(String[] args)

  • As in C++, the public keyword means that any object in the program can call the main method.
  • The keyword static indicates that the main method is a class method. This means that the method does not change objects of its own class – yet, the method must be invoked tied to the class and not to an object of that class.
  • The keyword void means, similarly to C/C++, that the main method doesn't return anything.

The main method accepts a single argument: an array of elements of type String.

…. main(String[] args)

This array is the mechanism through which the runtime system passes information to your application. Each String in the array is called a command-line argument. Command-line arguments let users affect the operation of the application without recompiling it. For example, a sorting program might allow the user to specify that the data be sorted in descending order with this command-line argument:

The user then types in this/her name from the keyboard, and the systems captures it.

Jennifer

Then, knowing the user’s name, it should ask how old the user is.

How old are you, Jennifer?

Jennifer then states she is 21.

21

When the user enters his/her age, the program simply says “ Thanks a bunch ”. In the case of Jennifer,

Thanks a bunch.

Then exits.

In order to do this, you will need to use an input class. This input class has been loaded into your hard drive, and it is called MlmIn. This input class is not a primitive class in Java, but was written by the authors specifically for this book. Java has no primitive class to do simple inputs. This is another disadvantage when compared to C/C++, which enjoy many primitive input functions.

As you use the command #include in C++ to employ libraries and to increase the functionality of your program, in Java you have to use the command import followed by the name of the class and a semicolon in order to utilize supporting classes or methods of them.

Some of the input methods that this class MlmIn has are: readChar(), readInt() and readString(). These methods are static, so you can call them by typing the name of the class, followed by a period and by the name of the method. The result of each method should be assigned to an appropriate variable.

You may need to know that Java has a primitive type called int (for integer variables) and the type String (for lines of text). This last type implements a whole class that facilitates the manipulation of text in Java, in contrast with the necessity in C++ of declaring a character array in order to store a string. To declare a variable, just write the type of the variable and then the name you select for your variable.

The last aspect of Java you may need in order to implement this program is that the method for displaying information on the screen can accept more than one parameter, for example, a string of text and a variable. All the parameters within the parenthesis should be concatenated with the symbol +. For example,

System.out.println("The product of " + n1 + " and " + n2 + " is " + n1n2);*

where n1 and n2 are integer variables.

Chapter 2

Classes and Objects in Java

As mentioned in Chapter 1, Java shares much of its syntax with C++. This is good if you are a C++ programmer. Bad if you are not. However, Java seems to make programming easier than with the overly complex C++ syntax. This chapter will discuss how to create classes in Java, and how it is similar or different from C++.

1. Class definitions in Java

You have already seen how to create a class in Java. As you already should know, the basic structure of a class is:

access class name {

... }

where access is the optional label public, and the name is any label chosen for the class by the programmer. This is very similar to C++ except for the existence of the package class access. This is the topic of discussion here.

Private or protected access does not make sense for classes, so they can only have either public or package access. Public access in a class means that it can be used by methods of any other object or class in the entire program. This type of access must be declared explicitly with the modifier public. Classes without the public access modifier can only be used by classes or objects within the same package (a package is a collection of classes grouped under the same name). This is the package access type.

Therefore, the default access is package. The public access specifier must be explicitly used whenever public access is desired. Yet, an explicit package access label is illegal. If package access is desired, you must leave the access label field blank. A Java source file can only have one public class (at most), and as many package classes as necessary. Remember that the name of the file and the name of the public class must match exactly.

We will next discuss how to define data and procedural members in Java classes.

2. Defining data members in a Java class

There are two types of variables in Java:

  1. Primitive variables
  2. Object variables

Primitive variables are simply the variables that we all know and love from other programming languages. They are of a primitive data type. The primitive data types in

public static char letter = ‘M’;

3. Constants in Java

Just as constants can be defined in C++ by preceding the variable with the word const , the same can be done in Java. The way to do it is by preceding the declaration of the variable with

public static final

This means that the value of the constant cannot be changed. Public and static are not strictly necessary, but it is common to use them to denote public access and static scope.

4. Defining methods in a Java Class

Methods in Java are the member functions in C++. Unlike C++, however, which encourages the separate definition of the member functions, Java requires that the methods be defined inside the class definition. This eliminates the need for the scope definition operator commonly used to define member functions in C++ outside the class definition brackets.

As in C++, the methods must have an access specifier. Typically, methods are public, but they may be private or protected in some cases.

The format of a method, as we saw in the previous chapter, is as follows:

< access > < method flag - optional > < returns > < name > ( )

  • As in C++, the access keyword indicates who can access that method. It is typically set to public for a method. The differences between the distinct access modifiers (public, private and protected) for methods are the same than those for the data members, including the fact that if you don’t specify the access keyword the default access is package.
  • The method flag is optional and when static is placed therein, it will indicate that the method is a class method. Class methods cannot operate on objects, and instance methods must only operate on objects. Since numbers are not objects, they must be manipulated only by class methods. If static is not used, then it is assumed that the method is not a class method.
  • The returns field indicates what the method returns. This is similar to functions defined in C and C++. void means that the method doesn't return anything.
  • The name field is the label for that method.
  • The declaration of parameters works in the same way than in C++. You declare a list of parameters separated by comas and where each parameter is preceded by its type.

To the class defined above, add a public method that calculates the day of the year and sets the value of a third variable, a float called doy , to the result. Then print out the value of that variable. Again, because the main method is static, it can only make reference to static data members and to static methods. So you need to declare the second method as static.

5. The new operator

The new operator makes an instance (an object) of a class. Of course, the class must be already defined, and a variable of the type of the class must already be declared.

;

= new ( );

This can be alternatively done in one line as follows:

= new ( );

But this is more important than it seems. Variables of a primitive type are locations in memory where the value of the variable is held. However, an object instantiated by new does not hold the object itself, but the address in memory where the object is located. Yes, a pointer! This is very similar to the operator of the same name in C++ that returns a pointer to a dynamically allocated block of memory.

Define a class called DayOfYear that contains the data members and the method to compute the day of the year as done previously in the main method. In this case, define the class and instantiate an object of the same class from the main method. After instantiating it, call its method that calculates the day of the year and that prints it out. This method and the data members of the class have to be nonstatic because now you are going to instantiate the class in the main method and you will call the method that calculates the result tied to the object.

6. Constructors

The theory of constructors in Java is basically the same than in C++. Their purpose is to initialize the data members of the class. If the constructor does not have any parameters, it is called the default constructor.

A class can have more than one constructor, and the name of all of them must match the name of the class. As in C++, the constructors don’t return any value and you don’t have to include the word void in its definition.

A difference with C++ is that the constructor of a class is called in Java only when you use new to create an instance of the class. For example:

DayOfYear obj = new DayOfYear ( ) ;

class myobj { public int data1 = 3; }

class change { public static void add(int x, myobj y) { x = x + 2; y.data1 = y.data1 + 2; } }

Chapter 3

Control Structures and Memory Management in Java

This chapter deals with defining the control structures in Java. Since they are very similar to those of C and C++, this chapter constitutes a review and a confirmation of them. Related to the control structures, we will mention different types of operators that are usually necessary in the construction of control structures. Finally, we will cover a topic that usually constitutes a source of errors in a program: pointers, and how to finalize objects.

1. Operators

Relational operators: < : less than <= : less than or equal to

: greater than = : greater than or equal to = = : equal to != : different to

Logical operators: && : and || : or ^ : exclusive or ! : not

Arithmetic operators: + , - , ***** , / and % (modulus).

Assignment operators: += , -= , *= , /= and %=. These operators carry out the specified operation and the assignation in a single step. For example, num += 2; assigns to the variable num the addition of the value in num and the value 2.

Incremental and Decremental operators: let num be an integer variable, ++num : pre-increment num++ : post-increment --num : pre-decrement num-- : post-decrement

2. if/else – Selection structure

The if-else structure works in the same way than it does in C++. Its format is:

if ( condition ) {

... } else { ...

the case with value2 and the case with value3. The default case is optional and it would be executed if none of the other cases were evaluated to true.

We will combine the switch with the for structure in the next section to improve the class DayOfYear.

4. for – Repetition structure

The for structure doesn’t have any change respect to C/C++. Its format is:

for ( initialization_control_var; boolean_expression ; update_control_var ) {

... }

An example of this structure is: for (int i=1; i<=10; i++) { ... }

Improve the accuracy of the method that calculates the day of the year in the class DayOfYear, including a for loop that goes from 1 (January) to the month before the month specified by the user in order to accumulate the correct number of days for each month. Inside the for loop you have to include a switch structure that selects the number of days to add depending on the month.

5. while – Repetition structure

The format of the while structure is:

while ( condition ) { ... }

With the while , the body of the loop will be executed as long as condition is true. It could happen that the statements in the body will never be executed if the condition is false since the first time that is evaluated.

6. do/while – Repetition structure

The do-while structure is very similar to the while , except that the condition is evaluated at the end of the loop, what causes that the body of the loop will be executed at least once. The repetition finishes when the condition is false. Its format is:

do { ... } while ( condition );

Modify the default constructor in the class DayOfYear, and include a repetition structure that keeps asking to the user a date until he/she enters a valid date. You can use either a while or a do-while. Remember that the do-while executes its body at least once.

7. Pointers and finalization of objects

When we talk about pointers in Java we could say that they don’t exist in this programming language or we could say that everything in Java is a pointer. The reason for this duality is that all the object variables in Java are references to object values stored in other memory locations. This contrasts with C++, where the object variables hold object values, and if we want a variable to hold the address of an object value we have to specify it explicitly with the pointer symbol *****. An object variable being an address to an object in Java, we don’t have to worry about pointers, we are manipulating them implicitly when we work with the object variables. This is the reason why we can say that the pointers don’t exist in Java, because in practical terms they don’t exist for the programmer.

An important issue at this point is how to free all the memory allocated to object variables. Well, this is simpler in Java than in C++. In C++ you need take care of all the objects you create, and destroy them when they are not longer needed (usually through the destructors), in order to free all the system resources they have assigned. In Java you don’t have to worry about this. Java has a garbage collector that is called automatically by the system, and whose task is to free the memory that objects that are no longer needed have. The objects that are candidates for garbage collection are those that the system determines that go out of scope in the program, and those that the programmer explicitly sets to null.

The garbage collector has another useful characteristic. Sometimes as part of the destruction of an object you may wish to free other system resources besides memory such as files, or you want to mark other objects for garbage collection. You can do this through the method finalize that is called automatically. The purpose of this method is to clean up the object before the garbage collector destroys it. The method finalize is inherited by all the objects from the class call Object, which is the parent of all the classes in Java, so you can override it for a specific class. This method must be declared as follows:

protected void finalize() throws Throwable { ... super.finalize(); }

It is recommended to include the last line of the method (super.finalize( ); ), because this cleans up all the resources that the class may have obtained through inheritance. A negative aspect of the garbage collector and the method finalize is that you never know when they are going to be executed, or even worse, you don’t know if they will be executed.