Chapter 25. Java

CONTENTS
  •  Introduction
  •  Architecture Independence
  •  The Java Platform
  •  Java vs. C and C++
  •  Java Environment
  •  Comments
  •  No Preprocessor
  •  Constants
  •  No Macros
  •  No Include Files
  •  Data Types
  •  Integral Types
  •  Reference Data Types
  •  Modifiers
  •  No Pointers
  •  Null
  •  No Structure or Unions
  •  No Enumerated Types
  •  No Typedef
  •  Object Creation
  •  Accessing Objects
  •  Garbage Collection
  •  Arrays
  •  Strings
  •  The for Loop
  •  Exception and Exception Handling
  •  Applets

Introduction

Java, the programming language, has gained tremendous popularity since its introduction in late 1995. Java was initially created to build applications for heterogeneous consumer electronic devices. The World Wide Web was experiencing explosive growth and developers craved more than static Web pages. Java developers soon realized that an architecture-independent language such as Java filled this technology gap. Because the Internet ran on a variety of machines, the ability to write a program once with the potential to execute the program on all those machines was extremely advantageous. This fueled the opportunity for widespread adoption of Java.

Java's creators wanted a programming language that would be easy to learn and familiar to most programmers. C and C++ languages were already widely accepted and used. When designing Java, many C and C++ constructs were retained and a number of features found in C and C++ were removed. Most of the features removed either led to poor programming practices or were rarely used. One example is that Java does not use pointers. Many programming errors are as a result of poor pointer implementation; therefore, they were removed.

Architecture Independence

Executables generated from C or C++ programs run only on the computer platform where they were compiled. These executables are not portable. In the highly heterogeneous world of the Internet, this fact presents a problem. In many cases, even the source code for a C or C++ program will not compile on a given computer platform.

Java allows for architecture independence. It is a language that is both compiled and interpreted. The Java compiler generates architecture-neutral bytecodes rather than native machine code. The bytecode is the same regardless of the platform on which it was compiled. This allows for the easy transport of Java programs to multiple platforms.

Java programs can only be run on a computer platform that has the Java Virtual Machine (JVM). This allows Java programs to execute without a re-compile or a change to source code. After Java bytecodes arrive on a computer system, the Java interpreter within the JVM interprets them into native machine code.

Figure 25-1 illustrates the compiled and interpreted nature of Java. The Java source code resides on computer A and is compiled into bytecode. When a request is made for the bytecode via the Internet, a copy is sent over the network. Computer B has made the request and receives a copy of the bytecode. The bytecode is interpreted into the native machine code understood by Computer B, executing the Java program.

Figure 25-1. Compiled and Interpreted Nature of Java

graphics/25fig01.gif

Not all Java programs are written to traverse the network. Many programmers use Java to create portable software. This capability is useful to prevent re-compiles and, in some cases, rewrites, that may be necessary for other languages to run on different computer platforms.

The Java Platform

A platform is typically the hardware and software environment in which a program runs. In contrast, the Java platform is a software-only platform that runs on top of other hardware platforms.

Java consists of two components, the JVM and the Java Application Programming Interface (Java API).

The JVM, which has been previously discussed, is part of what makes a Java program portable. JVMs are not portable; they must be written for a specific computer platform. JVMs interpret the Java bytecode into machine-dependent code for execution. A Java program cannot be run on a computer system unless it has a JVM.

The Java API is a large collection of frequently used software components. The Java APIs are grouped into libraries or packages of related components. The Java APIs enable quick development by providing pre-written components for use by a developer.

Figure 25-2 shows a Java program running on a Java platform. It illustrates how the Java APIs and JVM insulate the program from computer platform dependencies.

Figure 25-2. Java Program on a Java Platform

graphics/25fig02.gif

Java is a platform-independent environment, but there is a cost associated with this. Because Java portability is enabled through a JVM, which must interpret bytecode into machine code, Java can be slower than native code.

Just-in-time compilers, well-tuned interpreters, smarter compilers, and technologies such as HotSpot are bringing Java's performance closer to that of native code without threatening portability.

Dynamic

A separate linking phase, such as can be found in a C or C++ compile process, is basically absent from the Java environment. Linking in Java is actually the process of loading new classes by the Class Loader. This is a more incremental and lightweight process.

The portable and interpreted nature of the Java language produces a highly dynamic and dynamically-extensible system. The Java language was designed to adapt to evolving environments. Java classes are linked when needed and can be downloaded from the network.

The interpreted environment enables fast prototyping or updates to continuously running executables without waiting for the traditional compile and link cycle. An exception is the applet, which is executed by a Web browser. Most Web browsers cache information and changes will only be seen once the browser is restarted.

Java vs. C and C++

Java and C/C++ have many similarities, but there are a number of important differences as well. One of the primary differences between Java and C language is that Java is object-oriented.

Those familiar with C++ will find much of the syntax the same, those familiar with C will notice that the analogies are not as strong. The familiar Java syntax and keywords deceive many C++ programmers. Differences are significant enough to warrant a closer examination of the language.

Java Environment

To begin development in Java, the Java development tools, such as those provided in the Java Developers Kit (JDK), are needed. A JDK can be downloaded from most hardware vendor sites. A JDK will provide the Java compiler, Java APIs, the JVM, and an applet viewer, along with other useful components.

Many think of Java as a language enabling a program to run over the Web, in Web browsers. Although this perception is true, Java is also an application language that can reside on servers with a main() method, similar to C and C++.

When a Java applet is executed within a Web browser, the applet class is used instead of a main() method. It should be noted that a Java applet is not an application but rather a Java class that is loaded and run by an already running Java application such as a Web browser or applet viewer.

If the Java program is to run on a server as an application, the main() method is used. This chapter will discuss the applet class in more depth, because the intent is to discuss Internet programming. Discussions regarding the server applications will be limited to a few paragraphs.

Java source code resides in a file with the .java extension. It contains an optional package statement, followed by any number of import statements, followed by one or more class or interface definition. The package statement specifies of which package the code in the file is part. The import statement makes Java classes available to the current class. If more than one class or interface is defined in a Java source file, only one of the classes can be declared as public (made available outside the package). The source file name must have the same name as the public class or interface, plus the .java extension. For example, a Java source file called games.java will contain only one public class or interface called games.

The Java compiler generates the equivalent of object files containing bytecode in <file>.class files. Each class or interface definition in a Java source file is compiled into a separate file with the.class extension and must have the same name as the class or interface it defines. For example, the class Solitaire would be stored in the file Solitaire.class.

The command-line argument javac is used when compiling followed by the Java source file.

javac [options] files

Check with the vendor of your JDK for the exact argument.

To execute a Java application on a server by invoking the interpreter, the java command-line argument is used, followed by the class name and any arguments.

java [interpreter options] classname [program arguments]

To execute a debugging version of the interpreter, use java_g.

java_g [interpreter options] classname [program arguments]

The main() method is used by the Java interpreter to start a Java program. It must have the following prototype:

public static void main(String args[])

The Java interpreter will continue to run until the main() method reaches the end or the method returns.

The argument to the main() method is an array of strings called args or argv. The length of the array, passed as argc in C, is available as argv.length, as are all Java arrays. When dealing with commandline arguments within the application, note that the first element of the array of arguments is not the name of the class, as a C programmer might expect.

The main() method must be declared to return void. A return value from a Java program cannot use a return statement in the main() method. If a return value is needed, the System.exit() with an integer value is used.

Java cannot read operating-system environment variables because they are platform-dependent. Instead, Java has a system properties list, which allows textual values to be associated with names. Properties can be added to this listed to allow for easy customization of application behavior.

Name Space

Java is designed to support dynamic loading of modules over the entire Internet and must take special care to avoid name space conflicts. Java does not have any global variables, functions, or procedures.

