Java Language Fundamentals (Part 3)
Java Keywords
The following is a list of keywords in the Java language
this |
Java 1.2 course notes and work plan edited from several sources. This is a work in process and is constantly being refined, though may not be updated to the latest Java releases. Included is a collection of Java certification practise questions and answers.
Java Keywords
The following is a list of keywords in the Java language
this |
Identifiers
Identifiers are the blocks of a programming language - that is, they are the entities (values and data) that act or are acted upon. An identifier can be any length, but it must start with a letter, an underscore or a dollar sign. The rest of the identifier can include any characters except for those that are used as operators, e.g. +, -, * and others. There is one more restriction, you can’t use keywords in Java as a variable name. Valid identifiers are:
Java uses 16 bit Unicode rather than 8 bit ASCII text, so a letter has a considerably wider definition than just a to z or A to Z.
As mentioned before, an identifier can’t be a keyword, but it can contain a keyword as part of it’s name. For example:
importText()is valid even though import is a keyword.
Comments and Code Conventions
There are 3 types of comments allowed in the Java language:
// comment on one line
/* comment on one or more lines */
/** comment which can be used in the javadoc tool to produce HTML documents */
Always document your code!!!!! I’ll say it again, ALWAYS DOCUMENT YOUR CODE!!! Well documented code is easy for other developers to modify at a later date. In fact you could be that developer, who has to change the undocumented code that you produced a year earlier and can’t remember what all of those 1000 lines of code does.
Do not put obvious comments in. if you have one line of code in a class that prints a string, don’t write “this class prints a string”. On the other hand, if you have a complex class that contains 150 lines of code, comment liberally.{
topSpeed = 120;
lowSpeed = 35;
}
You can increase readability by using meaningful class, variable, and method names. Avoid using names like “d1” – rather use something like “firstDate”. The Java convention for identifiers are:
Class identifiers – a noun with the first letter of each word capitalized – for example: class MyCatVariables – a noun with the first letter of the first word lowercase and each subsequent word capitalized – for example: int topSpeed;
Methods – a verb with the same naming convention as variables – for example: public void DropCat()Interfaces – capitalized like class names
Constants (finals) – all letters capitalized. For example:while (counter < 0){
for (loopCounter = 0; loopCounter < 11; loopCounter++){
System.out.println(“this is difficult to read”);
}
System.out.println(“think how this looks with another 100 lines!”);
}or this code snippet:While (counter < 0){
For (loopCounter = 0; loopCounter < 11; loopCounter++){
System.out.println(“this is better”);
}
System.out.println(“this shows the inner loop better”);
}
Nuts and Bolts
This section covers the basic components of the Java Language. It will include variables, keywords, primitive types and class types.
Section Objectives
Exercise 1 - 3 Using the API Documentation
Exercise 1 - 4 Create another simple Java application
The Menu Applet
Self Test Question
Public class BadClass{
Public void main(string args){
…
…
}
}
The main source of information as to the various classes, fields, and methods available in the Java language is detailed in the Application Programming Interface (API) documents. These HTML files are arranged hierarchically, so that the home page lists all the packages as hyperlinks. If you select a link, the classes contained in that package are listed. Selecting a class then brings up a description of the class, it’s fields and methods, and links to related classes, methods and fields.
Figure 2 – The Java API Online Documentation
The main sections of a class document are:
Unfortunately, there aren’t many examples available to demonstrate the syntax. There are general examples available in a separate folder on your hard drive.
If you refer back to the HelloWorld.java file you can see that the code starts off with two import statements. By importing classes or packages, a class can more easily refer to classes in other packages. For example if you do not want to import the packages then you have to add the highlighted bits shown below to your HelloWorld.java file:
public class HelloWorld extends java.applet.Applet{
public void paint(java.awt.Graphics g){
g.drawString("Hello world!", 50, 25);
}
}
This might not seem much extra to write at the moment, but believe me when your code is more than 500 lines it is going to be so much easier to just import the packages rather than to include the whole path in your code.
Besides importing individual classes, you can also import entire packages. Here's an example:
import java.applet.*;
import java.awt.*;
Note: You might have noticed that the “Hello World” application example from the previous lesson uses the System class without any fix, and yet does not import the System class. The reason is that the System class is part of the java.lang package, and everything in the java.lang package is automatically imported into every Java program.
There is no overhead involved with importing entire packages so there isn’t any real reason not to!
Lets now move onto the class definition. Every applet must define a subclass of the Applet class. In the "Hello World" applet, this subclass is called HelloWorld. Applets inherit a great deal of functionality from the Applet class, ranging from communication with the browser to the ability to sent a graphical user interface (GUI). The extends keyword indicates that HelloWorld is a subclass of the class whose name follows Applet. If the term subclass means nothing to you don’t panic, you'll learn about it soon.
The HelloWorld applet implements just one method, the paint method. Every applet must implement at least one of the following methods: init, start or paint. Unlike Java applications, applets do not need to implement a main method. We will go into the details of init, start and other methods bit later in the course.
Returning to the above code snippet, the Graphics object passed into the paint method resents the applet's onscreen drawing context. The first argument to the Graphics drawString method is the string to draw onscreen. The second and third arguments are the (x,y) position of the lower left corner of the text onscreen. This applet draws the string "Hello world!" starting at location (50,25). The applet's coordinate system starts at (0,0), which is at the upper left corner of the applet's display area.
Exercise 1 - 2: The “Hello World” Applet
Create a text file named HelloWorld.java with the code shown 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);
}
}
Compile the source file with the Java compiler and as before it should create a HelloWorld.class file in the same directory.
Note: Java compiler in the JDK will compile both applications and applets.
An applet is not executed in the same way as an application. You must embed an applet in a web page before it can be run. You can then execute it either in a Java-enabled web browser such as Explorer and Firefox, or you can execute it using the appletviewer provided by JDK.
This means that you should at least know some basic HTML to accomplish this. In this course we are only going to cover enough HTML so we can run over applets. If you would like to learn more advanced HTML then you should get a proper HTML book.
When you define a web page as an HTML document, it is stored in a file with the extension .html. A HTML document consists a number of elements, and each element is identified by tags. The document will begin with <HTML> and end with </HTML>, these are tags, and each element in an HTML document will be enclosed between a similar pair of tags between angle brackets. Here is an example of an HTML document consisting of a title and some other text:
<HTML>
<HEAD>
<TITLE>My
First Web Page</TITLE>
</HEAD>
<BODY>
You can write
anything you want.
</BODY>
</HTML>
The text enclosed by the <TITLE> element tags will be displayed as the window title when the page is being viewed. Other element tags can appear within the <BODY> element, and they include tags for headings, lists, tables, links to other pages and Java applets. You can find a comprehensive list of available HTML tags in any HTML book.
For many element tag pairs, you can specify an element attribute in the starting tag which defines additional or qualifying data about the element. This is how a Java applet is identified in an <APPLET> tag.
Now we know enough to put our HelloWorld applet on a web page so lets continue where we left it.
Using a text editor, create a file named Hello.html in the same directory that contains
HelloWorld.class. This HTML file should contain the following text:
<HTML>
<HEAD>
<TITLE> A
Simple Program </TITLE>
</HEAD>
<BODY>
Here is the output of my program:
style='background:silver;mso-highlight:silver'><APPLET CODE="HelloWorld.class" WIDTH=150 HEIGHT=25>
</APPLET>
</BODY>
</HTML>
Lets look at the shaded line above, the applet to be executed is HelloWorld.class. The file containing the bytecodes for the applet is specified as an attribute in the <APPLET> tag. The other two attributes define the width and height of the region on the screen that will be used by the applet when it executes. These are compulsory.
To run the applet, you need to load the HTML file into an application that can run Java applets. This application might be a Java-compatible browser or another Java applet viewing program, such as the Applet Viewer provided in the JDK. You can invoke the JDK appletviewer from the DOS command prompt as follows:
appletviewer Hello.html
First we start with the comments as HelloWorldAppc.java starts with the comments. The Java language supports three kinds of comments:
/* text */
The compiler ignores everything from /* to*/ .
/** documentation */
This indicates a documentation comment (doc comment, for short). The compiler ignores this kind of comment, just like it ignores comments that use /* and */. The JDK javadoc tool uses doc comments when preparing automatically generated documentation.
// text
The compiler ignores everything from // to the end of the line.
Now lets look at the class definition, in the Java language the simplest form of a class definition is
class MyClass{
.
.
}
The keyword class begins the class definition for a class named MyName. The variables and methods of the class are enclosed by the curly brackets that begin and end the class definition block. The "Hello World" application has no variables and has a single method named main.
Every Java application must contain a main method whose signature looks like this:
public static void main(String[] args)
The method signature for the main method contains three modifiers:
public indicates that the main method can be called by any object.
static indicates that main method is a class method.
void indicates that the main method doesn't return any value.
All this will be explained in detail later in the course so don’t worry much about it now.
The main method in the Java language is similar to the main function in C and C++. When the Java interpreter executes an application, it starts by calling the class's main method. The main method then calls all the other methods required to run your application.
If you try to invoke the Java interpreter on a class that does not have a main method, the interpreter refuses to compile your program and displays an error message similar to this:
In class NoMain: void main(String argv[ ]) is not defined
As you can see from the following code snippet, the main method accepts a single argument: an array of elements of type String.
public static void main(String[]
args)
This array is the mechanism through which the runtime system passes information to your application. Each String in the array is called a command-line argument. Command-line arguments let users affect the operation of the application without recompiling it.
The program has one line of code which performs an action. This action is to print the string of text “Hello World!” to the screen. This code is
System.out.println(“Hello World!”);
System is a class which is available by default. It has a method called println that prints the string and appends a carriage return. The semicolon at the end terminates the line.
Before we get into nuts and bolts of the Java language lets create a simple Java application and an applet to see how really easy it is to develop applications and applets. We will first type the code, compile it and then run it. Don’t worry about what each line of the code does at the moment it will all be explained in a moment, first just concentrate on how to compile and run the Java Program.
Exercise 1 - 1The “Hello World” Application
Using a plain text editor, create a file named HelloWorldAppc.java with the following Java code:
/* *
* The HelloWorldAppc class implements an application that
* simply displays "Hello World!" to the standard output.
*/
class HelloWorldAppc {
public static void main(String[] args){
//Display the string
System.out.println("Hello World!");
}
Java source code is always stored in files with the extension .java
Be aware that Java is case sensitive. In other words, Graphics is not the same as graphics!
Compile the file using Java compiler that comes with JDK, you would do this by typing the following command at your MSDOS command prompt (windows) :
javac HelloWorldAppc.java
If the compilation succeeds, the compiler creates a file named HelloWorldAppc.class in the same directory (folder) as the Java source file. This class file contains the Java bytecodes, which are platform-independent codes interpreted by the Java runtime system. If the compilation fails, make sure you typed in and named the program exactly as shown above, using the capitalization shown.
Run the program using the Java interpreter, to accomplish this enter the following command:
java HelloWorldAppc
You should see "Hello World!" displayed at your command line
Java enforces it’s code security through the JVM. As mentioned before, Java source files are compiled (converted into a set of bytecodes) and stored in a .class file.
At runtime, the bytecodes are loaded, checked and run in the JVM interpreter. This interpreter has two functions: to execute code and make calls to the underlying hardware. Generally, whilst the bytecode is first interpreted, a portion of the bytecode is compiled to native machine code and stored in memory. If the program is run, say immediately again, the computer can use the machine code. This allows Java to run nearly as fast as C or C++.
The Java Runtime Environment (jre) runs the code compiled for the JVM and performs three main tasks:
Loads the code – performed by the class loader
Verifies the code – performed by the bytecode verifier
Executes the code – performed by the runtime interpreter
The class loader loads all of the classes needed for the program execution. The class loader also separates the classes from the local file system from those imported from other sources. This security feature limits any “Trojan horse” applications (applications which look like standard applications such as a login box but really does something sinister, like stealing your username and password!) because local classes are always loaded first.
The class loader deals with the memory layout of the program. This protects against unauthorized access into restricted areas of code.
The bytecode verifier tests the format of the code and checks for illegal code – code that creates pointers, attempts to change object types, or violates object access rights. The verifier actually passes the code through four times to ensure that the code adheres to the JVM specification and does not violate system integrity.
Figure 1 - The JVM
The Java platform differs from most other platforms in that it's a software-only platform that runs on top of other, hardware-based platforms. The Java Platform has two components:
The Java Virtual Machine (JVM)
The Java Application Program Interface (Java API)
You have already been introduced to the JVM, it’s the base for the Java Platform. The Java API is a large collection of ready-made software components that provide many useful capabilities, such as graphical user interface (GUI) widgets. Some of the important features provided by the APIs are shown below:
Security – both low-level and high-level, including electronic signatures, public/private key management and access control.
Java Database Connectivity (JDBC) - provides uniform access to a wide range of relational databases. Networking - URLs, TCP and UDP sockets, and IP addresses.
Object serialization – Allows lightweight persistence and communication via Remote Method Invocation (RMI).
Internationalization – Help for writing programs that can be localized for users worldwide. Programs can automatically adapt to specific locales and be displayed in the appropriate language.
In many programming languages, memory is allocated dynamically at runtime with the developer responsible for deallocating this memory. If the developer neglects this somewhat difficult exercise, a memory leak occurs. Eventually, the program will crash as there will be no more memory available.
This process of disposing or deallocating objects which require memory is called garbage collection. Garbage collection is automatic in Java, as Java provides a system-level thread to track memory allocation. The garbage collection process will deallocate memory in the background whilst the program is running. During idle cycles in the JVM, the garbage collection thread checks for and frees any memory that can be freed.
This section is a general overview of programming with the Java language. It introduces the the Java Virtual Machine, Garbage Collection, Security Features, and starts you on your Java programming journey with the humble “HelloWorld” application
Java is a high-level programming language that lets you write programs that you can embed in the web pages (known as applets), as well as programs that you can run normally on any computer that supports Java (known as applications). You can also write programs that will run both as applets and applications.
The most important characteristic of Java is that it was designed from the beginning to be machine independent. Java programs will run without any change on any computer that supports Java.
The next most important feature of the Java is that it is object-oriented. The object-oriented approach to programming is also an implicit feature of all Java programs.
Apart from the above Java is also Robust, Secure, Multithreaded, Dynamic and Distributed. We will go into more depth into each of these as we progress through the course.
Java was created from a number of languages (the Java team took what they considered the best features) and left out some of the worst. For example, Java doesn’t allow you to work with pointers (although a pseudo-pointer can be used as we will discover later), it has automatic memory management or garbage collection, and because it is Object-Oriented, it is easier to visualize and model problems in a real world sense.
Easy to learn: Although Java is a powerful object-oriented language, it is easy to learn, especially for programmers already familiar with C or C++.
Write less code means faster program development: Comparisons of program metrics (class counts, method counts, and so on) suggest that a program written in Java can be four times smaller than the same program in C++. Therefore your development time may be as much as twice as fast versus writing the same program in C++.
Write better code: The Java language itself encourages good coding practices, and its garbage collection helps you avoid memory leaks. Java's object orientation, its JavaBeans component architecture, and its wide-ranging, easily extendible API let you reuse other people's tested code and introduce fewer bugs.
Avoid platform dependencies with 100% Pure Java: By following the purity tips mentioned throughout this course and avoiding the use of libraries written in other languages, you can keep your program portable.
Write once, run anywhere: Because 100% Pure Java programs are compiled into machine-independent bytecodes, they run consistently on any Java platform.
Distribute software more easily: You can upgrade applets easily from a central server. Applets take advantage of the Java feature of allowing new classes to be loaded "on the fly," without recompiling the entire program.
Java is “easier” to learn than, say, C++ but is certainly more difficult than languages such as Basic. Nevertheless, after this course you will find working in Java easier than tying your shoelaces (well, almost!)
Java also is an Object Oriented programming language that can be used to create stand-alone programs or browser-compatible code (applets).
Learning Java, like any programming language, is a “doing” as well as reading activity. You will find many exercises and self test question throughout this booklet. It is strongly recommended that you attempt each exercise and question. Do not be tempted to skip over questions because they seem difficult. Each exercise has an answer (in fact in programming, there are usually several solutions.)
This course will first discuss the Java runtime environment
and the syntax of the Java programming language. It will then cover
Object-Oriented (OO) concepts as they apply to Java. As the course progresses,
advanced features of the Java platform are discussed.
Whilst Java is a platform independent language, the course was
created on a Microsoft operating environment. Screen shots will differ from
those obtained when working in another operating system such as Unix or
Macintosh. The code, however, remains the same. In other words, the contents of
this course is applicable to all Java operating system ports.
Upon completion of this course module, you should be able to: