Chapter 3 - Java Basics

The minimal applet

An example of a minimal Java applet is just a simple class declaration.

	public class MinimalApplet extends java.applet.Applet {

	}

The MinimalApplet applet, does nothing but shows the minimum code that you need to include for the compiler to do its job. "MinimalApplet" is the name of the defined class and the file that contains this code must be named MinimalApplet.java. If these names do not agree, the compiler will fail to write a class file and exit with an error. Public refers to the fact that the class you are defining is readable by everyone, which should be true of all your classes at this point. Extends java.applet.Applet is stating that the MinimalApplet class we have defined extends or adds upon the provided Applet class. This allows us to inherit all the functionality of the default applet class without having to rewrite the code. Inheritance and classes are discussed in Chapter 6 and are part of the terminology of Object Oriented Programming.

The HTML code used to embed the MinimalApplet example is simple.

	<html>
	<head>
	<title>Minimal Applet</title>
	</head>
	<body>
	<applet code="MinimalApplet" height="100" width="200">
	</applet>
	Pretty boring huh?
	</body>
	</html>

The text "Pretty boring huh?" will be displayed inside Netscape next to the running applet but not in Sun's applet viewer. In both cases this applet shows a blank area 100 pixels high and 200 pixels wide.

Figure 3.1

A more useful example is the standard "Hello World" applet:

	import java.applet.*;
	import java.awt.Graphics;

	public class HelloWorld extends Applet {
 	
		public void init() {
			resize(60, 15);
		}

		public void paint(Graphics g) {
			g.drawString("Hello world...", 10, 0);
		}

	}

All statements or expressions in Java must end in a semi-colon and functions are wrapped in curly braces. The HelloWorld applet begins with two import statements. These act just like #include statements in C++ and import certain functionality into this class from the specified libraries. The first import statement allows the "extends java.applet.Applet" to be rewritten as "extends Applet" because the java.applet class libraries were imported. The asterisk (*) serves as a wild card and tells the compiler to import all class libraries that begin with java.applet. The second import statement allows the applet to use the drawString function in the Graphics class library which is needed to draw the message to the screen.

The init() method is called once immediately after an applet is loaded. An init function already exists in the Applet class but we have overridden the default with the one coded above. Our init() function instructs the applet to resize itself to 60 pixels wide by 15 pixels high.

We have also overridden the paint() method in the HelloWorld example. Our paint() function calls the drawString() method with three parameters separated by commas. The first parameter is the string to be drawn on the screen. A string is a succession of characters such as a sentence. The second and third parameters tell the function the coordinates where it should begin drawing the string. In this case the string is 10 pixels in to the right and 0 pixels down from the top (0, 0 is at the top left corner of the applet). There are other standard functions that we often choose to override for various reasons but they will be discussed later.

The HTML code to embed the Hello World applet is similar to the MinimalApplet example.

	<html>
	<head>
	<title>Hello World Applet</title>
	</head>
	<body>
	<applet code=HelloWorld height=25 width=60>
	</applet>
	...the applet declared!
	</body>
	</html>

Again, you will only see the text "...the applet declared!" if you are using Netscape and not the applet viewer because it is part of the HTML and not included in the class code. The height and width options in the applet tag should always be the same as the height and width of your applet so the applet is not clipped.

Figure 3.2

If you have any trouble compiling the code examples, make sure you have typed them correctly and have not forgotten the semi-colons.

Data types and variables

Variables are items that store information of a given type and are specified by a name. You must declare a variable and its type before you assign it a value. Names of variables are case sensitive, meaning that xnumber and xNumber are considered separate and distinct. Variables cannot begin with a number in Java.

	int year;
	long largeNumber;
	String myFirstName, myMiddleName, myLastName;
	boolean areYouThere;
	boolean stillHere = True;
	String bookTitle = "Apple Flavored Java";
	year = 1996;

The first four lines are simple variable declarations. The first word is the type of variable you are declaring and the second the name you are assigning it. The variable year has been declared of type integer and largeNumber has been declared of type long. You may also declare and name multiple variables on one line as shown above in the third example.

The next two lines declare, name, and assign values to variables. The last line assigns a value to a variable whose type has already been declared in the first line. The variable year now contains the integer value 1996.

It is often a good idea to use variable names that have some relevance to the value or its purpose. Large applets may use hundreds of variables and it helps to be able to remember their function from the name.

There are four integer types in Java that differ in size.

	byte			-128 to 127
	short			-32,768 to 32,767
	int			-2,147,483,648 to 2,147,483,647
	long			-9223372036854775808 to 9223372036854775807

Java also has two floating point numbers to represent numbers with a decimal part and differ in their precision.

	float			32 bits, single precision
	double			64 bits, double precision

Boolean values, true and false, are of type boolean and unlike other languages are not represented by numbers. Characters are of type char which are unsigned 16 bit blocks of space.

	boolean			true or false
	char			character

