Showing posts with label jdk. Show all posts
Showing posts with label jdk. Show all posts

Wednesday, July 24, 2013

Explicit Casting

It may well be that the default treatment of mixed expressions listed in the preceding section is not what you want. For example, suppose you have defined a double variable result; and two variables, three and two, of type int with the values 3 and 2, respectively. If you compute the value of result with the statement

result = 1.5 + three/two;

the value stored will be 2.5, since three/two will be executed as an integer operation and will produce the result 1. You may have wanted the term three/two to produce the value 1.5 in Java program so the overall result would be 3.0. You could do this using an explicit cast:

result = 1.5 + (double)three/two;

This causes the value stored in three to be converted to type double before the divide operation takes place. Then rule 1 applies for the divide operation, and the operand two is also converted to type double before the divide operation is executed.

Sunday, January 8, 2012

Java’s Class Library

A library in Java is a collection of classes - usually providing related facilities - that you can use in your programs. The Java class library provides you with a whole range of goodies, some of which are essential for your programs to work at all, and some of which make writing your Java programs easier. To say that the standard class library covers a lot of ground would be something of an understatement, so I won’t be going into it in detail here; however, you will be looking into how to apply many of the facilities it provides throughout the book of Java.

Since the class library is a set of classes, it is stored in sets of files where each file contains a class definition. The classes are grouped together into related sets that are called packages, and each package is stored in a separate directory. A class in a package can access any of the other classes in the package. A class in another package may or may not be accessible.

The package name is based on the path to the directory in which the classes belonging to the package are stored. Classes in the package java.lang for example are stored in the directory path java\lang (or java/lang under Unix). This path is relative to a particular directory that is automatically known by the Java run-time environment that executes your code. You can also create your own packages that will contain classes of your own that you want to reuse in different contexts, and that are related in some way.

The JDK includes a growing number of standard packages - well over 100 the last time I counted. Some of the packages you will meet most frequently are:

[1] java.lang :-
These classes support the basic language features and the handling of arrays and strings. Classes in this package are always available directly in your programs by default because this package is always automatically loaded with your program.

[2] java.io :-
Classes for data input and output operations.

[3] java.util :-
This package contains utility classes of various kinds, including classes for managing data within collections or groups of data items.

[4] javax.swing :-
These classes provide easy-to-use and flexible components for building graphical user interfaces (GUIs). The components in this package are referred to as Swing components.

[5] java.awt :-
Classes in this package provide the original GUI components (JDK 1.1) as well as some basic support necessary for Swing components. java.awt.geom These classes define two-dimensional geometric shapes.

[6] java.awt.event :-
The classes in this package are used in the implementation of windowed applications to handle events in your program. Events are things like moving the mouse, pressing the left mouse button, or clicking on a menu item.

As noted previously, you can use any of the classes from the java.lang package in your programs by default. To use classes from the other packages, you typically use import statements to identify the names of the classes that you need from each package. This allows you to reference the classes by the simple class name. Without an import statement you would need to specify the fully qualified name of each class from a package each time you refer to it. As we will see in a moment, the fully qualified name for a class includes the package name as well as the basic class name. Using fully qualified class names would make your program code rather cumbersome, and certainly less readable. It would also make them a lot more tedious to type in.

You can use an import statement to import the name of a single class from a package into your program, or all the class names. The two import statements at the beginning of the code for the applet you saw earlier in this post are examples of importing a single class name. The first was:

import javax.swing.JApplet;

This statement imports the JApplet class name that is defined in the javax.swing package. Formally, the name of the JApplet class is not really JApplet - it is the fully qualified name javax.swing.JApplet. You can use the unqualified name only when you import the class or the complete package containing it into your program. You can still reference a class from a package even if you don’t import it though - you just need to use the full class name, javax.swing.JApplet. You could try this out with the applet you saw earlier if you like. Just delete the two import statements from the file and use the full class names in the program. Then recompile it. It should work the same as before. Thus, the fully qualified name for a class is the name of the package in which it is defined, followed by a period, followed by the name given to the class in its definition. You could import the names of all the classes in the javax.swing package with the statement:

import javax.swing.*;

