Java
GOT JAVA?
Are you a Java junkie? Do you crave information on JavaScripts? If you're looking for your fix, JavaScripts.com is the place for you. This Web site has it all for the typical Java geek. It's the source of over 4,000 free JavaScripts, tutorials, and more!
If you're looking for a place to help spice up your Web page with Java, then you should start here. With 500,000 registered users and many active forums on Web development applications, you're sure to find people to exchange ideas with. You'll also receive the site's weekly newsletter, JavaScripts Express. You can post your own scripts on the site, so you can get the feedback you need to sharpen your Java skills.
You do have to register, but it's free. Whether you're looking for cool ways to redirect to a URL or you just want to see how JavaScript can magnify a picture online, check out this site! By the time you leave, if you don't already love Java, you will! http://www.javascripts.com/
UNDERSTANDING WHILE LOOPS
We can use for loops if we know how many times we want something repeated, but what if we want to repeat a set of statements until a condition becomes true--say, until the solution to a problem has been found? In that case, we can use a while loop. Here's the syntax:

while (condition) 
{ 
// Statements to be repeated, including a statement (or several) that alters the condition above. 
}
There's not a lot to while loops, except that a statement that evaluates to a boolean value (called condition above) is tested, and, if it is true, the code in the loop executes. Then the condition is tested again, and, depending on its value, the code is or is not executed once more. The important thing to remember is that the code in the loop absolutely must change the value of condition at some point. Otherwise, execution never breaks out of the loop.

AN ALTERNATE WAY TO DECLARE ARRAY VARIABLES Here is the standard way to declare a variable that will hold an array of char values:


char[] varname; 
That's usually how you'll see the job done. However, you might prefer the syntax

char varname[]; 
which has precisely the same effect. This approach more closely associates the array brackets with the variable name (in this case, varname). Either syntax is legal, and you can even mix them in the same program. Doing so isn't a great idea, though--pick whichever you like and stick with it, so your code will have a consistent look and be easier to trace.

CREATING AN ARRAY Once you've created an array variable, you'll want to create an array for it to contain. An array is an example of what's called an object. An object is an instance of a particular kind of thing. (For those of you keeping track, a kind of thing--as opposed to an instance of that thing--is called a class.) Objects are, however, different from instances of basic data type, such as float and int values.

What's more, an array object has several elements, each of which can contain a value.
To create an array object, we need to use the new keyword. We also need to specify what kind of data the elements of the array will hold, and how many elements there will be. Here's the syntax for declaring an array variable:

char[] varname; 
varname = new char[5]; 
The first line establishes a variable for holding an array of char values. The second line creates an array of five char values. (Actually, it only allocates memory for it, but that's close enough for now.)
Both "object" and "class" are very heavily used words with more meanings than I've provided here! Stick around and we'll learn more about other phenomena to which the words apply.

DEFAULT VALUES IN AN ARRAY

When you declare an array variable and specify a new array that's assigned to it, like

char[] varname; 
varname = new char[5]; 
the array isn't empty. Believe it or not, it actually contains default values. The default values depend on the kind of data the array has been declared to hold. In the example above, the varname array holds five instances of '\u0000', which is the Unicode character specification for a null character.
In an array, all numerical types (short, byte, int, float, double, and long) have initial values of 0. Array elements of type boolean are initialized as false.
You can also declare an array to contain objects in its elements--more on that later. For now, know that such array elements have a special value called null.

INTRODUCING ARRAYS

An array is a data structure that allows you to store multiple values under a single variable name. You could, for example, store the names of all the passengers on a bus in an array. You could also use an array to store some portion of the Fibonacci number sequence. There are many uses for arrays, and you may have encountered some of them in simpler languages like JavaScript. Java, however, imposes more rules on the declaration and population of arrays than do other languages. In large part, this has to do with Java's stricter rules about data typing.
You can declare an array variable without assigning anything to it, just as you can declare a variable of any basic type (double, char, and so on) without giving it a value. The most common way to declare an array variable without assigning it a value is like this:

char[] varname; 
That statement establishes a variable called varname that will, at some point, hold an array of char values.

POPULATING AN ARRAY

Just for fun, let's say you've already declared an array:

char[] vowel; 
vowel = new char[5]; 
Now you want to assign values to its elements. There are a couple of things to remember.
The first thing to keep in mind is the basic syntax, which looks like this:

arrayName[n] = value; 
In this case, arrayName is the name of the array, n is the index number of the element to which you want to assign a value, and value is the value that's being assigned to that element. Remember, too, that value must be of the same type that the array was declared to hold. You can't mix and match data types in a Java array.
One more thing to remember is that array index numbers start at 0. Accordingly, arrayName[0] is the first element in the array, arrayName[1] is the second, and so on. In an array of 30 elements, the last element is arrayName[29]. Continuing with the vowels example, we could assign values like this:

vowels[0] = 'a'; 
vowels[1] = 'e'; 
vowels[2] = 'i'; 
vowels[3] = 'o'; 
vowels[4] = 'u'; 
Now, you're probably thinking there's gotta be a faster way to do this. Indeed, there is! Next time...

ASSIGNING A SERIES OF VALUES TO AN ARRAY VARIABLE

We've seen that it's possible to very deliberately declare an array variable, create an array of default values assigned to that variable, and then populate the elements of the array with "real" values one by one.
Now, let's take a look at the shorter way of doing the same thing. For example, instead of

char[] vowels; 
vowels = new char[5]; 
vowels[0] = 'a'; 
vowels[1] = 'e'; 
vowels[2] = 'i'; 
vowels[3] = 'o'; 
vowels[4] = 'u'; 
we can do the following:

char[] vowels = {'a', 'e', 'i', 'o', 'u'}; 
The net effect is precisely the same--an array of five char elements, represented by the variable vowels. There's no explicit statement of the number five--the way there would be in a "new char[5]" phrase--but, after all, Java can count without our help.

GETTING THE LENGTH OF AN ARRAY

It's handy to know the length of (also known as the number of elements in) an array. You'll need to know the length of an array, for example, to systematically examine its elements. After all, the first element's index number is always 0, while the last element's index number is always defined by the expression

length - 1 
where length is the number of elements in the array. As it happens, there's an easy way to get the number of elements in any given array. It's easy because arrays are objects. Objects can have (among other things) properties that describe them. An array object has a property called length, which is an integer that represents the number of elements in the array. You refer to the length property like this:

arrayName.length 
Here, arrayName is the name of the variable that holds the array whose length you want. Here's an example:

int numberOfVowels; 
char[] vowels = {'a', 'e', 'i', 'o', 'u'}; 
numberOfVowels = vowels.length; 
This code results in numberOfVowels holding 5. From that, it's easy to calculate that the last element in the vowels array is vowels[4], or vowels[(numberOfVowels - 1)].

INTRODUCING TWO-DIMENSIONAL ARRAYS While it's possible to impose external rules upon a one-dimensional array (for example, remembering that the odd-numbered elements contain one kind of data and the even-numbered elements contain something else), this approach is needlessly complex and invites error. Since there is no inherent structure to the data, you have to remember the artificial (even/odd) rules, and errors will result if you don't. Happily, Java provides a better method of handling multidimensional arrays. These "arrays of arrays" are exactly what the name implies--arrays in which each element is another array. To declare a variable to hold such an array, use this syntax: int datesAndTimes[][]; Then, to put a two-dimensional array in that variable, use something like this: datesAndTimes = new int[3][2]; This creates an array of three elements, each of which contains another array of two elements.

MULTIPLE DATA TYPES? NO... In thinking about multidimensional arrays (which is to say, two-dimensional arrays for the moment), it's tempting to ask if there's a way to get them to hold data of multiple types. The answer, as far as the basic data types are concerned, is no. You see, when you make the declaration int datesAndTimes[][] = new int[3][2]; you get an array of three elements, each of which contains another array object of two elements. The elements of the three-element array are occupied by the references to the subsidiary two-element arrays. There's no room for anything else there.

REFERRING TO THE CONTENTS OF A TWO-DIMENSIONAL ARRAY Okay, so you've created a two-dimensional array with a statement like this: int datesAndTimes[][] = new int[3][2]; Now, you want to populate that array with integers representing dates and times. Element 0 in each subsidiary (two-element) array will be the date of a Monday in December, while element 1 in those arrays will be an hour. Here's how to do the assignments: datesAndTimes[0][0] = 6; datesAndTimes[0][1] = 13; datesAndTimes[1][0] = 13; datesAndTimes[1][1] = 9; datesAndTimes[2][0] = 20; datesAndTimes[2][1] = 22; This data structure refers to 1300 on December 6; 0900 on December 13; and 2200 on December 20. Note that we're still imposing artificial rules on the arrays. We still must remember that every 0th element in every subsidiary array is a date, while every 1st element is a time. Still, there's now some inherent structure to the data.

USING EXTERNAL RULES TO DEFINE DATA STRUCTURES By now, declaring an array should be no problem for you. The fastest way to do it is with a statement similar to this one: int[] mondays = {6, 13, 20, 27}; This statement yields a single variable that contains an ordered list of the dates in December 1999 that fall on a Monday. Accordingly, you can refer to the second Monday's date as mondays[1]. But what if you want to use the same variable to refer to specific times on those Mondays? You could do something awkward, like remember that the first element in the array and every third element thereafter was a date, while intermediate elements held times, like this: int[] datesAndTimes = {6, 9, 15, 13, 13, 21}; Under this awkward system, the array would represent the times 0900 and 1500 on December 6 and the times 1300 and 2100 on December 13. This would work, but the possibility for error is large. As it happens, Java provides a handy way to structure this kind of data--which we call two-dimensional arrays. Now that you know the hard way to do it, you'll have to tune in tomorrow to learn the easy way.

HOW TO THINK OF TWO-DIMENSIONAL ARRAYS Consider this two-dimensional array we've been working with for the past few days: int datesAndTimes[][] = new int[3][2]; You can think of a two-dimensional array as a table or grid. In the example above, the imaginary grid would be three spaces across by two spaces down. You can refer to any element in the table by its "across" coordinate (remembering to start counting at 0) followed by its "down" coordinate. The element in the lower-right corner of the table could be referred to as datesAndTimes[2][1].

ARRAYS OF MORE THAN TWO DIMENSIONS If you really want to, you can declare multidimensional arrays of more than two dimensions--arrays of arrays of arrays (in the case of a three-dimensional array), if you like. The syntax is familiar--just more of the same, really. For example, you might start by declaring the array like this: int dataCube[][][] = new int[3][3][3]; Then, to reference an element, use something like this: int dataCube[0][0][3] = 56; There's no rule that says a multidimensional array must be cubic. You can just as well do this: int dataCube[][][] = new int[5][4][4]; which results in the creation of an array of five two-dimensional arrays, each four-by-four elements.

ASSIGNING A VALUE TO A STRING VARIABLE Once you've declared a variable and noted that it will contain a String object, as in String quote = new String; you're free to define that String object more specifically. A String object incorporates a sequence of characters. When you define a String object by explicitly stating the sequence of characters--by using a "string literal," to put it another way--you enclose the sequence in quotation marks (""). Here's how it looks: quote = "We have nothing to fear but fear itself."; To accomplish the same effect with a single line of code, we could have used this statement: String quote = "We have nothing to fear but fear itself."; Next time, we'll start to examine some of the ways a String object behaves like an Array objects containing data of type char.

CONVERTING THE CASE OF A STRING'S CHARACTERS Say you've declared a String object with this declaration: String quote = "We have nothing to fear but fear itself."; Later in your program, you decide that you want President Roosevelt's statement to carry more emphasis. You can use the String object's toUpperCase() method to convert each character in the string to its capital equivalent (the method has no effect on uppercase letters, spaces, and punctuation marks). So, if you did this: String strongQuote = quote.toUpperCase(); you'd have a second String object, contained in the variable strongQuote, that held "WE HAVE NOTHING TO FEAR BUT FEAR ITSELF." There's a similar method, toLowerCase(), that converts a string to a sequence of lowercase characters.

GETTING THE LENGTH OF A STRING Recall that if you declare an Array object like this: char[] letters = {'a', 'b', 'c'}; you can find the number of elements in the array by using the length property that all arrays have. In other words, this: letters.length is equal to the value 3. Strings, being similar to arrays of characters, also have length properties. If you use the declaration String quote = "We have nothing to fear but fear itself."; and then make reference to quote.length, you'll find that quote.length has the numerical value 40. There are 40 characters in the string referred to by the variable called quote. Note that the quotation marks are not part of the string; they're just delimiters.

REFERRING TO CHARACTERS IN A STRING You know that you can declare a string like this: String quote = "We have nothing to fear but fear itself."; and that you can get the number of characters in the string by referring to its length property. That sounds like an Array object, eh? Well, then, it stands to reason that you can refer to characters in the string just as you would refer to elements in an array. But you can't, not exactly. Although the characters in a string have index values and the first character in a string has index 0 (not 1), you can't use the square-bracket syntax to access characters in a string. Instead, you must use a method of the String object called charAt(). The best way to illustrate the behavior of charAt() is to give some examples. Working with the string contained by variable quote, as defined above, these statements are true: char character; character = quote.charAt(0); // Variable character holds 'W'. character = quote.charAt(5); // Variable character holds 'v'. character = quote.charAt(39); // Variable character holds '.'.

THINKING OF STRINGS AS ARRAYS An array is a collection of data, organized into an ordered series of elements and referred to by a common name. You could, for example, declare an array of elements of type char. If you think about it, a string--a sequence of characters that means something, either in a human language or to a machine--is really an array of characters. Java acknowledges this fact and allows you to work with strings as arrays of characters. A string stored in a variable is a special data type--a kind of object called a String object. The String object behaves much like an Array object. You declare a variable for holding a String much like you'd declare a variable for holding an Array. The syntax looks like this: String quote = new String; As you can see, the keyword new comes into play here, just as it does when you declare an Array object.

BOOLEAN COMPARISONS OF STRINGS Here's a neat piece of truth. You might expect that if you made the two declarations String aString = "ABCDE"; String bString = "ABCDE"; and then did a boolean comparison of the two string variables, like this: aString == bString) that the comparison would yield the boolean value true. Not so. Even though the strings are the same, character for character, the variables refer to different String objects and so are different. The comparison yields false. On the other hand, if you did this: String aString = "ABCDE"; String bString = aString; and then compared the two variables, the comparison would yield true.

USING ESCAPED CHARACTERS IN STRINGS Last time, we played with string concatenation by using this code: String quote = "We have nothing to fear but fear itself" + ", said President Roosevelt."; That yields "We have nothing to fear but fear itself, said President Roosevelt." We need a way to distinguish the actual quote from the attribution. We should do this with quotation marks, but if we just stuck quotation marks into the strings, the Java compiler would interpret them as delimiting the strings. If we use the escape sequence for quotation marks, though, we can avoid this problem. Here's how it works: String quote = "\"We have nothing to fear but fear itself" + ",\" said President Roosevelt."; The sequence \" denotes a quotation mark that's part of the string, not part of its definition. The code above yields what we want when it is printed: "We have nothing to fear but fear itself," said President Roosevelt. Note that each \" sequence counts as a single character for indexing and character-counting purposes.

AN INTRODUCTION TO OBJECTS An object is a thing--something you can think about as a unit. You can think of an object as anything you can name with a noun. For example, let's say we want to talk about a particular bicycle--the bicycle Miguel Indurain was riding when he finished the 1996 Tour de France. This is one bike, a particular bicycle distinct from all others. The bike is a definable object. We can think of it in terms of a hierarchy of objects. 1) Definable things. 2) Vehicles. 3) Wheeled vehicles. 4) Bicycles. 5) Racing bicycles. 6) The particular racing bicycle Miguel Indurain was riding when he finished the 1996 Tour de France. We could design the hierarchy differently, but this is one way to do it. The important thing to understand is that Java organizes its objects in hierarchies such as this one.

GETTING RID OF EXTRA SPACES If you've ever done any work that involves taking input from a user by way of a command-line interface or a text field in a form or Web page, you know that users can put all kinds of extra characters in their input. Extra spaces (leading and trailing) are among users' favorites. Say, for example, you expected a variable to contain a name, but in fact it contained the string " Kate " That could really mess up your formatting. The String object makes it easy to get rid of leading spaces, trailing spaces, or both. Here's how you'd do it: String name = " Kate "; name = name.lTrim(); This results in name holding "Kate ". The lTrim() method strips spaces from the left side of the string. The rTrim() method does the same on the right side of the string. To do both sides at once, use the trim() method: String name = " Kate "; name = name.trim(); This results in name holding "Kate", which is what you want.

AN INTRODUCTION TO METHODS We've seen that objects have describable, inspectable characteristics called properties. Objects also can do things. Every kind of object can do a particular set of things that may or may not be unique to that object. Let's imagine, for example, that we have the bicycle Miguel Indurain was riding when he finished the 1996 Tour de France. I will instruct you to make that bike do things. Ready? - Apply the bike's rear brake. Okay, you say. - Release the bike's rear brake. Okay. - Pedal the bike forward 20 yards. Okay. - Put the bike in its lowest gear. Okay. - Turn the bike's handlebars 15 degrees to the right. Okay. - Sell the bicycle for a sum not less than $5,000. All those are things you can do with the object we defined. Most of the actions I asked you to perform are generic to multi-speed bicycles, but the last item asks you to do something with Indurain's bike that you probably couldn't do with that old Schwinn you keep out in the shed. Likewise, if I had asked you to start the bike's motor, you would have protested, since that's not something you can do with a bicycle. Java objects have methods that work much the same way. Each object has a set of methods you can invoke individually to cause certain things to happen. You've used methods to a limited degree already, in converting the case of characters in strings and stripping extra spaces from them.

GETTING FAMILIAR WITH FIELDS An object is a readily identifiable thing. Identifiable things have characteristics that we can describe. In the language of object orientation, such characteristics are called fields (sometimes they're called properties, too). For example, we might discern the following fields about a particular object (in this case, Miguel Indurain's bicycle). - What is the color of the bicycle Miguel Indurain was riding when he finished the 1996 Tour de France? That bicycle is red. - What is the weight of that bicycle? That bicycle weighs 12 pounds. - Is that bicycle for sale? No, it is not. (By the way, these replies are all guesses, for you nitpicking cyclists out there.) The point of this is that objects have characteristics we can inspect, just as Java objects have fields. You've already seen a couple of them, in the form of the length properties of the Array and String objects.

ADDING A METHOD TO A CLASS--PART 1 OF 2 Most objects will have methods in addition to their fields. To define a method in a class, you just add a special block of code inside the curly brackets that surround the class's code. The generic syntax for a method declaration is this: returnDataType methodName(arguments) { // Method code. } In this example, returnDataType is a data type--either one of the basic data types (int, long, char, and so on) or a class (String, JDialog, whatever). It represents the kind of data that the method returns, or sends back to the point from which it was called. Some methods don't return any value--in which case they should have the keyword void in place of returnDataType. Continuing, methodName is a unique name by which to identify the method. Strictly speaking, it need not be absolutely unique among the methods in its class, but there are special conditions for duplicating method names. The parentheses, in turn, contain arguments, which represent values that must be sent to the method for processing. (More on those arguments another day.)

ADDING A METHOD TO A CLASS--PART 2 OF 2 Again using the example of our Java checking account, let's say you want to add a method to the Check class that returns the number of the bank account to which the Check applies. You could define the method like this: class Check { // Instance variables follow: double amount = 0.0; String payee = ""; String memo = ""; // Class variables follow: final static int accountNumber = 234234; // Methods follow: int getAccountNumber() { return accountNumber; } // Further defining code goes here. } In this case, the method getAccountNumber() is declared in order to return a value of type int and to take no arguments. The only line of code in the class is the keyword return and the name of the variable accountNumber, which means that accountNumber's value is to be returned to wherever this method is called.

ADDING CLASS VARIABLES TO A CLASS Recently, we've been discussing objects and variables using the example of a checking account. Checks drawn on a given account have several things in common, one of which is the bank account number of the payor (the person writing the check and giving it to a payee). It stands to reason that in a class whose objects represent individual checks, the field containing the payor's account number would be a class variable--that is, it would be the same across all instances of the class and accessible even if no instances of the class existed at a given moment. Here, then, is how we'd modify our class declaration to bring about this effect: class Check { // Instance variables follow: double amount = 0.0; String payee = ""; String memo = ""; // Class variables follow: static int accountNumber = 234234; // Further defining code goes here. } As you can see, all that is required to make a field a class variable is to precede its declaration with the word static. This makes the variable (and its value) the same across all instances of the class Check. Don't forget, though, that changing the variable in one instance of the class causes the same change to show up in all other instances. However, as you'll see next time, there is a way to make the value unchangeable.

ADDING INSTANCE VARIABLES TO A CLASS Recently, we defined classes and objects using the example of a checking account. Now, let's take a look at the syntax that would implement our Check class, which will be used to create objects representing checks drawn on a bank account. These objects will need some instance variables, unique to each instance of the class, representing the payee, the amount, and a memo field (we'll ignore dates for now). Here's how we'd declare those fields: class Check { double amount = 0.0; String payee = ""; String memo = ""; // Further defining code goes here. } No big deal, really. You just declare those variables and their data types in the normal way. No further adornment is needed. Every instance of the Check class (that is, every Check object) will have fields called amount (initially 0.0), payee (initially an empty string), and memo (also initially an empty string). Each field may be manipulated independently of the fields in other instances of the Check object.

DEALING WITH MULTIPLE ARGUMENTS You've already seen that you can send values to a method for processing by putting them in the parentheses following the method's name. Sometimes (well, quite often, actually), methods require multiple arguments. In those situations, you just separate the arguments with commas. The Math object, for example, has a method called min() that returns the smaller of the two specified integers. Accordingly, the code int smaller = Math.min(15,14); results in the variable smaller holding 14. Interestingly, the Math object has four min() methods. In addition to the one that evaluates values of type int, there are others for values of types double, float, and long. Thankfully, the Java Virtual Machine (JVM) evaluates what kind of values are being sent to min() and automatically invokes the proper method in response.

FIELD TYPE 1: INSTANCE VARIABLES Objects may have fields, which are inspectable values (or references to values). When you define a field in a class (a class being the template from which instances of that class--objects--are created), you may want to allow each instance to have unique values for its fields. For example, if you were creating a class that was to be used to create objects that represented checks drawn against your checking account, you'd want each check (each instance of the class) to have its own value for the amount paid. Similarly, each check would have its own values for date and payee, even though those values would occasionally be the same on different checks. Fields that are unique to individual objects are called instance variables. When you create an object from a class, instance variables can have initial values, but those values can be changed without affecting identically named fields in other instances of the same class. Using the checking example again, you might create two check objects (or two instances of the check class). Both might have initial "amount paid" values (contained, say, in a field called amountPaid) of 0. Shortly, though, one instance of the class might have its amountPaid field changed to 100.00, while the other could be changed, independently, to 19.95.

HOW JAVA REPRESENTS THE OBJECT HIERARCHY Java has a much more limited knowledge of the world than you and I. It wouldn't know a Zip drive from a tube of hair oil. The objects it knows are all figments of computer memory, but those figments are what concerns you when you're trying to build programs. The way you think of different kinds of bicycles, for example, Java thinks of strings. Likewise, the way you conceive of toasters, Java understands windows in a graphical user interface (GUI). Java identifies its objects the same way you do: via a hierarchy of progressively more specific objects. Java knows that a window, for example, has certain characteristics, such as its size and whether it is capable of being resized. The language knows how to make browser windows do certain things, such as open or close. Java knows the characteristics (which it calls properties) and capabilities (which it calls methods) of a whole bunch of objects that have to do with the various kinds of data you can manipulate with a Java program. The syntax may look a little bit unusual at first. Java identifies objects by a series of special words separated by periods. Here's an example: java.lang.Math Now don't panic. That hierarchy simply refers to the Math object, which is a part of the java.lang set of objects (a set of objects is called a package in this case). See? Not too hard at all.

OBJECTS VERSUS CLASSES As we've recently discussed, an object is a particular thing (my bicycle, as distinct from your bicycle and all other bicycles, for example). In terms of programming, an object is a particular instance of a kind of logical structure. In fact, you can declare a String object that contains one sentence, and another String object that contains a line from a poem, and you have two distinct String objects floating around (you'd still have two objects if they both contained the same thing, by the way). But obviously, the two String objects have something in common. Indeed--they both come from the same class. You can think of a class as a cookie-cutter. Once you've created a class, you can use it to create numerous instances of its particular kind of object. The class contains the names and definitions of all methods that objects of that class will implement, as well as the names and associated values of the fields. There are, however, two kinds of fields and two kinds of methods that classes can include. (More on that next time.)

