Showing posts with label programs. Show all posts
Showing posts with label programs. Show all posts

Sunday, January 8, 2012

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.

Advantages of Using Objects

As I said at the outset, object-oriented programs are written using objects that are specific to the problem being solved. Your pinball machine simulator may well define and use objects of type Table, Ball, Flipper, and Bumper. This has tremendous advantages, not only in terms of easing the development process and making the program code easier to understand, but also in any future expansion of such a program. Java provides a whole range of standard classes to help you in the development of your program, and you can develop your own generic classes to provide a basis for developing programs that are of particular interest to you.

Because an object includes the methods that can operate on it as well as the data that defines it, programming using objects is much less prone to error. Your object-oriented Java programs should be more robust than the equivalent in a procedural programming language. Object-oriented programs take a little longer to design than programs that do not use objects since you must take care in the design of the classes that you will need, but the time required to write and test the code is sometimes substantially less than that for procedural programs. Object-oriented programs are also much easier to maintain and extend.

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.

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.

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.

Learning Java - The Road Ahead

Before starting out on any journey, it is always helpful to have an idea of where you’re heading and what route you should take, so let’s take a look at a brief road map of where you’ll be going with Java. There are five broad stages you’ll progress through in learning Java using this blog:

[1] The first stage is this post. It sets out some fundamental ideas about the structure of Java programs and how they work. This includes such things as what object-oriented programming is all about and how an executable program is created from a Java source file. Getting these concepts straight at the outset will make learning to write Java programs that much easier for you.

[2] Next, you’ll learn how statements are put together, what facilities you have for storing basic data in a program, how you perform calculations, and how you make decisions based on the results of them. These are the nuts and bolts you need for the next stages.

[3] In the third stage, you’ll learn about classes - how you define them and how you can use them. Classes are blueprints for objects, so this is where you’ll learn the object-oriented characteristics of Java. By the time you are through this stage, you will have learned all the basics of how the Java language works, so you’ll be ready to progress further into how you can use it.

[4] In the fourth stage, you’ll learn how you can segment the activities that your programs carry out into separate tasks that can execute concurrently. This is particularly important for when you want to include several applets in a web page, and you don’t want one applet to have to wait for another to finish executing before it can start. You may want a fancy animation to continue running while you play a game, for example, with both programs sitting in the same web page.

[5] In the fifth stage, you’ll learn in detail how you implement an application or an applet with a graphical user interface, and how you handle interactions with the user in this context. This amounts to applying the capabilities provided by the Java class libraries. When you finish this stage, you will be equipped to write your own fully fledged applications and applets in Java.

Throughout this book I’ll be using complete examples to explore how Java works. You should create and run all of the examples, even the simplest, preferably by typing them in yourself. Don’t be afraid to experiment with them. If there is anything you are not quite clear on, try changing an example around to see what happens, or better still - write an example of your own. If you’re uncertain how some aspect of Java that you have already covered works, don’t look it up right away - try it out. Making mistakes is a very effective way to learn.

Tuesday, December 20, 2011

Java Programs

There are two basic kinds of programs you can write in Java. Programs that are to be embedded in a web page are called Java applets, and normal standalone programs are called Java applications. You can further subdivide Java applications into console applications, which only support character output to your computer screen (to the command line on a PC under Windows, for example), and windowed applications, which can create and manage multiple windows. The latter use the typical GUI mechanisms of window-based programs - menus, toolbars, dialogs, and so on.

While you are learning the Java language basics, you will be using console applications as examples to illustrate how things work. These are applications that use simple command-line input and output. With this approach you can concentrate on understanding the specifics of the language, without worrying about any of the complexity involved in creating and managing windows. Once you are comfortable with using all the features of the Java language, you’ll move on to windowed applications and applet examples.

Because your Java program consists of bytecodes rather than native machine instructions, it is completely insulated from the particular hardware on which it is run. Any computer that has the Java environment implemented will handle your program as well as any other, and because the Java interpreter sits between your program and the physical machine, it can prevent unauthorized actions in the program from being executed.

In the past, there has been a penalty for all this flexibility and protection in the speed of execution of your Java programs. An interpreted Java program would typically run at only one-tenth of the speed of an equivalent program using native machine instructions. With present Java machine implementations, much of the performance penalty has been eliminated, and in programs that are not computation intensive - which is usually the case with the sort of program you would want to include in a web page, for example - you really wouldn’t notice this anyway. With the JVM that is supplied with the current Java 2 Development Kit (JDK) available from the Sun web site, there are very few circumstances where you will notice any appreciable degradation in performance compared to a program compiled to native machine code.

Introducing Java

This blog will give you an appreciation of what the Java language is all about. Understanding the details of what I’ll discuss in this post is not important at this stage; you will see all of the topics again in greater depth in later posts of the blog. The intent of this post is to introduce you to the general ideas that underpin what I’ll be covering through the rest of the book, as well as the major contexts in which Java programs can be used and the kind of program that is applicable in each context.

book of java


In this blog you will learn:

[1] The basic characteristics of the Java language
[2] How Java programs work on your computer
[3] Why Java programs are portable between different computers
[4] The basic ideas behind object-oriented programming
[5] How a simple Java program looks and how you can run it using the Java Development Kit
[6] What HTML is and how it is used to include a Java program in a web page