4.3.1 Primitive Types Numbers, characters, and boolean values are fundamental elements in Java. Unlike some other (perhaps more pure) object-oriented languages, they are not objects. For those situations where it’s desirable to treat a primitive value as an object, Java provides ” wrapper” classes (see Chapter 9). One major advantage of treating primitive values as such is that the Java compiler can more readily optimize their usage. Another important portability feature of Java is that primitive types are precisely defined. For example, you never have to worry about the size of an int on a particular platform; it’s always a 32bit, signed, two’s complement number. Table 4.2 summarizes Java’s primitive types. Table 4.2, Java Primitive Data Types Type Definition Boolean trueor false Char 16-bit Unicode character Byte 8-bit signed two’s complement integer Short 16-bit signed two’s complement integer Int 32-bit signed two’s complement integer Long 64-bit signed two’s complement integer Float 32-bit IEEE 754 floating-point value Double 64-bit IEEE 754 floating-point value If you think the primitive types look like an idealization of C scalar types on a 32-bit machine, you’re absolutely right. That’s how they’re supposed to look. The 16-bit characters were forced by Unicode, and ad hoc pointers were deleted for other reasons. But overall, the syntax and semantics of Java primitive types are meant to fit a C programmer’s mental habits. 4.3.1.1 Floating-point precision Floating-point operations in Java are standardized to follow the IEEE 754 international specification, which means that the result of floating-point calculations will generally be the same on different Java platforms. More recent versions of Java have been enhanced to allow for extended precision on platforms that support it. This can introduce extremely small-valued and arcane differences in the results of high-precision operations. Most applications would never notice this, but if you want to ensure that your application will produce exactly the same results on different platforms, use the special keyword strictfp as a class modifier on the class containing the floating-point manipulation. 4.3.1.2 Variable declaration and initialization Variables are declared inside of methods or classes in C style. For example: int foo; double d1, d2; boolean isFun; Variables can optionally be initialized with an appropriate expression when they are declared: int foo = 42; double d1 = 3.14, d2 = 2 * 3.14; boolean isFun = true; - 68
Note: If you are looking for good and high quality web space to host and run your application check Lunarwebhost Tomcat Web Hosting services
* @see PotatoPeeler * @see PotatoMasher * @author John ‘Spuds’ Smith * @version 1.00, 19 Dec 1996 */ javadoc creates HTML format documentation of classes by reading the source code and the embedded comments. The author and version information is presented in the output, and the @see tags make hypertext links to the appropriate class documentation. The compiler also looks at the doc comments; in particular, it is interested in the @deprecated tag, which means that the method has been declared obsolete and should be avoided in new programs. The compiler generates a warning message whenever it sees the usage of a deprecated feature in your code. Doc comments can appear above class, method, and variable definitions, but some tags may not be applicable to all of these. For example, a variable declaration can contain only a @see tag. Table 4.1 summarizes the tags used in doc comments. Table 4.1, Doc Comment Tags Tag Description Applies to @see Associated class name Class, method, or variable @author Author name Class @version Version string Class @param Parameter name and description Method @return Description of return value Method @exception Exception name and description Method @deprecated Declares an item to be obsolete Class, method, or variable 4.3 Types The type system of a programming language describes how its data elements ( variables and constants) are associated with actual storage. In a statically typed language, like C or C++, the type of a data element is a simple, unchanging attribute that often corresponds directly to some underlying hardware phenomenon, like a register value or a pointer indirection. In a more dynamic language like Smalltalk or Lisp, variables can be assigned arbitrary elements and can effectively change their type throughout their lifetime. A considerable amount of overhead goes into validating what happens in these languages at runtime. Scripting languages like Perl and Tcl achieve ease of use by providing drastically simplified type systems in which only certain data elements can be stored in variables, and values are unified into a common representation, such as strings. Java combines the best features of both statically and dynamically typed languages. As in a statically typed language, every variable and programming element in Java has a type that is known at compile time, so the runtime system doesn’t normally have to check the type validity of assignments while the code is executing. Unlike C or C++, though, Java also maintains runtime information about objects and uses this to allow truly safe runtime polymorphism and casting (using an object as a type other than its declared type). Java data types fall into two categories. Primitive types represent simple values that have built-in functionality in the language; they are fixed elements, such as literal constants and numbers. Reference types (or class types) include objects and arrays; they are called reference types because they are passed “by reference,” as we’ll explain shortly. - 67
Note: If you are looking for good and high quality web space to host and run your application check Lunarwebhost Java Web Hosting services
The Java char type and String objects also support Unicode. But if you’re concerned about having to labor with two-byte characters, you can relax. The String API makes the character encoding transparent to you. Unicode is also ASCII-friendly; the first 256 characters are defined to be identical to the first 256 characters in the ISO8859-1 (Latin-1) encoding; if you stick with these values, there’s really no distinction between the two. Most platforms can’t display all currently defined Unicode characters. As a result, Java programs can be written with special Unicode escape sequences. A Unicode character can be represented with this escape sequence: uxxxx xxxx is a sequence of one to four hexadecimal digits. The escape sequence indicates an ASCII- encoded Unicode character. This is also the form Java uses to output a Unicode character in an environment that doesn’t otherwise support them. Java stores and manipulates characters and strings internally as Unicode values. Java also comes with classes to read and write Unicode-formatted character streams. 4.2 Comments Java supports both C-style block comments delimited by /* and */ and C++ - style line comments indicated by //: /* This is a multiline comment. */ // This is a single-line comment// and so // is this As in C, block comments can’t be nested. Single- line comments are delimited by the end of a line; extra // indicators inside a single line have no effect. Line comments are useful for short comments within methods; they don’t conflict with wrapping block comment indicators around large chunks of code during development. 4.2.1 Javadoc Comments By convention, a block comment beginning with /** indicates a special doc comment . A doc comment is designed to be extracted by automated documentation generators, such as the DSK’s javadoc program. A doc comment is terminated by the next */, just as with a regular block comment. Leading spacing up to a * on each line is ignored; lines beginning with @ are interpreted as special tags for the documentation generator. Here’s an example: /** * I think this class is possibly the most amazing thing you will * ever see. Let me tell you about my own personal vision and * motivation in creating it. *
* It all began when I was a small child, growing up on the * streets of Idaho. Potatoes were the rage, and life was good… * - 66
Note: If you are looking for good and high quality web space to host and run your application check Lunarwebhost Tomcat Web Hosting services
Aside from information for your own use, there are special values (in SDK 1.2) you can put in the manifest file that are useful. One of these, Main-Class , allows you to specify a class that contains a main( ) method: Main-Class: Game If you incorporate this specification in your JAR file manifest (using the m option described earlier), you can actually run the JAR from the command line: % java -jar spaceblaster.jar The interpreter looks for the Main-Class value in the manifest. Then it loads the named class as the application’s initial class. What can we do with the revision and temperament information we’ve so cleverly included in the JAR file? Unfortunately, nothing, except for unpacking the archive and reading the manifest. However, if you were writing your own JAR utility or some kind of resource loader, you could include code to look at the manifest, check for your private keywords, and act accordingly perhaps darkening the display if the artist’s temperament is moody. Another important keyword is Java-Bean . The value of this keyword should be true if the item is a Java Bean; this information is used by the BeanBox and other utilities that work with Beans (see Chapter 19). Chapter 4. The Java Language In this chapter, we’ll introduce the framework of the Java language and some of its fundamental facilities. We’re not going to try to provide a full language reference here. Instead, we’ll lay out the basic structures of Java with special attention to how it differs from other languages. For example, we’ll take a close look at arrays in Java, because they are significantly different from those in some other languages. We won’t, on the other hand, spend much time explaining basic language constructs like loops and control structures. Nor will we talk much about Java’s object-oriented side here, as that’s covered in detail in Chapter 5 through Chapter 7. As always, we’ll try to provide meaningful examples to illustrate how to use Java in everyday programming tasks. 4.1 Text Encoding Java is a language for the Internet. Since the people of the Net speak and write in many different human languages, Java must be able to handle a large number of languages as well. One of the ways in which Java supports international access is through Unicode character encoding. Unicode uses a 16-bit character encoding; it’s a worldwide standard that supports the scripts (character sets) of most languages.[1] [1] For more information about Unicode, see http://www.unicode.org. Ironically, one of the scripts listed as “obsolete and archaic” and not currently supported by the Unicode standard is Javanese a historical language of the people of the Island of Java. Java source code can be written using the Unicode character encoding and stored either in its full 16-bit form or with ASCII-encoded Unicode character values. This makes Java a friendly language for non-English-speaking programmers who can use their native alphabet for class, method, and variable names in Java code. - 65
Note: If you are looking for good and high quality web space to host and run your application check Lunarwebhost Tomcat Web Hosting services
Manifest-Version: 1.0 Created-By: 1.2.1 (Sun Microsystems Inc.) Basically the file just describes its version number. In SDK 1.1, the manifest contains entries describing each item in the archive. In our case, the beginning of our manifest file looks like this (in SDK 1.1 only): Manifest-Version: 1.0 Name: spaceblaster/game/Game.class Digest-Algorithms: SHA MD5 SHA-Digest: D5Vi4UV+O+XprdFYaUt0bCv2GDo= MD5-Digest: 9/W62mC4th6G/x8tTnP2Ng== Name: spaceblaster/game/Planetoid.class Digest-Algorithms: SHA MD5 SHA-Digest: SuSUd6pYAASO5JiIGlBrWYzLGVk= MD5-Digest: KN/4cLDxAxDk/INKHi2emA== … The first line is the same version number as before. Following it are groups of lines describing each item. The first line tells you the item’s name; in this case, the lines describing the files Game.class and Planetoid.class. The remaining lines in each section describe various attributes of the item. In this case, the Digest-Algorithms line specifies that the manifest provides message digests (similar to checksums) in two forms: SHA and MD5.[2] This is followed by the actual message digest for the item, computed using these two algorithms. [2] SHA and MD5 stand for Secure Hashing Algorithm and Message Digest 5. That’s all you really need to know about them; an explanation of these algorithms is beyond the scope of this book. As we’ll discuss in the next section, the META-INF directory and manifest file can also hold digital signature information for items in the archive. Since the message digest information is really necessary only for signed JAR files, it is omitted when you create an archive in SDK 1.2 and later. You can add your own information to the manifest descriptions by specifying a supplementary manifest file when you create the archive. This is a good place to store other simple kinds of attribute information about the files in the archive, perhaps version or authorship information. For example, we can create a file with the following keyword: value lines: Name: spaceblaster/images/planetoid.gifRevisionNumber: 42.7 Artist-Temperment: moody To add this information to the manifest in our archive, place it in a file called myManifest.mf and give the following jar command: % jar -cvmf myManifest.mf spaceblaster.jar spaceblaster We’ve added an additional option to the command, m, which specifies that jar should read additional manifest information from the file given on the command line. How does jar know which file is which? Because m is before f, it expects to find the manifest information before the name of the JAR file it will create. If you think that’s awkward, you’re right; get the names in the wrong order, and jar will do the wrong thing. Be careful. - 64
Note: If you are looking for good and high quality web space to host and run your application check Lunarwebhost Tomcat Web Hosting services
Because we requested verbose output, jar tells us what it is doing: adding:spaceblaster/ (in=0) (out=0) (stored 0%) adding:spaceblaster/game/ (in=0) (out=0) (stored 0%) adding:spaceblaster/game/Game.class (in=8035) (out=3936) (deflated 51%) adding:spaceblaster/game/Planetoid.class (in=6254) (out=3288) (deflated 47%) adding:spaceblaster/game/SpaceShip.class (in=2295) (out=1280) (deflated 44%) adding:spaceblaster/images/ (in=0) (out=0) (stored 0%) adding:spaceblaster/images/spaceship.gif (in=6174) (out=5936) (deflated 3%) adding:spaceblaster/images/planetoid.gif (in=23444) (out=23454) (deflated 0%) adding:spaceblaster/docs/ (in=0) (out=0) (stored 0%) adding:spaceblaster/docs/help1.html (in=3592) (out=1545) (deflated 56%) adding:spaceblaster/docs/help2.html (in=3148) (out=1535) (deflated 51%) jar creates the file spaceblaster.jar and adds the directory spaceblaster, in turn adding the directories and files within spaceblaster to the archive. In verbose mode, jar reports the savings gained by compressing the files in the archive. We can unpack the archive with this command: % jar xvf spaceblaster.jar Likewise, we can extract an individual file or directory with: % jar xvf spaceblaster.jar filename But you normally don’t have to unpack a JAR file to use its contents; Java tools know how to extract files from archives automatically. We can list the contents of our JAR with the command: % jar tvf spaceblaster.jar Here’s the output; it lists all the files, their sizes, and creation times: 0 Thu May 15 12:18:54 PDT 1997 META-INF/ 1074 Thu May 15 12:18:54 PDT 1997 META-INF/MANIFEST.MF 0 Thu May 15 12:09:24 PDT 1997 spaceblaster/ 0 Thu May 15 11:59:32 PDT 1997 spaceblaster/game/ 8035 Thu May 15 12:14:08 PDT 1997 spaceblaster/game/Game.class 6254 Thu May 15 12:15:18 PDT 1997 spaceblaster/game/Planetoid.class 2295 Thu May 15 12:15:26 PDT 1997 spaceblaster/game/SpaceShip.class 0 Thu May 15 12:17:00 PDT 1997 spaceblaster/images/ 6174 Thu May 15 12:16:54 PDT 1997 spaceblaster/images/spaceship.gif 23444 Thu May 15 12:16:58 PDT 1997 spaceblaster/images/planetoid.gif 0 Thu May 15 12:10:02 PDT 1997 spaceblaster/docs/ 3592 Thu May 15 12:10:16 PDT 1997 spaceblaster/docs/help1.html 3148 Thu May 15 12:10:02 PDT 1997 spaceblaster/docs/help2.html 3.5.2.1 JAR manifests Note that jar adds a directory called META-INF to our archive. It contains one file: MANIFEST.MF. The META-INF directory holds files describing the contents of the JAR file. The MANIFEST.MF file that jar adds is an automatically generated packing list naming the files in the archive along with cryptographic checksums for each. The manifest is a text file containing a set of lines in the form keyword: value. The format of the manifest file changed between SDK 1.1 and SDK 1.2. In SDK 1.2 and later, the manifest file is very simple, containing no information on the items in the archive: - 63
Note: If you are looking for good and high quality web space to host and run your application check Lunarwebhost Tomcat Web Hosting services
Compression makes downloading classes over a network much faster. A quick survey of the SDK distribution shows that a typical class file shrinks by about 40 percent when it is compressed. Text files such as arbitrary HTML or ASCII containing English words often compress by as much as 75 percent to one-quarter of their original size. (On the other hand, image files don’t get smaller when compressed; both of the common image formats have compression built in.) Compression is not the only advantage that a JAR file has for transporting files over a network. For an application with many components, the amount of time it takes to transport all of the parts may be less significant than the time involved in setting up the connections and making the requests for them. This is especially important for applets loaded via the Web. The typical web browser has to make a separate HTTP request for each class or data file. An applet comprising 100 classes, for example, would require at least 100 separate trips to the web server to gather all its parts. Placing all the classes in a single JAR file enables them to be downloaded in a single transaction. Eliminating the overhead of making HTTP requests is likely to be a big savings, since individual class files tend to be small, and a complex applet could easily require many of them. 3.5.2 The jar Utility The jar utility provided with the SDK is a simple tool for creating and reading JAR files. Its user interface isn’t friendly; it mimics the Unix tar (tape archive) command. If you’re familiar with tar, you’ll recognize the following incantations: jar -cvf jarFile path [ path ] [ .. . ] Create jarFile containing path(s) jar -tvf jarFile [ path ] [ … ] List the contents of jarFile, optionally showing just path(s) jar -xvf jarFile [ path ] [ … ] Extract the contents of jarFile, optionally extracting just path(s) In these commands, the letters c, t, and x tell jar whether it is creating an archive, listing an archive’s contents, or extracting files from an archive. The f means that the next argument will be the name of the JAR file on which to operate. The v tells jar to be more verbose when displaying information about files. In verbose mode you can get information about file sizes, modification times, and compression ratios. Subsequent items on the command line (i.e., anything aside from the letters telling jar what to do and the file on which jar should operate) are taken as names of archive items. If you’re creating an archive, the files and directories you list are placed in it. If you’re extracting, only the filenames you list are extracted from the archive. (If you don’t list any files, jar extracts everything in the archive.) For example, let’s say we have just completed our new game: “spaceblaster.” All the files associated with the game are in three directories. The Java classes themselves are in the spaceblaster/game directory; spaceblaster/images contains the game’s images; and spaceblaster/docs contains associated game data. We can pack all of this in an archive with this command: % jar cvf spaceblaster.jar spaceblaster - 62
Note: If you are looking for good and high quality web space to host and run your application check Lunarwebhost Tomcat Web Hosting services
If you don’t specify the CLASSPATH environment variable, it defaults to the current directory (.); this means that the files in your current directory are always available. If you change the class path and don’t include the current directory, these files will no longer be accessible. 3.4 The Java Compiler In this section, we’ll say a few words about javac, the Java compiler that is supplied as part of Sun’s SDK. (If you are happily working in another development environment, you may want to skip ahead to the next section.) The javac compiler is written entirely in Java, so it’s available for any platform that supports the Java runtime system. The ability to support its own development environments is an important stage in a language’s development. Java makes this bootstrapping automatic by supplying a ready-to-run compiler at the same cost as porting the interpreter. javac turns Java source code into a compiled class that contains Java virtual machine byte-code. By convention, source files are named with a .java extension; the resulting class files have a .class extension. Each source code file is a single compilation unit. As you’ll see in Chapter 6, classes in a given compilation unit share certain features, such as package and import statements. javac allows you one public class per file and insists the file have the same name as the class. If the filename and class name don’t match, javac issues a compilation error. A single file can contain multiple classes, as long as only one of the classes is public. Avoid packing many classes into a single source file. Including non-public classes in a .java file is one easy way to tightly couple such classes to a public class. But you might also consider using inner classes (see Chapter 6). Now for an example. Place the following source code in file BigBird.java: package animals.birds; public class BigBird extends Bird { … } Then compile it with: % javac BigBird.java Unlike the Java interpreter, which takes just a class name as its argument, javac needs a filename to process. The previous command produces the class file BigBird.class in the same directory as the source file. While it’s useful to have the class file in the same directory as the source for testing a simple example, for most real applications you’ll need to store the class file in an appropriate place in the class path. You can use the -d option to javac to specify an alternative directory for storing the class files it generates. The specified directory is used as the root of the class hierarchy, so .class files are placed in this directory or in a subdirectory below it, depending on whether the class is contained in a package. (The compiler creates intermediate subdirectories automatically, if necessary.) For example, we can use the following command to create the BigBird.class file at /home/vicky/Java/classes/animals/birds/BigBird.class: % javac -d /home/vicky/Java/classes BigBird.java You can specify multiple .java files in a single javac command; the compiler creates a class file for each source file. But you don’t need to list source files for other classes that your class references, as - 60
Note: If you are looking for good and high quality web space to host and run your application check Lunarwebhost Tomcat Web Hosting services
.3 The Class Path The concept of a path should be familiar to anyone who has worked on a DOS or Unix platform. It’s an environment variable that provides an application with a list of places to look for some resource. The most common example is a path for executable programs. In a Unix shell, the PATH environment variable is a colon-separated list of directories that are searched, in order, when the user types the name of a command. The Java CLASSPATH environment variable, similarly, is a list of locations that can be searched for packages containing Java class files. Both the Java interpreter and the Java compiler use CLASSPATH when searching for packages and classes on the local host. A location on the class path can be a directory name or the name of a class archive file. Java supports archives of class files in its own Java archive ( JAR) format, and in the conventional ZIP format. JAR and ZIP are really the same format, but JAR archives include extra files that describe each archive’s contents. JAR files are created with the SDK’s jar utility; many tools for creating ZIP archives are publicly available. The archive format enables large groups of classes to be distributed in a single file; the Java interpreter automatically extracts individual class files from an archive, as needed. The precise means and format for setting the class path vary from system to system. On a Unix system, you set the CLASSPATH environment variable with a colon-separated list of directories and class archive files: CLASSPATH=/home/vicky/Java/classes:/home/josh/oldstuff/foo.zip:. On a Windows system, the CLASSPATH environment variable is set with a semicolon-separated list of directories and class archive files: set CLASSPATH=D:usersvickyJavaclasses;. The first example above, for Unix, specifies a class path with three locations: a directory in the user’s home, a ZIP file in another user’s directory, and the current directory, which is always specified with a dot (.). The last component of the class path, the current directory, is useful when tinkering with classes, but as a general rule, it’s bad practice to put the current directory in any kind of path. The Java interpreter and the other command-line tools also know how to find core classes, which are the classes included in every Java installation. The classes in the java.lang, java.io, java.net, and javax.swing packages, for example, are all core classes. You don’t need to include these classes in your class path; the Java interpreter and the other tools can find them by themselves. To find other classes, the Java interpreter searches the locations on the class path in order. The search combines the path location and the fully qualified class name. For example, consider a search for the class animals.birds.BigBird. Searching the class path directory /usr/lib/java means the interpreter looks for an individual class file at /usr/lib/java/animals/birds/BigBird.class. Searching a ZIP or JAR archive on the class path, say /home/vicky/Java/utils/classutils.jar, means that the interpreter looks for component file animals/birds/BigBird.class in the archive. For the Java interpreter, java, and the Java compiler, javac, the class path can also be specified with the -classpath option: % javac -classpath /pkg/sdk/lib/classes.zip:/home/pat/java:. Foo.java - 59
Note: If you are looking for good and high quality web space to host and run your application check Lunarwebhost Tomcat Web Hosting services
Choose SocketPermission from the first combo box. Then fill out the second text field on the right side with the network address that EvilEmpire will connect to. Finally, choose connect from the third combo box. Click on OK; you should see the new permission in the policy entry window, as shown in Figure 3.3. Click on Done to finish creating the policy. Then choose Save As from the File menu and save the policy file as something memorable, like EvilEmpire.policy. You can quit policytool now; we’re all done with it. There’s nothing magical about the policy file you just created. Take a look at it with a text editor. It has a simple syntax; here’s the important part, showing the policy we just created: grant codeBase “file:/c:/Projects/Exploring/” { permission java.net.SocketPermission “207.46.131.13″, “connect”; }; You can eschew policytool entirely and just create policy files with a text editor, if you’re more comfortable that way. 3.2.3 Using a Policy File with the Default Security Manager Now that we’ve gone to the trouble of creating a policy file, let’s use it. You can tell the default security manager to use the policy file with another command-line option to the java interpreter: C:> java -Djava.security.manager -Djava.security.policy=EvilEmpire.policyEvilEmpire Connected! EvilEmpire can now make its socket connection because we have explicitly granted it permission with a policy file. The default security manager still protects us in other ways, however; EvilEmpire cannot write or read files on the disk except in the directory it came from; it cannot make connections to any other network addresses except the one we specified. Take a moment and bask in this warm fuzzy feeling. Later, in Chapter 20, you’ll see policytool again when we explain signed applets. In this chapter, codebases are identified by URLs, which isn’t the most secure option. Through tricky network shenanigans, a clever forger may be able to give you code that appears to be from somewhere it’s not. Crytpographically signed code is even more trustworthy; see Chapter 20 for the full details. - 58
Note: If you are looking for good and high quality web space to host and run your application check Lunarwebhost JSP Web Hosting services