






































































Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!







































































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