REFERRING TO FIELDS IN JAVA Once you've used the correct Java syntax to identify the object you want to work with, you can go on to specify the field you want to inspect or the method you want to employ. You do that by tacking another period on the end of your object reference, then specifying the name of the field or method to which you want to refer. For example, whenever the Java Virtual Machine (JVM) is active, an object called Math exists and is available for reference. The Math object has a field called PI, which is equal to the number 3.141592553589793. Math is an object, PI is one of its fields, and the value of PI is always 3.141592553589793. Whenever you need to use the constant pi in your calculations, you can refer to Math.PI and save yourself the trouble of entering the whole value in your code. That's the syntax for referring to a field: the name of the object, followed by a period and the name of the property. Accordingly, these two calculation are the same: double area = Math.PI * radius * radius; double area = 3.141592553589793 * radius * radius;

REFERRING TO METHODS IN JAVA To refer to a method of a Java object, you use much the same syntax you use to refer to a property. In fact, the only syntactic difference is that methods always have parentheses after them (the parentheses sometimes contain extra stuff, but not always). For example, it so happens that the Math object has a number of methods--one of which is called random(). The random() method generates a number (at random, for all intents and purposes) that is greater than or equal to 0.0 and less than 1.0. The generated number is of type double. Accordingly, to invoke that method, we'd use this syntax: Math.random() The following is a valid bit of code involving this method: double oneToTen = 10 * Math.random(); This code generates a double value between 0.0 and 9.999999999999999.

SENDING ARGUMENTS TO METHODS As we've discussed recently, all references to an object's methods are followed by parentheses, as in double randomValue = Math.random(); Some methods, however, require raw material to process. These pieces of raw material are called arguments. For example, there's a method of the Math object, sin(), which returns (in double form) the sine of a number you specify in the parentheses. Accordingly, the code double sine = Math.sin(90); results in the variable sine holding the value 1.0.

ADDING A CONSTRUCTOR THAT DUPLICATES AN EXISTING OBJECT At some point in the execution of your checkbook-management program, you might want to duplicate an existing instance of the Check object. One of the ways to do this is with a special constructor that takes a Check object as an argument. You can make the constructor copy the instance variables out of the argument object and assign them to the new object's instance variables. Such a constructor for the Check object might look like this (ignoring the rest of the class): Check(Check checkToCopy) { this(); amount = checkToCopy.amount; payee = checkToCopy.payee; memo = checkToCopy.memo; } You've seen the use of the dots before--they separate an object's name from the names of the variables and (in cases other than this one) methods it contains.

CALLING ONE CONSTRUCTOR FROM ANOTHER While it's possible to write multiple constructors for the same class, you'll frequently find that the settings you make with each of a class's several constructors are similar. In our check example, the payor and the checking account number will pretty much always be the same. Let's modify our check class so it has several constructors: - A "blank check" constructor that specifies only payor and account number - A "standard" constructor that specifies the above data, plus the payee and an amount - A "standard plus memo" constructor that includes the above, plus a memorandum string Let's start with the blank check constructor. We'll eliminate a lot of the variables and methods we put in earlier--they'd just get in the way now. class Check { String payor = "Ruth Ann Krinklemeyer"; String accountNumber = "123-123X"; double amount = 0.0; String payee = ""; String memo = ""; // Further defining code goes here. } That's the default constructor--the one that's called when someone instantiates the class without any arguments. Next time, we'll move on and refer to that default constructor from another constructor that does take arguments.