The following is a list of the commonly used non-printable characters:

	\n			newline
	\r 			carriage return
	\b			backspace
	\t			tab
	\f			form feed
	\'			single quote
	\"			double quote
	\\			backslash

Variables may also be declared as instances of a certain predefined class. Strings in Java are actual objects rather than arrays of characters and thus are contained in a class.

	String statement;
	Image myPicture;
	Font defaultFont;

The position in your code where you declare your variables matters. Certain functions may not be able to access your variables if you do not define them at the top of the class definition.

	import java.applet.*;
	import java.awt.Graphics;

	public class VariableDemo extends Applet {

		String message;
		String message2 = "The following are examples of using 					variables.";
		int x = 5;
		int y, z;
		String myNumber;
		boolean really;

			public void init() {
			resize(300, 100);
			message = "Hello there...";
			y = x + x;
			z = x * x;
			myNumber = "13";
			really = true;
		
		}

		public void paint(Graphics g) {
			String answer1 = java.lang.Integer.toString(y);
			String answer2 = java.lang.Integer.toString(z);
			g.drawString(message, 10, 10);
			g.drawString(message2, 10, 35);
			g.drawString("5 + 5 = " + answer1, 10, 60);
			g.drawString("5 * 5 = " + answer2, 10, 85);

		}

	}

Figure 3.3

Variables in the VariableDemo class are declared in two places, inside the class and inside the paint method. Variables declared just inside the class statement can be seen by any functions inside that class and since paint is a funtion inside VariableDemo it can use them. Variables declared inside the paint function would not be seen by any other functions inside class. These variables are called local variables and only exist while the paint method is running.

Also, notice the use of java.lang.Integer.toString() which turns an integer into a string so that it can be painted by the drawString() method.

Commenting your code is a good idea if something is obscure or if multiple people will be reading it. You can comment Java code in two ways. First, you can use a double slash that will cause the compiler to ignore the rest of that particular line.

	String myName;	// this is only the last name used to sort list

You may also use /* and */ which will cause the compiler to ignore everything between those two sequences.

	/* This program is calculates the mean distance between 
	    two moving points  */

Operators and expressions

Operators take variables or values as arguments, perform some calculations, and then return a result. Java operators consist of normal arithmetic operators, logical operators, and assignment operators.

The five arithmetic operators:

	+			addition
	-			subtraction
	* 			multiplication
	/			division
	%			modulus

The arithmetic operators behave like you would expect them to in normal settings. Division between integers will result in an integer with the remainder thrown away. The remainder can be calculated by the modulus operator which results in the remainder after evenly dividing the arguments. Java will convert the resulting data type as it needs to and under specific rules set by the Java Language Specification.

To increment or decrement a value, Java supports the ++ and -- operators. Incrementing a value adds 1 to the original value while decrementing a value subtracts 1 from the original value. This notation is not needed to fill in any gap in the operators already provided but instead serves as shorthand notation for these common commands (a savings of two keystrokes).

	x++			is the same statement as x=x+1
	x--			is the same statement as x=x-1

Note that these operators can be used in prefix or postfix notation but the position makes a difference. This will be of great importance in certain expressions such as loops and conditional statements.

	y=x++			y is assigned the value of x after it is incremented
	y=++x			y is assigned the value of x before it is incremented

Java supports the bitwise operators found in C++ for modification of values. Bitwise operators should be used with caution and are a more advanced method of modifying values.

	&			bitwise and
	|			bitwise or
	^			bitwise xor
	~			bitwise compliment
	<<			left shift
	>>			right shift
	>>>			right shift with zero fill

Java also provides comparison operators that return a boolean value as their result.

	==			equal to
	!=			not equal to
	>			greater than
	>=			greater than or equal to
	<			less than
	<=			less than or equal to

Boolean expressions can be combined and tested by using the provided logical operators.

	&&			and (true only if both are true)
	||			or (true if either or both are true)
	^			xor (true if operands do not agree)
	!			not (!false is equal to true)

Expressions are statements that consist of operands and operators that evaluate to a certain value. For example the following are all expressions:

	1 + 5			returns the integer 6
	8 / 5			returns the integer 1
	8 % 5			returns the integer 3
	5.5 - 3.0		returns the float 2.5
	true && false		returns the boolean false
	true && !false		returns the boolean true
	true ^ true		returns the boolean false

There is a need to store results into another variable so that they can be accessed without having to evaluate the original expression again. This is accomplished with the assignment operators.

	y = x			assign the value of x to y
	y = x + 5		assign the value of the result of (x + 5)
	y += x			is the same statement as y = y + x
	y -= x			is the same statement as y = y - x
	y *= x			is the same statement as y = y * x
	y /= x			is the same statement as y = y / x

It is important to realize that there is a certain order of operation that Java follows when evaluating expressions. For instance, 9 + 10 * 7 is not the same expression as (9 + 10) * 7. The first expression evaluates to 79 while the second expression evaluates to 133. If you are unsure of the operator precedence use parenthesis to override or ensure your expression.