The asterisk specifies that all the class names are to be imported. Importing just the class names that your source code uses makes compilation more efficient, but when you are using a lot of classes from a package you may find it more convenient to import all the names. This saves typing reams of import statements for one thing. We will do this with examples of Java code in the book to keep the number of lines to a minimum. However, there are risks associated with importing all the names in a package. There may be classes with names that are identical to names you have given to your own classes, which would obviously create some confusion when you compile your code.

As I indicated earlier, the standard classes do not appear as files or directories on your hard disk. They are packaged up in a single compressed file, rt.jar, that is stored in the jre/lib directory. This directory is created when you install the JDK on your computer. A .jar file is a Java archive - a compressed archive of Java classes. The standard classes that your executable program requires are loaded automatically from rt.jar, so you don’t have to be concerned with it directly at all.

Java Program Structure

Let’s summarize how a Java program is structured:

[1] A Java program always consists of one or more classes.

[2] You typically put the program code for each class in a separate file, and you must give each file the same name as that of the class that is defined within it.

[3] A Java source file name must have the extension .java. Thus your file containing the class Hat will be called Hat.java and your file containing the class BaseballPlayer must have the file name BaseballPlayer.java.

This program clearly majors on apparel, with four of the five classes representing clothing. Each source file contains a class definition, and all of the files that go to make up the program are stored in the same directory. The source files for your program contain all the code that you wrote, but this is not everything that is ultimately included in the program. There is also code from the Java standard class library, so let’s take a peek at what that can do.

Classes and Data Types

Programming is concerned with specifying how data of various kinds is to be processed, massaged, manipulated, or transformed. Since classes define the types of objects that a program will work with, you can consider defining a class to be the same as defining a data type. Thus, Hat is a type of data, as is Tree, and any other class you care to define. Java also contains a library of standard classes that provide you with a whole range of programming tools and facilities. For the most part then, your Java program will process, massage, manipulate, or transform class objects.

There are some basic types of data in Java that are not classes, and these are called primitive types. I will go into these in detail in the next chapter, but they are essentially data types for numeric values such as 99 or 3.75, for single characters such as A or ?, and for logical values that can be true or false. Java also has classes that correspond to each of the primitive data types for reasons that you will see later on, so there is an Integer class that defines objects that encapsulate integers, for example. Every entity in your Java program that is not of a primitive data type will be an object of a class - either a class that you define yourself, a class supplied as part of the Java environment, or a class that you obtain from somewhere else, such as from a specialized support package.

Encapsulation

At this point we can introduce another bit of jargon you can use to impress or bore your friends - encapsulation. Encapsulation refers to the hiding of items of data and methods within an object. This is achieved by specifying them as private in the definition of the class. In the CowboyHat class, the instance variables owner, type, size, and hatOn were encapsulated. They were accessible only through the methods defined for the class. Therefore, the only way to alter the values they contain is to call a method that does that. Being able to encapsulate members of a class in this way is important for the security and integrity of class objects. You may have a class with data members that can take on only particular values. By hiding the data members and forcing the use of a method to set or change the values, you can ensure that only legal values are set.

I mentioned earlier another major advantage of encapsulation - the ability to hide the implementation of a class. By allowing only limited access to the members of a class, you have the freedom to change the internals of the class without necessitating changes to Java programs that use the class. As long as the external characteristics of the methods that can be called from outside the class remain unchanged, the internal code can be changed in any way that you, the programmer, want.

A particular object, an instance of CowboyHat, incorporates, or encapsulates, the owner, the size of the object, and the status of the hat in the instance variable hatOn. Only the constructor, and the putHatOn(), takeHatOff(), changeOwner(), and getSize() methods can be accessed externally.

Java Program Statements

As you saw in the CowboyHat class example, the code for each method in the class appears between braces, and it consists of program statements. A semicolon terminates each program statement. A statement in Java can spread over several lines if necessary, since the end of each statement is determined by the semicolon, not by the end of a line. Here is a Java program statement:

hatOn = false;

If you wanted to, you could also write this as:

hatOn = false;

You can generally include spaces and tabs, and spread your statements over multiple lines to enhance readability if it is a particularly long statement, but sensible constraints apply. You can’t put a space in the middle of a name for instance. If you write hat On, for example, the compiler will read this as two words.

Operating on Objects

A class object is not just a collection of various items of data. In addition to the parameters that characterize an object, a class specifies what you can do with an object of the class - that is, it defines the operations that are possible on objects of the class. Clearly, for objects to be of any use in a program, you need to decide what you can do with them. The operations that you specify for objects of a given type will depend on what sort of objects you are talking about, the attributes they contain, and how you intend to use them.

For the CowboyHat class, you may want to have operations that you could refer to as putHatOn and takeHatOff, which would have meanings that are fairly obvious from their names, and do make sense for CowboyHat objects. These operations on a particular CowboyHat object would set the value of hatOn for the object. To determine whether your CowboyHat was on or off, you would just need to look at this value. Conceivably, you might also have an operation changeOwner by which you could set the instance variable recording the current owner’s name to a new value.

Of course, for each type of object you can have any operation that makes sense for you. If you want to have a shootHoleIn operation for Hat objects, that’s no problem. You just have to define what that operation does to an object. You are probably wondering at this point how an operation for a class is defined. As you’ll see in detail a bit later, it boils down to a self-contained block of program code called a method that is identified by the name you give to it. You can pass data items - which can be integers, floating-point numbers, character strings, or class objects - to a method, and these will be processed by the code in the method.

A method may also return a data item as a result. Performing an operation on an object amounts to executing the method that defines that operation for the object. Just so you’ll recognize one when you see it, let’s take a look at an example of a complete class definition. The code for the class CowboyHat we have been talking. This code would be saved in a file with the name CowboyHat.java. The name of a file that contains the definition of a class is always the same as the class name, and the extension will be .java to identify that the file contains Java source code. The code for the class definition appears between the braces that follow the identification for the class.

The code for each of the methods in the class also appears between braces. The class has three instance variables, owner, size, and hatOn, and this last variable is always initialized as false. Each object that is created according to this class specification will have its own independent copy of each of these variables in Java program, so each object will have its own unique values for the owner, the hat size, and whether the hat is on or off. I omitted the type parameter in this version of the class to make the code a little bit shorter. The keyword private, which has been applied to each instance variable, ensures that only code within the methods of the class can access or change the values of these directly.

Methods of a class can also be specified as private. Being able to prevent access to some members of a class from outside is an important facility. It protects the internals of the class from being changed or used incorrectly. Someone using your class in another program can get access only to the bits to which you want them to have access. This means that you can change how the class works internally without affecting other programs that may use it. You can change any of the things inside the class that you have designated as private, and you can even change the code inside any of the public methods, as long as the method name and the number and types of values passed to it or returned from it remain the same.

Our CowboyHat class also has five methods, so you can do five different things with a CowboyHat object. One of these is a special method called a constructor, which creates a CowboyHat object - this is the method with the name, CowboyHat, that is the same as the class name. The items between the parentheses that follow the name of the constructor specify data that is to be passed to the method when it is executed - that is, when a CowboyHat object is created.

Object-Oriented Programming in Java

As I said at the beginning of this post, Java is an object-oriented language. When you use a programming language that is not object-oriented, you must express the solution to every problem essentially in terms of numbers and characters - the basic kinds of data that you can manipulate in the language. In an object-oriented language like Java, things are different. Of course, you still have numbers and characters to work with - these are referred to as the primitive data types - but you can define other kinds of entities that are relevant to your particular problem. You solve your problem in terms of the entities or objects that occur in the context of the problem. This not only affects how a program is structured, but also the terms in which the solution to your problem is expressed. If your problem concerns baseball players, your Java program is likely to have BaseballPlayer objects in it; if you are producing a program dealing with fruit production in California, it may well have objects that are Oranges in it. Apart from seeming to be an inherently sensible approach to constructing programs, object-oriented programs are usually easier to understand.

In Java almost everything is an object. If you haven’t delved into object-oriented programming before, or maybe because you have, you may feel this is a bit daunting. But fear not. Objects in Java are particularly easy. So easy, in fact, that you are going to start out by understanding some of the ideas behind Java objects right now. In that way you’ll be on the right track from the outset.

This doesn’t mean you are going to jump in with all the precise nitty-gritty of Java that you need for describing and using objects. You are just going to get the concepts straight at this point. You’ll do this by taking a stroll through the basics using the odd bit of Java code where it helps the ideas along. All the code that you use here will be fully explained in later posts. Concentrate on understanding the notion of objects first. Then you can ease into the specific practical details as you go along.