The directory structure under which the class files are stored contains the same components as the package name. For example, if the fully qualified name of a class is

gameworld.games.multi_player.doom.landscapes

the full path of the class file must be

gameworld/games/multi_player/doom/landscapes.class.

The file name is interpreted relative to the Java class path.

The Java class path is an environmental variable set by the developer to tell the Java interpreter where to look for the user-defined classes. The interpreter knows where the standard system classes are installed and will append that location to the end of the path specified in this environmental variable. You can set the class path for the example above:

setenv CLASSPATH .:/home/gameworld/games/multi_player/doom 

Comments

Java supports three comment types: the standard C-style beginning with /* and ending with */, a C++ style starting with // and continuing to the end of the line, and a special doc comment. The doc comment begins with /** and continues to the next */ and may not be nested. The doc comments are specially processed by a javadoc program to produce simple online documentation from the Java source code.

No Preprocessor

Java does not have any preprocessors and does not support #define, #include, and #ifdef.

Constants

A variable declared as final in Java is a constant, and the value may never be changed. The Java equivalent of a C #define constant is a static final variable declared within a class definition.

No Macros

Java does not have an equivalent for the C macro, which saves the overhead of a function call. Many Java compilers and virtual machines "inline" short Java methods where appropriate. This method of inlining does not leave the developer with control of which methods are inlined and which are not.

No Include Files

Java does not have a #include directive, because class names are fully qualified and the Java compiler knows where to find them without the use of a special directive.

Data Types

The primitive types of byte and Boolean were added by Java to the standard set of C types.

Java also strictly defines the size and signedness of its types. In C, a float may be 16, 32, or 64 bits, and a char may behave as signed or unsigned, depending on the platform. In Java, the size and signedness remains consistent across platforms.

In C, an uninitialized variable usually contains garbage as its value. Java assigns default values for all variables. Table 25-1 below shows the data type, the default value, and the size.

Table 25-1. Data Types, Values, and Sizes

Data Type

Default Value

Size

boolean

false

1 bit

char

\u0000

16 bits

byte

0

8 bits

short

0

16 bits

int

0

32 bits

long

0

64 bits

float

0.0

32 bits

double

0.0

64 bits

Integral Types

Java integral types are byte, short char, int, and long. All integral types, other than char, are signed. The keywords unsigned, long and short are no longer valid syntax. A long constant will have the character l or L appended to it.

Reference Data Types

Non-primitive data types in Java are objects and arrays and are often called "reference types". These types are handled by reference, meaning that the address of the object or array is stored in a variable and passed to methods.

In C, value by reference can be manipulated using the & operator and dereferenced using the * and -> operators. These operators do not exist in Java.

Modifiers

Modifiers may be applied to variable and/or method declarations to provide additional information or to place restrictions. Java defines a number of modifier keywords.

The final keyword can be applied to classes, methods and variables. A final class may never be a subclass. A final method may never be overwritten. A final variable may never have its value set.

The native keyword is a modifier that may be applied to method declarations, indicating that the method is implemented elsewhere in C or another platform dependent implementation.

The synchronized keyword prevents concurrent modification of the class, indicating that the class is not thread-safe.

The transient keyword can be applied to instance fields within a class, indicating that the field is not part of an object's persistent state and does not need to be serialized with the object.

The volatile keyword indicates that synchronized threads are using a field, and that the compiler should not attempt to perform optimizations with it. For example, it may indicate that the value of the variable should be read from memory every time and should not have a copy saved on the stack.

No Pointers

Java automatically handles the referencing and dereferencing of objects. Java does not allow the developer to manipulate pointers or memory addresses of any kind. It will not allow casting of objects or array references into integers and vice versa. It will not allow pointer arithmetic. There is no sizeof operator.

Null

Variables of all reference types have the default value of null, which means "no object" or absence of a reference. NULL in C is a constant defined to be 0. Java has made null a reserved keyword.

No Structure or Unions

Struct and union types ae not supported. It is important to note two things: First, a class is essentially the same as a struct with more features, and second, a union can be simulated by using subclassing.

No Enumerated Types

Java does not support the C enum keyword. Enumerated types can be partially simulated with the use of static final constant values.

No Typedef

The typedef keyword, which defines aliases for type names, is not supported in Java, due to Java's simpler type naming scheme.

Object Creation

To create a new object, the new keyword is used, followed by the object's class or type and an optional argument list. These arguments are passed to a constructor method for the class, which initializes internal variables in the new object.

The following is an example of creating a class:

TempBuffer s = new TempBuffer(name); 

Because strings are created so frequently, Java provides the following shortcut for creating a string object:

String s = "346Ocean Blvd"; 

The memory needed for the newly created object is dynamically allocated. Creating an object with new in Java is the equivalent of calling malloc() in C. It is even more similar to using the new operator in C++.

Accessing Objects

You use dot to access fields of an object. The following is an example of assigning a value to a field in an object using a dot:

Circle c = newCircle();  c.radius = 2.0; 

Garbage Collection

Java allows objects to be created and space allocated using new, but there is no corresponding method to free the space. Java uses a technique called garbage collection to automatically detect when objects are no longer in use. Java determines that an object is no longer used when there are no references to it.

Arrays

Just like objects, arrays are manipulated by reference, dynamically created with new, and when they are no longer referred to, they are automatically garbage collected.

You have two ways to create an array. The first method uses new with a specification for the size of the array:

int lottery_numbers[]= new int[6]; 

The elements in an array created with this method are set automatically to the data type default.

The second method creates an array with initializing values, and looks like it does in C:

int lottery_numbers[]= {1, 7, 11, 17, 26, 29}; 

This method initializes the elements of the array to specific values.

Accessing elements in an array is the same as C and C++; an integer-valued expression is placed between square brackets after the name of the array.

Strings

Java strings are not null-terminated arrays of characters as in C, but rather are instances of the String class. String literals are widely used; therefore, Java allows them to appear between quotes just as they do in C.

The String class does not contain a method that allows the contents to be changed. If the contents need to be modified, a String-Buffer object is used.

The for Loop

Most control statements found in C and C++ are identical to those found in Java. The only statement with sufficient difference to warrant a mention is the for loop. There are only two differences between the Java for loop and the C for loop. First, Java does not support the comma operator, which allows multiple expressions to be joined into a single expression. Java allows multiple comma-separated expressions in the initialization and increment sections of the loop syntax, but not in the test section.

The second difference is regarding the C++ capability to declare local loop variables in the initialization section of the loop:

for (int x = 0; x < max_shells; x++)  System.out.println("current number of shells = " + x); 

Although the variable declared has the for loop as its scope, the Java compiler will not allow the declaration of a loop variable that has the same name as an already existing variable or parameter.

Exception and Exception Handling

Exception handling is a new feature in Java, although it is similar to C++ exception handling. An exception is a signal indicating that some exceptional condition such as an error has occurred. To throw an exception is to signal an exceptional condition. An exception is caught when the exception is handled, along with actions necessary to recover from it.

If the block of code that throws the exception does not catch the exception, it will move up to the next higher block of code. If an exception is never caught, it eventually moves to the main() method and causes the Java interpreter to print an error message and a stack trace, and exit.

An exception in Java is an object that has two standard subclasses representing Error and Exception. Any exceptions that are of subclasses Error generally indicate unrecoverable errors and should not be caught. Exceptions that are of subclasses Exception indicate conditions that may be caught and recovered from, such as end of file, or array out of bounds.

The try/catch/finally statement is Java's exception-handling mechanism. try establishes a block of code that will have exceptions and abnormal exits handled. The try block is followed by zero ormore catch clauses. The catch clause is optionally followed by a finally block that contains "clean-up" code.

The try/catch/finally statement appears as follows:

try {     // Block of code that will normally run without any      // problems, but may run into exceptions.  }  catch (AnException e) {     // Handles the exception object, catching it  }  finally {     // This code will always execute after leaving the try      // clause, regardless of how we leave it.      // This section will be executed whether the run was      // normal, an exception was caught, an exception was not      // caught, or the code was broken out of with a break,      // continue, or return statement.  } 

Various pieces of code can anticipate that exceptions will be thrown at some point. For example, if a program requires a user to enter an integer, there is a strong possibility that something other than an integer may be entered. The following fragment of code requires that an integer be passed into the main() method via arguments on the command line.

try { i = Integer.parseInt(argv[0]); }  catch (NumberFormatException e) {     System.out.println("Argument must be an integer.");      return;  } 

Applets

Applets are a kind of small application designed to be run by a Web browser or an applet viewer. They differ from regular applications in two ways. First, there are a number of security restrictions governing applets and what they can do. An applet may consist of untrusted code, so it must not be allowed to access the local file system, for example.

Programmers will notice another difference between applets and applications: Applets do not have a main() method. An applet is a subclass that is loaded into a piece of software already running Java, such as a Web browser or applet viewer.

How does it work? First, a Java class is created using the applet class. An HTML file is created and an HTML tag is used to reference the applet and request it from the local machine or a machine on the Internet. It is then loaded into the browser or applet viewer and executed. The process becomes clearer after you create your first applet.

Creating a First Applet

The first step is to create a Java source file. Create a file named HelloWorld.java with the Java code below:

import java.applet.Applet;  import java.awt.Graphics;  public class HelloWorld extends Applet {     public void paint (Graphics g) {         g.drawString("Hello World!!", 50, 25);  }  } 

Next, compile the source file using the Java compiler. If the compile is successful, a file called HelloWorld.class is created in the same directory.

An HTML file needs to be created to invoke the applet. Create a file called HelloWorld.html in the same directory as the HelloWorld.class file. Insert the following text:

<HTML>  <BODY>  <APPLET code="HelloWorld.class" WIDTH= 150 HEIGHT=50>  </APPLET>  </BODY>  </HTML> 

To run the applet, the HTML file needs to be loaded into a program that can run Java applets. Examples are a Java-enabled browser and the applet viewer provided with the JDK. To load the file, the URL of the HTML file must be entered. An example is listed below:

file:/home/kit/applet/HTML/HelloWorld.html 

The command when using an applet viewer may appear as follows:

appletviewer file:/home/kit/applet/HTML/HelloWorld.html 

Importing Classes and Packages

The first two lines of the applet import java.applet.Applet and java.awt.Graphics. If these lines were not included, the following changes would need to be made to the applet source code:

Public class HelloWorld extends java.applet.Applet {     Public void paint(java.awt.Graphics g) {         g.drawString("Hello World!!", 50, 25);      }  } 

Importing the classes allows the program to refer to them without any prefixes.

Defining Applet Subclass

In the Applet source code, the keyword extends indicates that HelloWorld is a subclass of the class following it, in this case Applet. Applets inherit functionality from the Applet class; one of the more important is the ability to respond to browser requests.

An Applet isn't restricted to defining one class; it can define custom classes.

Applets as Graphical User Interfaces

The very nature of applets encourages the use of User Interface (UI) components. The AWT and Swing libraries contain pre-made graphical components. AWT libraries were some of the first graphical components. The Swing libraries followed, providing the capability of customizing the graphical look and feel of a component. For example, Swing libraries enable a Windows look and feel for the graphical components regardless of the platform.

Some of the basic components are buttons, check boxes, singleline text fields, editing areas, field labels, lists, pop-up lists, sliders and scrollbars, and menus.

A layout manager will help the developer arrange the components and produce a well-designed applet.

Java has many API's and libraries with pre-written components. Anyone interested in learning more should also investigate these libraries. They are described in most books with a sizeable Java section.

CONTENTS


UNIX User's Handbook
UNIX Users Handbook (2nd Edition)
ISBN: 0130654191
EAN: 2147483647
Year: 2001
Pages: 34

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net