CALLING SEVERAL CONSTRUCTORS IN A CHAIN We want to modify our Check class so that you can declare an instance of the class with three arguments: a payee, an amount, and a memo field. If we design a constructor that can take and assign the memo field, we can leave the rest of the work up to other constructors, thanks to a special use of the this() call. Here's how: class Check { String payor = "Ruth Ann Krinklemeyer"; String accountNumber = "123-123X"; double amount = 0.0; String payee = ""; String memo = ""; // Further defining code goes here. } Now, let's modify that class so it includes a constructor that creates a check with the regular information, plus a payee and an amount. Here's how that would look: class Check { String payor = "Ruth Ann Krinklemeyer"; String accountNumber = "123-123X"; double amount = 0.0; String payee = ""; String memo = ""; Check(String namedPayee, double namedAmount) { this(); payee = namedPayee; amount = namedAmount; } Check(String namedPayee, double namedAmount, String namedMemo) { this(namedPayee, namedAmount); memo = namedMemo; } // Further defining code goes here. } The newly added constructor makes reference to this() in this way: this(namedPayee, namedAmount); It tells the Java interpreter to instantiate the current class (Check) with its two-argument constructor. Two of the three arguments that came to the three-argument constructor are sent to the other constructor, and the assignment of the third is handled locally. Note that the two-argument constructor uses this() as well. It's a chain of references.