Monday, December 26, 2011

Executing a Java Application

To execute the bytecode program in the .class file with the Java interpreter in the JDK, you make the directory containing the .class file current and enter the command:

java -enableassertions MyProgram

Note that we use just the name MyProgram to identify the program, not the name of the file generated by the compiler, MyProgram.class. It is a common beginner’s mistake to use the latter by analogy with the compile operation. If you put a .class file extension on MyProgram, your program won’t execute, and you will get an error message:

Exception in thread “main” java.lang.NoClassDefFoundError: MyProgram/class

While the compiler expects to find the name of your source file, the java application interpreter expects the name of a class, which is MyProgram in this case, not the name of a file. The MyProgram.class file contains the MyProgram class. We will explain what a class is shortly. The -enableassertions option is necessary for JDK 5.0 programs that use assertions, and since you will be using assertions once you have learned about them it’s a good idea to get into the habit of always using this option. You can abbreviate the -enableassertions option to -ea if you wish. If you want to override an existing CLASSPATH definition, the option is the same as with the compiler. You can also abbreviate -classpath to -cp with the compiler or the Java interpreter. Here’s how the command would look:

java -ea -cp . MyProgram

To execute your program, the Java interpreter analyzes and then executes the bytecode instructions. The Java Virtual Machine is identical in all computer environments supporting Java, so you can be sure your program is completely portable. As we already said, your program will run just as well on a Unix Java implementation as it will on that for Microsoft Windows, Solaris, Linux, OS/2, or any other operating system that supports Java.

Wednesday, December 21, 2011

Compiling a Java Program

Java source code is always stored in files with the extension .java. Once you have created the source code for a program and saved it in a .java file, you need to process the source using a Java compiler. Using the compiler that comes with the JDK, you would make the directory that contains your Java source file the current directory, and then enter the following command:

javac MyProgram.java

Here, javac is the name of the Java compiler, and MyProgram.java is the name of the program source file. This command assumes that the current directory contains your source file. If it doesn’t, the compiler won’t be able to find your source file. It also assumes that the source file corresponds to the Java language as defined in the current version of the JDK. There is a command-line option, -source, that you can use to specify the Java language version, so for JDK 5.0, the command above to execute the compiler is equivalent to:

javac -source 5 MyProgram.java

Note that you can also use 1.5 as the value with the source command-line option, in which case you could write the command like this:

javac -source 1.5 MyProgram.java

In practice you can ignore the -source command-line option unless you are compiling a Java program that was written using an older version of the JDK. For example, to compile code written for JDK 1.4 you would write:

javac -source 1.4 oldSourceCode.java

Here’s a simple program you can try out the compiler on:

public class MyProgram {
public static void main(String[] args) {
System.out.println(“Rome wasn’t burned in a day!”);
              &nb}
}

This just outputs a line of text to the command line. As this is just to try out the compiler, I won’t explain how the program works at this point. Of course, you must type the code in exactly as shown and save the source file as MyProgram.java. If you have made any mistakes the compiler will issue error messages. If you need to override an existing definition of the CLASSPATH environment variable - perhaps because it has been set by a Java development system you have installed - the command would be:

javac -classpath . MyProgram.java

The value of CLASSPATH follows the -classpath specification and here it is just a period. This defines just the path to the current directory, whatever that happens to be. This means that the compiler looks for your source file or files in the current directory. If you forget to include the period, the compiler will not be able to find your source files in the current directory. If you include the -classpath . commandline option in any event, it will do no harm. Note that you should avoid storing your source files within the directory structure that was created for the JDK, as this can cause problems. Set up a separate directory of your own to hold the source code for a program and keep the code for each program in its own directory.

Assuming your program contains no errors, the compiler generates a bytecode program that is the equivalent of your source code. The compiler stores the bytecode program in a file with the same name as the source file, but with the extension .class. Java executable modules are always stored in a file with the extension .class. By default, the .class file will be stored in the same directory as the source file. The command-line options we have introduced here are by no means all the options you have available for the compiler.

You will be able to compile all of the examples in the blog just knowing about the options we have discussed. There is a comprehensive description of all the options within the documentation for the JDK. You can also specify the -help command-line option to get a summary of the standard options you can use. If you are using some other product to develop your Java programs, you will probably be using a much more user-friendly, graphical interface for compiling your programs that won’t involve entering commands such as that shown above. However, the file name extensions for your source file and the object file that results from it will be just the same.

Installing the JDK

You can obtain detailed instructions on how to install the JDK for your particular operating system from the Sun web site, so I won’t go into all the variations for different systems here. However, you should watch out for a few things that may not leap out from the pages of the installation documentation.

First of all, the JDK and the documentation are separate, and you install them separately. The JDK for Windows is available in two versions - as a web install where components are downloaded incrementally, and as a full download of an .exe file that you just execute to start installation. The documentation for the JDK consists of a large number of HTML files structured in a hierarchy that are distributed in a ZIP archive. You will find it easier to install the JDK first, followed by the documentation. If you install the JDK to drive C: under Windows, the jdk1.5.0 directory sometimes referred to as the root directory for Java.

In some contexts it is also referred to as the Java home directory. The actual root directory name may have the release version number appended, in which case the actual directory name will be of the form jdk1.5.0_n where n is a release number, so in the first maintenance release, it will be jdk1.5.0_01, for example.

The sample directory contains sample applications that use JNLP, which is the Java Network Launching Protocol that is used for executing applications or applets from a network server without the need for a browser or the need to download and install the code. You don’t need to worry about the contents of most of these directories, at least not when you get started, but you should add the path for the jdk1.5.0\bin directory to the paths defined in your PATH environment variable. That way you will be able to run the compiler and the interpreter from anywhere without having to specify the path to it. If you installed the JDK to C:, then you need to add the path C:\jdk1.5.0\bin. A word of warning - if you have previously installed a commercial Java development product, check that it has not modified your PATH environment variable to include the path to its own Java executables.

If it has, when you try to run the Java compiler or interpreter, you are likely to get the versions supplied with the commercial product rather that those that came with the JDK. One way to fix this is to remove the path or paths that cause the problem. If you don’t want to remove the paths that were inserted for the commercial product, you will have to use the full path specification when you want to run the compiler or interpreter from the JDK. The jre directory contains the Java Runtime facilities that are used when you execute a Java program. The classes in the Java libraries are stored in the jre\lib directory. They don’t appear individually though. They are all packaged up in the archive, rt.jar. Leave this alone. The Java Runtime takes care of retrieving what it needs from the archive when your program executes.

The CLASSPATH environment variable is a frequent source of problems and confusion to newcomers to Java. The current JDK does NOT require CLASSPATH to be defined, and if it has been defined by some other Java version or system, it is likely to cause problems. Commercial Java development systems and versions of the Java Development Kit prior to 1.2 may well define the CLASSPATH environment variable, so check to see whether CLASSPATH has been defined on your system. If it has and you no longer have whatever defined it installed, you should delete it. If you have to keep the CLASSPATH environment variable - maybe because you want to keep the system that defined it or you share the machine with someone who needs it - you will have to use a command-line option to define CLASSPATH temporarily whenever you compile or execute your Java code. This corresponds to C:\jdk1.5.0 if you installed the JDK to your C: drive. This will create a new subdirectory, docs, to the root directory, and install the documentation files in that. To look at the documentation, you just open the index.html file that is in the docs sub-directory.

Java Program Development

For java application you need the Java 2 Platform, Standard Edition (J2SE) version 5.0 or later. You can download the JDK from Sun for a variety of hardware platforms and operating systems, either directly from the Sun Java web site at java.sun.com (for Windows, Solaris, and Linux operating systems) or from sites that you can link to from there. The JDK you’ll be using is available from java.sun.com/j2se. Versions of the Java Development Kit for Mac OS X are available from devworld.apple.com/java/.

Note that J2SE 5.0 succeeded J2SE 1.4. Normally, release 1.5 would have followed release 1.4, but it was decided to identify it as release 5.0 in recognition of the significance of the new features that are introduced by release 5.0 and the maturity of the product. Code module names in release 5.0 still use the denotation 1.5.0 so expect to see folder names incorporating 1.5.0 rather than 5.0, and you’ll see 1.5.0 popping up in a few other places too, so don’t let this confuse you.

One aspect of terminology also causes confusion sometimes - the Java Development Kit has been referred to at various times as the JDK - the Java Development Kit - and as the SDK - the Software Development Kit. The current usage with release 5.0 is JDK but with release 1.4 it was SDK, so if you see SDK this generally means the same as JDK. Just for consistency, I’ll use JDK to refer to any Java Development Kit in this blog of java.

To create the Java program source files that you will use with the JDK, you’ll need a plain text editor. Any editor will do as long as it does not introduce formatting codes into the contents of a file. Quite a number of shareware and freeware editors around are suitable, some of which are specific to Java, and you should have no trouble locating one. I find the JCreator editor is particularly good. There’s a free version and a fee version with more functionality, but the free version is perfectly adequate for learning.

A number of excellent professional Java program development environments are available, including products from Sun, Borland, Metrowerks, and Symantec. These all provide very friendly environments for creating and editing your Java source code and compiling and debugging your programs. These are powerful tools for the experienced programmer, but for learning Java using this blog of java, I recommend that you resist the temptation to use any of these, especially if you are relatively new to programming. Instead, stick to using the JDK from Sun together with a suitable simple program text editor for creating your source code. So why am I suggesting that you will be better off not using a tool that makes programming easier and faster? There are several reasons.

Firstly, the professional development systems tend to hide a lot of things you need to get to grips with so that you have a full understanding of how Java works. Secondly, the pro development environments are geared to managing complex applications with a large amount of code, which introduces complexity that you really are better off without while you are learning. Virtually all commercial Java development systems provide prebuilt facilities of their own to speed development. While this is very helpful for production program development, it really does get in the way when you are trying to learn Java. A further consideration is that productivity features supported by a commercial Java development are sometimes tied to a specific version of the Java 2 Platform. This means that some features of the latest version of Java may not work. The professional Java development tools are intended primarily for knowledgeable and experienced programmers, so start with one when you get to the end of the blog. Having said that, if you really do prefer to work with a commercial Java development system for whatever reason, and you have problems with running a particular example from the book, try it out with the JDK from the command line. The chances are good it will work okay.

Tuesday, December 20, 2011

Learning Java

Java is not difficult to learn, but there is a great deal to it. Although the Java language is very powerful, it is fairly compact, so acquiring an understanding of it will take less time than you think. However, there’s more to Java than just the language. To be able to program effectively in Java, you also need to understand the libraries that go with the language, and these are very extensive. In this book, the sequence in which you learn how the language works and how you apply it has been carefully structured so that you’ll gain expertise and confidence with programming in Java through a relatively easy and painless process. As far as possible, each chapter avoids the use of things you haven’t learned about already. A consequence, though, is that you won’t be writing Java applications with a GUI right away. While it may be an appealing idea, this would be a bit like learning to swim by jumping in the pool at the deep end. Generally speaking, there is good evidence that by starting in the shallow end of the pool and learning how to float before you try to swim, you’ll minimize the chance of drowning, and there is a high expectation that you’ll end up being a competent swimmer.

You can run Java programs on a wide variety of computers using a range of operating systems. Your Java programs will run just as well on a PC running any supported version of Microsoft Windows as it will on Linux or a Sun Solaris workstation. This is possible because a Java program does not execute directly on your computer. It runs on a standardized environment called the Java 2 Platform that has been implemented as software on a wide variety of computers and operating systems. The Java Platform consists of two elements - a software implementation of a hypothetical computer called the Java Virtual Machine (JVM) and the Java Application Programming Interface (Java API), which is a set of software components that provides the facilities you need to write a fully fledged interactive application in Java.

A Java compiler converts the Java source code that you write into a binary program consisting of bytecodes. Bytecodes are machine instructions for the Java Virtual Machine. When you execute a Java program, a program called the Java interpreter inspects and deciphers the bytecodes for it, checks it out to ensure that it has not been tampered with and is safe to execute, and then executes the actions that the bytecodes specify within the Java Virtual Machine. A Java interpreter can run standalone, or it can be part of a web browser such as Netscape Navigator, Mozilla, or Microsoft Internet Explorer where it can be invoked automatically to run applets in a web page.