DECLARING A CLASS METHOD WITH STATIC You may have noticed that in the latest version of the Check class (discussed in the previous tip), the getAccountNumber() method referred only to the accountNumber class variable (which in turn is declared with static). Because of the static status, it makes sense to declare the getAccountNumber() method to be a class method, accessible even when no objects of class Check have been instantiated. To do this, we use basically the same syntax we use to make a field a class variable, preceding the method declaration with the keyword static. (Note that class methods can only refer only to class variables and constants. If you try to refer to instance variables, you'll run into trouble when someone attempts to run the class method when no instances of the class exist.) Here, then, is the (slightly) modified class: class Check { // Instance variables follow: double amount = 0.0; String payee = ""; String memo = ""; // Class variables follow: final static int accountNumber = 234234; // Methods follow: static int getAccountNumber() { return accountNumber; } // Further defining code goes here. }

ENDOWING A CLASS WITH A CONSTRUCTOR A constructor is a special kind of method that serves to create an instance (an object) of the class in which the constructor appears. A constructor always has the same name as the class it instantiates, and a constructor never has a return data type (nor is it declared to be void). Usually, constructors serve only to set instance variables to values specified as arguments in the call to the constructor. Accordingly, here's our Check class (from the Java checking account example we've been using recently), with a new constructor: class Check { // Instance variables follow: double amount = 0.0; String payee = ""; String memo = ""; // Class variables follow: final static int accountNumber = 234234; // Methods follow: static int getAccountNumber() { return accountNumber; } void setAmount(double newAmount) { amount = newAmount; return; } //Constructor follows: Check (double initialAmount, String initialPayee, String initialMemo) { amount = initialAmount; payee = initialPayee; memo = initialMemo; } // Further defining code goes here. } Now, with this constructor in place, we can create a new object of class Check by using a call such as this: Check check834 = new Check(100.00, "Ruth Anne Krinklemeyer", "Song and dance"); This statement creates a new Check object (attached to the variable check834) with three initial values that represent the amount, payee, and memo.

INCLUDING MULTIPLE CONSTRUCTORS You can have multiple constructors in a given class, which in turn allows objects of the class to be created with different sets of information. In the case of our Java checking account, for example, it would be reasonable to allow the creation of new Check objects without specifying any contents for the new object's memo field. To allow that to happen, we must create a second constructor that doesn't expect a memo argument. Here's how it looks: class Check { // Instance variables follow: double amount = 0.0; String payee = ""; String memo = ""; // Class variables follow: final static int accountNumber = 234234; // Methods follow: static int getAccountNumber() { return accountNumber; } void setAmount(double newAmount) { amount = newAmount; return; } //Constructors follow: Check (double initialAmount, String initialPayee, String initialMemo) { amount = initialAmount; payee = initialPayee; memo = initialMemo; } Check (double initialAmount, String initialPayee) { amount = initialAmount; payee = initialPayee; } // Further defining code goes here. } In this case, the second Check constructor doesn't expect a memo value, as does the first constructor. Accordingly, you could call the two constructors (one with memo, and one sans) with this code: Check check834 = new Check(100.00, "Ruth Anne Krinklemeyer", "Song and dance"); Check check835 = new Check(19.95, "Late-Night TV Marketing Company"); The Java Virtual Machine (JVM) can route the instantiation call to the proper constructor, based on the number and type of arguments included in the call.

SETTING UP A METHOD THAT TAKES ARGUMENTS A lot of times, you'll want to send values to a method so that the method can use them in performing its work. These values are called arguments. To declare a method as one that takes an argument, use this syntax: returnDataType methodName(argumentType argumentName) You've seen the stuff at the beginning of this line, but the material in the parentheses may be new. In this case, argumentType represents the data type of the argument, while argumentName represents the name by which the argument will be known inside the method. If you want to accept more than one argument, separate the type/name pairs with commas. Accordingly, here's our Check class (from the example we've been using the last week or so), modified with a setAmount() method that takes an argument. class Check { // Instance variables follow: double amount = 0.0; String payee = ""; String memo = ""; // Class variables follow: final static int accountNumber = 234234; // Methods follow: static int getAccountNumber() { return accountNumber; } void setAmount(double newAmount) { amount = newAmount; return; } // Further defining code goes here. } One more thing to note: In setAmount(), that final return on a line by itself is optional. It signifies that the method (which is declared as void and therefore returns no value) is finished executing, and execution should return to the point at which this method was called. However, encountering a method's closing curly bracket has the same meaning, so the return in non-branching void methods is there only to help clarify the source code.

THIS() REFERENCES THE DEFAULT CONSTRUCTOR Last time, we created a class--having only a default constructor that creates a "blank check"--that looks like this: class Check { String payor = "Ruth Ann Krinklemeyer"; String accountNumber = "123-123X"; double amount = 0.0; String payee = ""; String memo = ""; // Further defining code goes here. } Now, let's modify that class so it includes a constructor that creates a check with the regular information, plus a payee and an amount. Here's how that would look: class Check { String payor = "Ruth Ann Krinklemeyer"; String accountNumber = "123-123X"; double amount = 0.0; String payee = ""; String memo = ""; Check(String namedPayee, double namedAmount) { this(); payee = namedPayee; amount = namedAmount; } // Further defining code goes here. } The key here is this(). The this() call refers to the current object--in this case, Check. When we call this() in the two-argument constructor, it calls the default constructor (the one that takes no arguments and sets the payor and accountNumber variables). The two-argument constructor then fills in the other two variables' values.

Assigning Subclasses to Superclass Variables by David Wall and Venkat Subbarao Say you have a class called Vehicle, which has a subclass called Motorcycle. You can make variables of type Vehicle hold objects of type Motorcycle, but you can't make Motorcycle variables hold Vehicle objects (not without jumping through hoops, anyway). This code is valid, assuming the Vehicle and Motorcycle classes exist:

Vehicle vehicleHolder; 
Motorcycle harley = new Motorcycle();
vehicleHolder = harley; 
No problem. Even though vehicleHolder is technically a Vehicle object, it can hold instances of any of its subclasses. All Motorcycle objects are also Vehicle objects. - Using Explicit Casting - So, now we know the above is valid JavaScript. This is because all Motorcycle objects are also Vehicle objects, but not all Vehicle objects are Motorcycle objects. You can account for this with what's called explicit casting, in which you acknowledge that you're creating an instance in which a superclass fits into a subclass. This code is valid:
 
Motorcycle harley; 
Vehicle conveyance = new Vehicle();
harley = (Vehicle) conveyance; 
The Class name in parenthesis is called an explicit cast. ***** Invoking a Servlet Bean is Similar to Invoking Servlets by Venkat Subbarao To invoke a Servlet Bean from the browser, simply type (into the location text box) the URL for the Bean. To call a Servlet Bean from an applet, create a URL specifying the Bean address and then call the ShowDocument() method using this URL. The source code for this looks like:
String urlstring = "http://machineaddress/servlet/myBean";
URL Location = new URL(urlstring);
getAppletContext.showDocument(Location,"_blank");

What’s Up With Get and Set? by David Wall You may have noticed that recent examples have included "get" and "set" functions. You may wonder why you would have a getWhatever() method that returns the value of variable whatever and a setWhatever() method that alters its value. Why wouldn't it be easier to just alter the fields directly, by referring to the name of whatever instance you were concerned with, and the name of the variable? In other words, how is... Check.setValue(45); ..different from Check.value = 45; Well, in simple cases, get and set methods are inefficient. Their advantage becomes more apparent in larger programs that might require modification. You might have a class that has getMass() and setMass() methods, and programs that referred to those methods that send and expect values in kilograms. If, for some reason, you had to change the internal workings of your program to use English units (the English unit of mass is the slug, interestingly), you could keep the external callers happy with relative ease by doing the conversion in the get and set methods. It's a maintenance thing.

Using toString() by David Wall Methods
Objects are an important part of Java, but they don't lend themselves to certain important tasks. For example, if you try to put an object in the parentheses here... System.out.println(); ..nothing good would happen were it not for a Java convention. The convention states that every object should have a method to work with, like the one shown above, called toString() that provides a string for methods. All of the core Java classes (the ones you get with the Java Development Kit) have toString() methods -- look and see. So, let's outfit our PoliticalCandidate class with a toString() method. Here's how it looks in modified form: public class PoliticalCandidate { // Class variable: public String name; // Constructor: public PoliticalCandidate(String providedName) { name = providedName; } // Methods: public String toString() { return "Hi! I'm " + name + ". Please like me."; } } With that in place, you can create an instance of PoliticalCandidate like this: PoliticalCandidate favored = new PoliticalCandidate("Charlie Grinster"); ..and then use this statement: System.out.println(favored); ..to get this output: Hi! I'm Charlie Grinster. Please like me. That's neat, I think -- the toString() method gives your objects a way to behave properly in situations in which they're required to act like strings. Next Week: What do you do when you have subclasses, and those need to have toString() methods, too? The solution is a feature of Java called method overriding.
Error Handling with VetoChangeException of JavaBeans by Venkat Subbarao
Java Beans implements Bound and Constrained properties with the help of Listener interfaces and Support classes. Listener interfaces are of two types: VetoableChangeListener and PropertyChangeListener. Of the two, VetoableChangeListener provides a method for vetoing the property change and makes the bean reject the value assigned to it. PropertyChangeListener lets you adjust for the change. Accordingly, there are two types of Support Classes: VetoableChangeSupport and PropertyChangeSupport. These classes maintain the list of listeners, so those listeners can be informed of the property change. In the following example code, myVetoableChange is a listener, which implements the vetoableChange method. This method defines the logic for the valid values. It verifies whether a property is valid or not by checking to see whether a file with that name exists. For complete source code, please visit http://www.venforyou.com/source/itworld/feb13-01.html class myVetobaleChange implements java.beans.VetoableChangeListener { public void vetoableChange(java.beans.PropertyChangeEvent event) throws PropertyVetoException { String filenamenew = dirname+F_S+(String)event.getNewValue(); try { BufferedReader productFile = new BufferedReader(new FileReader(new File(filenamenew))); } catch(Exception ee){ System.out.println("FILE NOT EXISTS"); throw new PropertyVetoException("Product file Not Exists",event); } } } Although constrained properties may appear simple to implement for handling error logic, extreme caution should be taken when using such a property. For instance, making a Bean itself veto a property change could result in unexpected and undesirable consequences, and implementing multiple vetoable listeners may hinder the performance by consuming the CPU Time.
Defining Abastract Methods by David Wall
It's campaign season in the United States and I figure, What better way to explore the political process than through Java? Let's implement a superclass called PoliticalCandidate that represents characteristics and capabilities that all political candidates have in common. However, since actual candidates usually belong to a political party, we'll use inheritance to differentiate among various kinds of candidates. The superclass, PoliticalCandidate, is declared like this: public class PoliticalCandidate { public abstract void vocalizeSlogan(); } What's that? You see, all political candidates have the capacity to vocalize their slogans, so we've defined the superclass as including a vocalizeSlogan() method. But you'll notice that there's no actual code there. You'll also notice that the word "abstract" precedes the method name. That means that the method is defined in the superclass just so it can be inherited and modified in the subclasses. Hence, the public access attribute as well. Having defined the superclass that way, we can declare several subclasses, one for each political party. The subclasses are DemocratCandidate, RepublicanCandidate, and GreenCandidate. DemocratCandidate, which is typical of the subclasses, is declared like this: public class DemocratCandidate extends PoliticalCandidate { public void vocalizeSlogan() { System.out.println("Babies are cute. Down with criminals!"); } } There, the vocalizeSlogan() method is fleshed out with useful code.
Getting Started With EJB by Venkat Subbarao
This week, I'd like to present an overview of Enterprise Java Bean Architecture. EJB allows us to develop and deploy server side software components. It is different from other architectures in that it defines standards, not only for a Bean Developer but also for an application server provider. It builds a contract, or bond, between a bean and the application server by dividing the responsibilities between them. Let's look at the working of an application server that follows EJB standards. Application Servers provide a container, which creates, destroys, and maintains beans. If you are familiar with database connection pooling, you know that you can improve performance of the application by using a fixed number of connections and swapping them if necessary. Container works similarly. When the application server is started, container creates multiple instances of each Bean; when a client makes a request for a Bean, it associates this bean instance with an EJBObject. The Client and Application Server talk through the EJBObject interface. The Container is responsible for creating, maintaining and destroying the beans. Moreover, it can implement low-level transactions, database connection pooling, and security. On the contrary, the developer of the bean is responsible for the business logic and may not even use the database information in his code. He can define the mapping between the bean properties and the database column using the Descriptor tool provided by the application server. If that is the case, all control is transferred to the container, making the container responsible for generating the necessary code for the database transactions. For more information on how the EJB Server works, please visit http://www.venforyou.com/main_publications.html (Migrating for RMI to EJB Column).
Using Access Attributes To Restrict Importability by David Wall
When you use an import statement to bring in the classes in a package, like this... import mathModels.*; ..you make the classes in that package available for use in the importing class. You make them available, that is, unless they have import restrictions on them. You see, Java allows you to make rules about how a class may be used remotely. Furthermore, Java has rules about how classes may be referred to by other classes within the same package. Members of a class may have any of three access attributes (keywords that regulate accessibility rules), or no stated access attribute at all. The three access attributes are: - public - private - protected Public members are accessible from any class, either in the same package or in another class that imports the package that includes the class containing the member defined as public. That's awkward, but correct. To put it another way, any class may access any public member via an import statement. Members without a stated access attribute (neither public, private, nor protected) are accessible from any class in the same package, but they can't be accessed through import statements. Private members cannot be accessed via import statements. In fact, they can't even be accessed by other classes in the same package. Private members exist only within the classes that define them. Within their package, protected members are like members with no stated access attribute -- they may be accessed freely. Outside their package, though, they may be invoked only as superclasses for subclasses that inherit their members.
How to Display Pop-up Windows from Applets by Venkat Subbarao
A reader named David has a question on whether a pop-up window can be displayed from an applet. The answer is yes, and today I will show you how. To begin, editing some properties on the applet may need password authentication. You can implement such a business requirement using pop-up dialogs. A ValidatePassword pop-up dialog consists of two methods: Constructor, which takes in the DialogProcessor interface as an argument, and the DialogProcessor, which contains the method dialog that can call back on the applet. The code for DialogProcessor looks like this: public class ValidatePassword extends Dialog { public ValidatePassword(Frame frd, Dialogprocessor pr) { super(frd,"Save As",true); ..... } } Applet constructs the dialog and displays it. The source code for it looks like: Frame fr1 = new Frame(); Dialog dlg1 = new ValidatePassword(fr1,this); fr1.setVisible(false); dlg1.setSize(100,100,200,200); dlg1.show(); For complete source code please visit: http://www.venforyou.com/march4week
Bust Out
Language: JavaScript Level: Intermediate Author: Me What you'll need: Nothing special This code will check to see if the location of the document is the same as the location of the frameset, if any. If it is not, then it "busts out." Here's the code: Now let's see how it works. It's fairly simple in concept, as most scripts are. It checks to see if it's location is the same as the entire page's location. If it's not, then the code changes that. If it is, the code leaves well enough alone. Did you use this script? I would greatly appreciate it if you would put a link from your site to mine. https://www.angelfire.com/pop/javascript/index.html
E-mail Validation
Language: JavaScript Level: Intermediate/Advanced Author: Me What you'll need: A form named "form", a text box named "email" and a button to trigger the function The Script: Did you use this script? I would greatly appreciate it if you would put a link from your site to mine. https://www.angelfire.com/pop/javascript/index.html
Status Bar Scroll
Language: JavaScript Level: Advanced Author: Me What you'll need: Nothing special This is a more complex code, but it is also concise. It includes a block of code and an onLoad event handler. Here's the code: Now let's take a look at what this script does. First, we declare the variables for the text that will be scrolling. The first variable probably looks a little weird. It's just a bunch of spaces to keep the blocks of text from bumping into each other. The substring method tells the browser how many characers to "scroll" at a time. For now, it's set to one character. Then it is added to the value of "scr". Then, the whole string is returned. The next line shows where the text should be displayed, and how many spaces should be allocated for the scroll. In this case, 60 is plenty. The next line has a setTimeout method, which keeps the scroll going. The number after the function name is in milliseconds, so a smaller number is faster. The very last part in getting this script running is calling the function. By placing the onLoad event handler in the body tag, the scroll will start once the page has loaded. Did you use this script? I would greatly appreciate it if you would put a link from your site to mine. https://www.angelfire.com/pop/javascript/index.html
Spawning a Window
By David Wall We've meddled around at the command line for a while now, and spent a lot of effort on concepts that don't generate any output at all. It's important stuff that we have to understand, but let's take a break from it and use Java to create a window and print something in it. We'll go back to non-graphical programming soon, because windowing adds a lot of overhead. To generate a simple window, use this code: import javax.swing.* public class WindowMaker { static JFrame myWindow = new JFrame("My window."); public static void main(String[] args) { myWindow.setBounds(10, 10, 300, 100); myWindow.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); myWindow.setVisible(true); } } That program displays a window with the title "My window." Let's look more closely at it. The import statement makes available the classes of the javax.swing package, which is where most graphical user interface classes are defined. Then, ... static JFrame myWindow = new JFrame("My window."); ..creates a new instance of the JFrame object, which is the object that represents a window. The argument specifies the contents of the title bar. Then, the main method does three things. This line... myWindow.setBounds(10, 10, 300, 100); ..specifies that the upper-left corner of the window should be 10 pixels from the left edge of the screen and 10 pixels from the top (the origin of this coordinate system is the upper-left corner of the screen). It also specifies that the window should be 300 pixels wide and 100 pixels tall. The next line... myWindow.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); ..tells the Java Virtual Machine to destroy this JFrame object when the user closes the window (as with the "X" button in Microsoft Windows). Finally, this line... myWindow.setVisible(true); ..tells the rendering system to actually put the JFrame object's image on the screen by making the JFrame object visible.
Implementing Different Types of Entity Beans
By Venkat Subbarao Last week, I defined an Entity Bean as a service that implements an action to a database or any other persistent data storage. Entity Beans maintain persistent data and usually map to data in a database. Whenever you update an entity Bean with a set method and once the transaction is complete, the data is committed to the database or any other data source. The application server provider or the Bean developer can define the actual implementation on how the attributes of the bean are mapped to different tables in a database. Depending on this implementation, we have Container Managed Entity Beans and Bean Managed Entity Beans. Container Managed Entity Beans are used when there is one-to-one mapping between a database table row and an attribute of a Bean. In this case, application provider provides the mapping tool and generates the implementation for the bean during deployment. If we look at last week's examples of hiring an employee, Skill, Supervisor can be such kinds of a Bean. Often a Bean cannot be mapped to a table column. Moreover, if you use some other kind of persistent data storage, then you need to develop a Bean Managed Entity Bean with the implementation of how to retrieve and update information to the data storage. Employee Bean which updates multiple tables or which talks to a legacy system can be such an example. For a simple example of Bean, please visit the following and select April 3 week column: http://venforyou.com/itworld.asp
More About Interfaces
David Wall Last week, we saw how to declare interfaces and, later, denote classes that implement the methods they define. How do you associate multiple interfaces with a given class? The answer combines interface implementation with inheritance. Here's an example: Say you want to define an interface that includes a method, isEven(), that returns true if a number sent to it is zero or is evenly divisible by two. Otherwise, the method returns false. Here's how that interface declaration would look: public interface EvenOdd { public boolean isEven(Number n); } We might also have another interface declaration that looked like this: public interface PrimeTest { public boolean isPrime(Number n); } The interfaces define their parameters as an object of type Number so we can pass several different kinds of values to them (the Number object's subclasses include byte, double, float, int, long, and short). When we set out to give some teeth to that interface, we can do it like this: public class NumberTester implements EvenOdd { public boolean isEven(Number n) { // Code that does testing and returns a boolean value } } Then, say we wanted another kind of NumberTester class. We could declare it like this: public class NumberTester2 extends numberTester implements PrimeTest { public boolean isPrime(Number n) { // Code that does testing and returns a boolean value } } There's no need to define isEven() in the NumberTester2 class because it inherits it from NumberTester. This is how you associate multiple interfaces with a class.
Implementing Different Types of Session Beans By Venkat Subbarao
Enterprise Java Bean Architecture defines the services offered by the application server as Beans. These Beans are of two types: Entity and Session Beans. Session Beans are reusable services that are most commonly used for defining the various actions that need to be taken when a request is passed to the server. Entity Beans are widely used for implementing the actions. For example, consider the process of creating a new employee profile. This process includes several different actions associated to it: 1. Adding employee General Information 2. Adding employee Skill Information 3. Adding Employment History 4. Adding Supervisor information, and so on. These sequences of actions and the associated logic are implemented in a Session Bean, whereas actual implementation of each action is defined in an Entity Bean. Let's examine the two types of Session Beans -- Stateful and Stateless. Unlike a Stateful Session Bean, a Stateless Session Bean does not maintain a transaction state. In the example above, if the order of transactions is not important and the activities are independent of one another, then the process can be implemented as a Stateless Session Bean. In real life, it is important to add the employee first, then get the employee ID and add the other information based on it. So, such a transaction is generally implemented as a Stateful Session Bean. However, Stateless Session Beans have little overhead and can have better performance over Stateful Beans. These types of Bean can be implemented at an advantage while retrieving information from a Database or for developing Reporting Systems.
Using Interfaces by David Wall
You've seen that it's possible, using abstract methods, to define skeleton methods in a superclass and flesh them out in various ways in subclasses. Java also allows you to create interfaces, which are kind of like abstract methods, but with key differences. Whereas classes can inherit only one superclass (a characteristic called "single inheritance"), they can implement any number of interfaces. Interfaces also come in handy during the development process, when they make it possible to note that certain classes need to be written before the project is done, while simultaneously allowing you to compile and run other parts of the code. The idea is that an interface defines a signature, which is to say it specifies the parameters that must be sent to methods and the data types of the values those methods return. To declare an interface, use this syntax: public interface interfaceName { public returnType methodName1(parameters); public returnType methodName2(parameters); } That interface defines two different methods, each of which can take different parameters and return a different kind of value. Interface definitions are written in .java files and are compiled into .class files, by the way, just like fully defined classes. All interfaces are final, and though you can put the "final" keyword in their opening line, it's bad style to do so. Later, when you decide to define the code that fleshes out those skeleton declarations, you'd write a class whose opening line looked something like this: public class className implements interfaceName { } That class must contain all methods defined in the interface, with matching parameter requirements and return data types.
Roles in EJB Architecture: By Venkat Subbarao
Enterprise Java Bean Architecture defines different roles to ease the development and deployment process. The four major roles involved are: 1. Container Provider 2. Bean Developer 3. Bean Assembler 4. Bean Deployer Bean Developer is responsible for implementing the business logic, whereas Container Provider takes care of the low-level transaction management, database connection pooling, and security. This simplifies the development effort of the Java developer. A simple Bean, for instance, can simply have create (), remove (), findXXX(), setXXX() and getXXX( ) methods. For deploying the bean onto a server, the properties (e.g. database to connect to, username, password etc.) need to be defined. These properties, along with the home and remote interfaces with which bean interacts, can be defined in the Descriptor files. According to EJB 1.1 specification, these files should be XML files with standard tags. Bean Assembler brings together Bean, Home, and Remote, and the descriptor files. The Application server provider usually provides tools for generating these descriptors. Finally, Bean Deployer is responsible for setting the runtime attributes and deploying the Bean using the application provider deployment tool.
Getting A Handle on Exceptions By David Wall
In Java, exceptions are kind of like errors. In fact, exceptions often arise because of errors, but that's not their only purpose in life. Exceptions exist to handle extraordinary circumstances, whether those circumstances are due to an unexpected (and therefore erroneous) situation, or because of an anticipated but unusual set of circumstances. Exceptions provide you with a way to handle irregularities gracefully. Depending on the nature and severity of the situation that causes an exception, exception-handling features in your code can often prevent exceptions from turning into show-stoppers that halt execution in an ugly way. Exceptions occur, to cite a few examples, when: * You try to do something mathematically illegal, like divide by zero. * You make an invalid reference, as to array element 10 in a five-element array. * You ask a method to do something it isn't capable of doing. Note that these are the sorts of errors that won't usually show up at compile time. Many times they arise because of data incompatibility issues, such as when a user or client process provides invalid input to your program. When exceptions occur, the object that caused the problem is passed to an exception-handling facility, which is a block of code that exists for the purpose of dealing with exceptions. Because of the object passing, you say that exceptions are "thrown." The syntax for working with exceptions involves at least two and sometimes three blocks of code, known respectively as the try block, the catch block, and the finally block. The try block is where problems may occur and so where exceptions may be thrown. The catch block is what deals with them if they are thrown. The finally block, which is optional, runs regardless of whether an exception was thrown, and allows you to make sure things are set right in the event that the execution of the try block was interrupted by an exception. We'll detail this further next time, but for now, just be aware of the keywords try, catch, and finally, used like this in a method: try { // Code that runs every time and may throw an exception } catch (exceptionType exceptionName) { // Code that deals with exceptions of exceptionType, // referred to here as exceptionName } finally { // Code that runs every time, regardless of whether // the try block threw an exception }
Buttons to Close a Window
Try this code out. It uses JavaScript close() funtion:
If that is the only window open, the user will be asked if they wish to close the window; otherwise it will just close it.
Most tips are from TipWorld - http://www.tipworld.com :The Internet's #1 Source for Computer Tips, News, and Gossip
David Wall works as a freelance writer, programmer, lecturer, and consultant. Based near Washington, D.C., David has written and co-written several books, including Graphics Programming with JFC. He enjoys traveling, sailing, woodworking, and literary nonfiction. His woodworking habit has come in handy for building those much-needed bookshelves in the Dave Cave. He can be reached at david.wall@javaworld.com.
Venkat Subbarao is the lead software analyst at Infovision Software Services Group -- a group devoted to software consulting and training. He designed and developed various internet/intranet applications using JSP-JavaBeans, EJB and XML. He can be reached at venkat.subbarao@javaworld.com.