Java

"They all laughed at Albert Einstein.
They all laughed at Columbus. Unfortunately,
they also laughed at Bozo the clown."

And then the King Leered...

By Vijay Mukhi

Every once in a while, the structure of technology has to run through acataclysmic dishwasher. Suddenly out of the magenta, a virgin idiot-proof idea wreaks a radical metamorphosis and the big, bad world gawks at it,holds it high on a virtual pedestal like the neighbour's puppy and sings paeans to it until a whole new regime of idiots comes along. Then there issomething else, something else and something else. And wait up, don't skip that tiny, little something else in the corner. It just might change your life...

In a world where you've got to be careful what you wish for (for you might wake up in pink pyjamas one dingy morning and find that you've got it!), Java is the latest dropping from the technoputing dishwasher. Extolled by self-styled pundits as a Web tool nonpareil . Embraced by the 'like wow' companies harder than the cardboard cutouts of the cyberbabes with peanut polythenes pinned across their bosoms. The concerned cyberpuppies and bar-stool cultural critics are already hoping impressionistic tykes to join tattoos and sneakers in the pantheon of this dubious globe-spanning megatrend called JAVA!

While its name might suggest one of those weak puns that comfortably pass for pseudonyms these days, in a hideously overcalculated effort to sprinkle the missing 'creative touch' on the digiteratti, Java is actually (and accidentally) just about as much fun as a plastic snap-together dragon from the bottom of a cracker Jack box that your grandma gave you for the fifth birthday. And it is catching on at a rate that could make wild crabgrass blush. Nothing trumpets its arrival more stridently than the episode of 28 heinously high-heeled heavyweights like Oracle, Borland, Silicon Graphics, IBM et al being smitten by it, and smitten bad enough to volunteer their oddly enthusiastic endorsements. But that's only half the story - the other half is Microsoft, the mammoth wheelbarrow pulled by the divine Gates, playing the hands-up after being waylaid by some-goddamn-company-in-a-goddamn-corner-of-the-world. After a spell of haplessly looking out of Windows, they too decided to follow the tried-n-tested aphorism : If you are being chased out of the village, wave a baton and make it look like a graceful parade. On another foot, however, Netscape Incorporation - the most trailblazing eligible bachelor around, prefers to play safe and wager its worth on making hay while the Sun shines (pun intended :).

In case that sounds like a gross exaggeration, try keying in the Midas-word Java as a query to your pet search engine, check out the number of hits sniffed out and tell us if we are going overboard.

Well then, welcome to digital blackhole, only a slightly modified to be called Java. The punch is : it sucks more catchy things than light.

Java - The accident that happened accidentally

"Revolutions are dignified accidents."

To get maximum attention, its hard to beat good, big mistake. Java is a royal case in point. In more ways than one, it is like Colgate oozing out of a tube squeezed too hard. Courtesy : Internet, the amorphous blob of bedfellow computers networks. Only the tube here is the market with the pressures thereof lending absolutely unnecessary and ill-timed impetus to the release of a product that was still in puberty. How else do you expect something that was intentioned to pop its clogs inside electronic appliances to end up in the programming languages rink. All that the folks at Sun Microsystems perhaps expected when they announced Java last summer was to devise a language that could traipse across unfriendly platforms, for that was the major bottleneck faced by networking software. It was neither designed for pentiums nor for the rather spooky vistas of UNIX, but for the gee-whiz gadgetry that only existed in the minds of the people who were designing it. But it has since cobbled into a whopping multitude of classes and libraries, and then some.

Picture this : You get up with the crack of dawn, because your alarm has croaked its designated signal. Your toaster that is connected to some sort of an intranet, downloads information from the alarm clock that it has to pop up a couple of slices of bread and tell the coffeemaker to whiff up a nice, warm mug. The VCR in the meanwhile has to rewind BladeRunner II or the movie last seen using it, while the thermostat in the AC would be asked to shut up.

If anything, that sounds like a scoop straight out of an H.G.Wells bestseller. But the mediated role of Java indeed was electronic consumer products. Until the whole project turned over a new leaf, altered its very rhizome and plain swept Sun off their feet (not to mention their schedules and deadlines). Infact, the whole Java episode was a frenzy in time. Even today, Sun is too busy mopping the floor to turn the faucet off. It is not entirely wrong to say, therefore, that what we see as Java today is not The

Java but a mere foretaste of what we are going to thrive on half a dozen months later (which is true literally as well, since the final version of Java is not yet out, at the last check).

That is to say that from a certain perspective, Internet served as a retroactive agent for Java rather than the loyal crutch it has been touted as. Wouldn't Java be a trifle healthier and better as a language if it was born in normal nine months rather than being snuffed out as a caesarean case that scraped the baby out in three weeks!

Nevertheless, it gives a strong reason for the rest of us that if this is what the accident version looks like, wonder what the real thing would have been. Ask the cook who made his best custard-pudding while trying to experiment for the first time in the kitchen...

Java - The least common denominator

"The nice thing about standards is that there are so many of them to choose from. "

While Java serves up a considerable cornucopia of widgets in the form of AWT (which gives a developer a free reign over the grotesque underpinnings that pass for 'killer' interfaces), it diligently dispenses with the totally inessential cosmeticisms. It had to be architectural-neutral after all and the people who design the architecture make sure theirs is entirely unique, like everyone else. Take in way of a (bad) example, UNIX uses XWindows for the (rather overabused) GUI. The way in which a button with an image on it will be displayed in XWindows might not really jibe with the way Windows 95 displays it. Different OS, different functionalities. Translated, that means that Javamakers had to take care to be in the right ballpark when it came to platform-independence. A Mac is not really the smartest of 'em all when it comes to concepts like multithreading, while Windows 95 sports it as one of its key features.

Let us say, for the sake of argument, Sun today shows lack of discernful thinking, does deep research in to the innards of Macintosh machines and digs out a feature that, even though peculiar to that variety of Macs, is interesting. Then they decide to incorporate a feature that will help program better on that Mac. The development of that feature or its incorporation could take eleven months, by which time that Mac becomes more than obsolete. What is the point in breaking heads on that kind of moke work? (not to mention the electricity and the pizza bills to be footed).

As another simile, let us take a Mac and Windows 95. Let Windows 95 be a black and white television while a Mac rightly being a colored one. Since the basic groundwork is accomplished, I can work on a color television, i.e., Windows 95. For making use of the color TV, the Mac, I will have to add a few auxiliary features. That is the very essence of the huff-up about Java not being supported by the beautiful Macs, as of now. Have you tried the Roaster , though?

From a fairly prudent perspective, our environment goes a long way in conditioning the way we live our lives. For what ulterior motive would one bother a to give a guest a glass of water other than it is simply a part of the generic courtesies that one has been brought up to live with? It is the place where we work and the place where we breathe that tempers us. But again, different people live in different environments - the way you live might be very different from the way I do. If I intend today to make friends with just about anyone, regardless of the way he has been brought up, there are two ways I can do it. Either I can be efficient enough to adapt myself to him impromptu, or keep myself at a low intellectual so I can get along with everyone.

Drawing the analogy, the different people are the diverse Operating systems. The person trying to make friends with all and sundry is Java. In the light of the conflicts of various platforms, Java is concocted at a minimal, lowest-common-denominator level. Therefore, it was only a fair idea that features like bitmapped buttons, which are handled differently in different systems, be scrapped or adjusted in a way cognizible by any system. Therefore it has an array of functionalities that are broadly supported by any platform. The basic scaffold is ready, the groundwork is done. It is the building that has to be erected.

Java - The Rhino-skin

Spying on a neighbor on the web might be a mass-participation sport, and the most widely-acclaimed timepass, but unfortunately Java does not seem to like it (yawn!). Might sound like fresh pugcrap, but Java has punctilious security features. While Java and C/C++ spring up suspicions of illegal liaisons and isomorphism, Java is a little sharper when it comes to safety. C and C++ sport a discreet access to naked memory (through pointers, forthe people in the know) and leave leeway for viruses to germinate. Java, on the other hand, is not only virus-resistant, it is entirely tamper proof.

A Java applet that comes on to your machine cannot turn into a virus because it can not write to your disk in the first place. The class file or the object file that is generated during compilation has its hurdles to cross. There are staunch rules about the things that an applet is permitted to do or otherwise. As a second check, there is browser verification. When some data is to be transferred, something called an RSA signature is slapped along with it and passed along. Along the teleroute, nobody can tamper with even one byte for this data is checked for its RSA signature by the browser. Which weeds out any unwanted guests along the way.

The question of viruses is a significant one but it is small against that of tampering. Java gives the solidarity of the data not being allowed to fall into the wrong hands, and if it does and Mr. Wrong Hands does something with it, Java makes sure the subverse form does not screw up my hard disk.

 The only tangible drawback in such secure systems is that there will be a lot of hackers out there who will now feel challenged to burn the midnight halogen (midnight oil went out with the Gulf war) and try to crack the security wall offered by Java. If there was no security, everyone would feel a little too trite to create viruses thinking that the whole world must be working on one. And that in its own weird way, would ensure security. Well, to each his own.

 

Java - The Paradigm Wringer

 * The computer gets hollowed out

 "Its not the network in our lives, its the life in our networks"

 His Majesty of the desktop empire, Microsoft, has had his tenure. The elusive throne now belongs to networking, where the software from the computer ebbing away ever so swiftly. We have had enough of MS Bloatwares which used to give us 3 trillion and 56 functions, the ones never being used in the whole life of the software being 3 trillion and 49. Before you could invent a use for a great dormant feature in the package, the next version would peek in through the back door. And of course, you were human. You would swoon, drool and slurp. Finally falling for the latest version which offered an equally, infact, a dozen more useless functions. Notwithstanding an arm and a leg you had to pay for it. So when Nicholas Negroponte weighs in on the subject of MS's software archetypes "Every time Andy Grove (Intel) makes a faster chip, Bill uses all of it", we know he speaks from experience-accrued wisdom.

Great thing, Java, to come along and reverse all that. Its prowess lies in the idea of not having any software on your machine. The marrow is on some other computer in the world (popularly labeled in the digital jargon as a "server"), you just have to log on to that machine and download the software, use it and bid adieu. That portents that a normal PC that we use will be a dumb terminal soon, with little or no intelligence to call its own.

 The entire structure of software programming will be like cheesecakes. You get the program in small bits, but each one worth it.

 An applet is a test-tube application, a miniature program. It can be transferred over the Internet just about as comfortably as text files are lugged around today. An applet is included in an HTML page, which is nothing more than an ordinary text file with a few flaky tags. For instance, the tag <b> tells my browser that a word following it has to be displayed in Bold, <img> tag forewarns that an image is on its way etc. But as of now, all these pages have been deadpan, static. Java allows you to incorporate real time interactive audio-video content, animation and instantaneous updation in these Web pages. Imagine : instead of just getting soaked on the press release of Madonna's latest pop dish-out, you could actually see her (agape) in the egendary conical gear or in some altogether revolutionary wonderbra, gyrating to the latest scores. You could get smart updates on the stock market fiascoes. Or have your company's logo animated on the page! As an institutionalized commitment to shuffling the foundations of the Web, Java also aspires to add a few muchneeded shreds of ivacity to the rather addled pages.

Instead of now having to use a whole Word 6 which brags a thousand ways to do the same thing, I can now call a small applet on my machine which performs a categorically specific task, use it, save my work and off goes the applet. Cynics might be yanked out of stupor and question the utilitarian aspects of an applet. But very much on the lines of the runt of the litter being the sturdiest, an applet is also an extremely thing.

No more Vanilla, its the cassatta world...

The programs that you have designed till now compile and execute on the same machine. If you are using C/C++, for example, you compile the program and view the output on your machine. With Java, the program could be compiled on a machine and then transferred. It would be executed accordingly.

The goal of computer science today is to build something that lasts at least until it is built. No sooner do you get acclimatized to a particular software, than the next version of it comes out. A case in point : the whopping CD-ROM encyclopedias. There is a quasi-trend among the knowledge-freaks to discard the old CDs every two years or so to replace it with the latest to acquire the latest fact caboodle. Wise up man, there are some things that are irrevocable - things that even time cannot change. If JFK was murdered with a bullet, he can't be dead two years later by drowning in chicken soup. If edelweiss is the wild flower that grows in the Alps, it will always be a fact. If human heart has a particular pattern of blood-flow, a new CD can not afford to dismantle it and whiff up a new fangled cardiovascular theory. Despite their inability to alter even an iota of the facts that were already present and their only scoring point over the previous ones being, say, a 2% addition of information, the CDs sell like hotcakes. And trust me, cakes were never so cruel to the pocket. The price that you pay for a minuscule addition to the databank is another CD altogether.

Take Windows 95. Tongue-in-cheek retributions aside, the software has millions of users today. If its creative owner suddenly gets a couple of ideas that he staunchly believes will make the software far better, there's no earthly way, or at least no practically earthly way in which he can do it (unless those teeming millions are willing to shell out for a couple of changes. )

With a concept like Java, that's a cinch. All the 2% ornamentations to the CD-ROMs or the couple to Windows 95 today can be done on a machine lurking anywhere in the world and on the web, with interested third parties downloading it any time of the day and getting the freshest copy. That is not to say that Gates is going to do that with Windows 95. We are talking here of Java applets (and applications) that will be placed on a server. Their writer can make changes any time as many times. The next time you and me download that applet, we automatically get the latest version. So no more version headaches, no more pocket explosion syndromes (that's good news for the tightwads) and no more tiffs with your software vendor for giving you that last version...And to think that you need no more rely on the 9 o'clock news for knowing what's up with uncle Sam or what's down with the rest of the world...its right there, you plain need to find out for yourself.

Isn't that a far better alternative ?

Java - A Writer's Dough Earner

And then there is the din about some Java virtual machine, bytecodes and Pcodes, Java computer within a computer. For all practical purposes, a Java virtual machine is also virtual talk (or as an open Yankee would put it : it sucks). For there is heap lot of sleuthing to be done in case you crave to discover the reality behind those ostentatious words. From a fairly practical perspective, the Virtual machine is the various tamper-proof, verification procedures put together that make sure Java functions more than a little isolated from your ordinary procedures.

Talking about codes, well they have been an amusing source of interesting discussions spanning almost any self-respecting Java mailing list. What the hell is a bytecode, anyway. When a Java program file that ends in an extension of .Java is compiled, a .class file is formed. When the same class file is put on your hard disk, however, it is against digital religion to retain their name as class files. Accordingly, they are called Pcodes. But that's the saga when it is there on your own machine. The moment it is expected to be trolling over cables, it is fittingly christened as Bytecodes, since it is bytes that are on a tour.

A friendly advice here (and also the moral of the story) : don't read in on the cryptic combo of technical jargon. If anything, it is the skullduggery on the part of the cyber vendors, in a drive to make the innocent programmers lose some of their frisson. Or in a more politically correct way to put it, maybe it was yet another creative brain at work – intending little more than trying to earn his daily dough.

Java - A Revenge of the Nerds?

Widely felt but vaguely understood, Java's semblance to a mass revenge of the nerds is unmistakable. It is better than a slightly more eligible successor to HTML which was so easy to use that one could sit over the weekend, yes even that motor-mouth female across the road, with enough beer and pudding stashed away in the refrigerator. Java, on the other hand, is not every hairbrain's eggnog. It takes a little more than just good intentions to marshal yourself the Java way. To achieve the kind of fireworks expected from it, a reasonably good grip over C/C++ and a bundle of creative gray cells is indispensable.

Here's the latest fear : Is the right to freedom of (drab) expression that HTML blared being snatched away from the ordinary Johnny and Jennifer? And here's the latest counter-fear : Well, if the Johnny and gang are not determined-enough, then yes.

In that light, one is given to the belief that Java portends a style-and-content inequality when it comes to designing smart web sites. While the big-wigs can afford to throw in a fair share of resources and dish out an ultra-slick site, the folks with a perennial cash-crunch could be left out quivering in the cold. That's not really true for the most part because Java, at least as of now, is freeware and any mortal soul with the drive has a free reign to implement it.

 

 

 

Java - The Cyber Plateau

Did you ever stop to think that you live where you live and not in the lush havens of Beverly Hills or the posh seaface condos in Miami? Its no time to begin if you haven't, though. But Java, only abetted by the sprawling Internet is a great field-leveller. As yet. It is available for free download at Java's page and that goes a long way in plateauing the socio-economic-strata bar graphs. A poor-yet-driven programmer can now safely wriggle out of monetary conundrums because he no longer needs to cry

the Mississippi at lack of the right software. It is equally accessible to every one. Even a guy deep down from the backwoods of Morocco could be the next whiz on the Internet.

In way of a good example, take us. A month back in time, we were official neophytes when it came to Java programming. Today, a score of full-blown half-baked truths and a dozen Nescafe jars later, we have one of the largest and most frequently visited tutorials in the world (or we so love to believe, with good reason.) We even succeeded in enamoring a friend so spankingly, he put a Spanish version of our tutorial on the web. If that is any indication, we have got the welcome mat out there. That's pretty healthy as an enlightenment.

Not to forget the fundamental discovery that designing an applet is about as easy and as much fun as fantasizing being kidnapped at gun-point by a ravishing cyberchick. Given enough incentive and amphetamines, any Tom-Dick-or-Harry and his toothless buddy can hope to take on the digital world. Isn't that what the essence of Internet is all about ?

Java - The alternatives

If your are an ornery critic and analyst, you have probably already trailed down the alternatives to Java, if there are any, that is. Honestly, if you prefer peanuts to pizza, its okay to look for the alternatives. Otherwise, however, it is just about as availing as watching paint dry. There is a flock of some languages that pride themselves over their internet-orientedness, but they have their fair share of handicaps. Perl , LISP and Telegraphic from General Magic are the fairly well-known (if that word conveys the meaning) among the developer circles. Something called Blackbird was flashed out by Microsoft, but it does not seem to be bright enough to arouse much interest. Tickle , in a similar vein, besides being a newbie's nightmare is closer to a huge digital yawn. And the rest are better if not disclosed. Could one say ignorance is bliss?

Java - A coffer factory for Sun and gang

 

Whatever one decides to perceive Java as, the fact remains that it has raked in, directly or indirectly, a neat bunch of green backs and had their coffers grinning. Sun stands tall in Wall street. And much to the disdain of counter-parts on the prowl, it has already pigeonholed the company as an Internet company.

Java - The Noose for Microsoft?

Microsoft is not dead, it is just in suspended animation. They might have been caught with their pants down, but let us be fair to them. There's no fool like an old fool - you can't beat experience. But there is always a lesson to be shopped. Microsoft is feeling left out because it arrived late at the Internet bang. Gates can wax nostalgic for the times when all the other party-poopers would get up and offer a seat, but this time the party is different. No one rules the cyberdom; no one molds the Internet like measly desktop world, which is growingly becoming an emigrating empire world, which is growingly becoming an emigrating empire.

Java - America's slap-down suicide note

That's admittedly a rather skew-whiff way to put it. Yet, it is the undeniable truism and more an issue of perspective. Regardless of whether the classic tumbler is half-empty, half-full or just twice as large as it need be, technologies like Java are America's axe-in-the-foot. Java is simple and it is accessible. If anybody can write those teeny-weeny applets, we might as well have our next Bill Gates or Andy Grove from the Kalahari or the rifts of Congo. And that forebodes a danger to the superpower status that America has relished for a long while. But then again, they say Internet was a mistake in the first place...

Java - A flaw no one told you about

This is classified information. Since we are all for Java, it is difficult to disclose a flaw without alienating the folks at Sun. But between you and me, Java is so engrossing, it doesn't leave you with time for a haircut -- and that can produce spectacularly unfortunate effects if your boss was in the army.

Java - The Last clouds in the coffee

If the skeptical shenanigans are to be believed, Java might not be the perfect answer (as of now), but it raises some pretty interesting questions. For one, Windows 95 that we are working just about bears up with 8 MB and really likes 16. If you and me could have Java in our toasters, would our toasters have to flaunt a 16 MB RAM ? Here's a reflective thought : Maybe that appears to be a big chunk of memory today but might be an ordinary plaything tomorrow. Not very long ago, 16 K was a big amount. Infact, a few years back, if a guy was willing to shell out 32 K of memory, I would not think twice to marry his daughter. And, if a guy basks in that measly amount as of today, I wouldn't be a fool to believe that he has been hatching eggs for 20 years...

All said and done, there is little sense in mulling over the yesterdays, tomorrows and todays (which incidentally, are the yesterdays that you will worry about tomorrow). Java is here and is here for keeps. Our human minds have a mysterious tenet of never regaining their original dimensions once they have been stretched by a new idea. That seems rather grimly true in the case of Internet. What triggered out as a small experimental convenience is now the order of the day. Java might be a little overpampered kitten as of now, but the fullblown panther is yet to come.The last word is saved for grandma of course, whose vast skeins of computer knowledge end at the gadget's number-crunching capabilities :

"I never knew so much could be said about coffee."

Was Albert Einstein serious when he said that you don't know a technology well enough until you can explain it to your grandma...?

With inputs from Shashank Tripathi and Sonal Kotecha

 

HOW TO TEACH JAVA

 

All around us, people have been rather raring to pick up their foghorns and start tooting about this great new product called Java. In fact, if one were to catalog the number of tie-ups that have ensued its release, you should not be surprised if the paper spans from here to the bright, ol' moon. Go Java-hunting in Cyberspace and you will hit hundreds of sites that have Java splashed across their expanse, maybe some even sport the most fertile imagination when it comes to writing code. But honestly, very few can yet boast decently understandable code or any other work, still fewer that tell a person how to learn Java in the best possible way and perhaps none really sheds any light on the aspect of how best to teach Java.

For instance, no one is bothered about the poor MIS guy who is all confused how to go about executing his plans of introducing a Java turnabout in his company. Just about how much Java does he need to know to make sure the team of 200 computer programmers under him is doing the right job? No body cares a whoop about the guy who runs the Computer Training Institute down the road and wishes to start teaching Java but does not know exactly how to go about it, especially if ardent people come to him with no former knowledge of C/C++.

Target Audience

When we talk of Java, we talk of something ubiquitous. It will be lack of discernment to have something to do with Java and not target the whole world. So, while just about any one of you is welcome to send in his/her contributions regarding personal Java experiences, the kind of people we have in mind as we organize this CyberConference are :

institutions,

company like Levers who has a large in-house project on Java or, say, Microsoft who wants to develop in-house Java talent

These people, in their own distinct ways, need to be clear on how Java has to be so they can chase their respective ideas to the hilt. Luckily, we have an active support of Sun Microsystems , India and Videsh Sanchar Nigam Limited (VSNL) , the only Internet Access Providers in India.

Perspectives

It is just fair here to offer a few insights into Java that our grappling with it have unraveled. While these might not be universally agreeable as the final word on teaching Java, we furnish a sample of the questions that make a marked difference when it comes to training at a professional level...

Who must be taught Java ?

Java has to be one's third language, not the first. If a person has no former command over C/C++, he probably might not be a suitable candidate. It is not really a nightmare to write a working applet. Infact we have had a Russian housewife telling us that after she read our tutorial, she wrote her first Java applet. That might be very touching as a compliment, but then being creative and productive with the language takes a firm grasp over the fundamentals.

For instance, if a person does not understand the way in which classes and interfaces work, it is difficult to understand how Java works. There are some things that are better learnt in C++, e.g. the this pointer can be understood in C++ because it has pointers. Unless one is conversant with programming under windows how ishe/she going to understand events? So the questions that arise are ...

What is that back ground?

What must be the steps in learning Java ?

When you are learning something, the learning and the teaching process travel in pairs. What is the most fitting way to initiate a person into the Java environment. For instance, does it suffice to cram the person's head with all the best properties of Java in the same definition (as the definition of Java at the Sun site so immaculately does).

 

What must be taught?

 

What matters ?

How many types of Java training ?

It might not be common knowledge but atleast a dozen companies in India are providing rigorous training to theirstaff for developing in-house talent in Java.

More surely than not, many people will be using the language for enhancing and enriching the existing content on their web pages at one level. A very handy example is the simplistic animation mechanisms that Java offers ifyou are willing to have the images ready. But that throws up a whole new set of questions:

series of 10 small applets that showcase the caliber of Java from its most rudimentary feature to the most intricate one.

A little end note

When you are teaching Java, it is also important to tell the people where it fits in the entire scheme of things. For example, is all the hub-bub about Java residing inside Internet toasters just a publicity stunt or is it for real? What will be the evolution of Java, say, 5 years from now.

It is not even a year old now and still people love to refer to it as "The Microsoft killer". Well the question whether a year old sibling commit murder might be a good topic for an Oxford rebuttal contest, we are concerned with the ready-made explanation it offers for our conference dates from 29 to 31 May -- Java will officially be one year old on May 22, 1996.

Maybe Gates retorts with yet another powerful technology by then. One fact that everyone is willing to overlook is that Billy did not become the kind of enviable billionaire he is by playing second fiddle. If the whiff of coffee can take the world by a storm, he might come up with a still stronger condiment. To believe the interest generated by Visual Basic script, well, it is the next weapon in Microsoft's armory. If it indeed is, we must be most willing to give it a shot. Finally, it is the technology that matters, not who brought it in.

But the one thing that stands clear through all this is : With Internet and Java, technology is no more the call-girl of America or Japan or Germany, it is now an international realm. And that's the reason we wish to have the people of the whole world meet at one place, whether physically or otherwise, and discuss how the technology can be offered to the people on a global platter.

Vijay Mukhi.

A Tweak of Lemon...

 Blowing away the clouds in the coffee..Brewing the first Applet

"Ours is the age of substitutes; instead of principles, we have slogans; instead of genuineideas, bright ideas; instead of languages, jargon. "

 

When it comes to bright jargon, Sun Microsystems has left no stone unturned. And the creative terminology goes a long way (if not all the way) in making it like the tidal wave it has been. Java programs are called 'Applets'. In the directory in which the whole downloaded software of Java is saved, there is a subdirectory called Bin. This is where we have the Java compiler called 'Javac.exe'. The first thing we do is to create a subdiretory under the root called, say, "xxx". Then set the path to \java\bin. We are going to write our Applets here. Each applet or program has to be written in a file with the extension of .Java. In keeping with the ritual, let us consider this one-liner code first...

a1.java

class zzz
{
}

You'll agree that even an ice-hockey player or a visitor to Disneyland will love this sort of a program because it is looks manageably concise and absolutely simple. Well, we do not expect fireworks with that sort of a code, but let us compile it all the same. Save the file a1.java. It is noteworthy to mention here that like C/C++, Java is case-sensitive too (and preposterously so!). Type the command javac a1.java. The compiler gives no errors. If you key in the DIR command now, you will see that after successful compilation, a file called zzz.class is made automatically. That is because we specified zzz as the name of our class. This makes it adequately clear that the name of the applet file (the .java file) and the class can very well be different.

Now comes the question of viewing how our applet works. If it is a Java applet, you can call it only from an HTML file (An HTML file, in case you don't know, is nothing but a text file with tags that link it to other documents). Since all the documents on the Internet use this format, an applet has to be specified in an HTML file. Consider the following HTML file.

aa.html

<applet code = "zzz" width =120 height =120>
</applet>

As is evident, the .class file (zzz.class in our case) that is formed after successful compilation of the .java file (a1.java) is specified in the HTML. The width and the heigth This is the way in which you can incorporate an applet in the HTML format. The applet could be a program to display animation or perform any other dynamic task and thus, enliven a page on the net.

But it still remains to be seen how the applet works or what the output looks like. Towards this end, we have a program called the appletviewer (in the same directory as javac). This is a program that allows you to view how your applet works. Hence, we key in the command appletviewer aa.html. Sorry folks, but there is no output (if your stars are not happy with you, your machine might even hang!).

There are a hundred and sixty five things to be done in the background before our class begins work (like the initialization routines et al). Our class does not have any property towards that end.

As one does not know what routines are to be initialized internally, the safest thing to do is to derive a class from another class provided with the language. Now edit your a1.java file in the following way.

class zzz extends Applet
{
}

Applet is a class that has all the required functions necessary for this purpose, so we derive zzz from Applet or extend zzz to Applet. This means, in plain English, that we can now use all the functions and variables of the Applet class and also add our own ones. The only hitch now is that compiler refuses to recognize Applet, unless we mention specifically the name of the class library in which it is contained. So we now have to formally introduce the compiler to the Applet class. We do this by inviting the Applet class into our program (how else?). Only, the invitation here is in the form of importing a file called Applet.class from the classes\ java\Applet subdirectory.

import java.applet.*
class zzz extends Applet
{
}

When we compile this program, however, we get some lines of dreadful errors, with only one making any sort of horse-sense, " ; expected". Guess what, we missed out on the elusive semicolon after the import statement! Remember, this is a sibling of C and C++ and the use of semicolon is inevitable. And hence, our program now looks like this...

import java.applet.*;
class zzz extends Applet
{
}

However, having put that necessary punctuation, when we compile and run the program again, it gives the error that the 'class not public'. As a result, the applet is not initialized. That brings us to another important feature of the Java, as it stands today. All the classes that we define have to be public, otherwise the class cannot be initialised by the Appletviewer. Not being the arguing types, we make our class public in the following way...

import java.applet.*;
public class zzz extends Applet
{
}

One snag with making a class public is that the name of your file and that of the class have to be the same. So after adding the word public, rename a1.java to zzz.java. Before you begin to swear about this queue of unending snags, let us state that this is it. We finally have what can be safely labeled as the smallest Java program. Now when we key in the command appletviewer aa.html, a small window appears to show the output. This is the first successful applet and all the economists out there would love it. Because it is concise, precise and absolutely useless ( :-) ). As we are not economists and expect our applet to do something, let us make some additions. But to continue further, we have to quit from the appletviewer. For this, click on the Applet menu that you see in the appletviewer window and select Quit.

import java.applet.*;
public class zzz extends Applet
{ public void init()
{ resize(300, 500);
}
}

All the functions in our class have to be public. The function init() gets called initially when you run an applet. Whenever your applet begins and you need to do something put it in the init(). Inside this, we have the resize() which is one of the many functions of the Applet class. It is used to change the size of the area in which our applet can work. By default, a small area is given to the applet but the resize() says "Give me two parameters, the width and the height and I can increase or decrease the scope of your applet". We obediently pass two parameters to this function, the width of the area(300) and the height(500). When we compile and run the above program, we can see a rectangular box as an output. As yet, we have just plain specified the area for the applet, now let us try displaying something inside it...

import java.applet.*;
import java.awt.* ;
public class zzz extends Applet
{ public void init()
{ resize(300, 500);
}
public void paint(Graphics g)
{ g.drawString("Hello", 10, 50);
}
}

As you must have realized, this program displays "Hello" at the coordinates 10, 50. As mentioned earlier, the init () gets called first. The workarea is resized in the same way as before. Everytime the screen or the window has to be displayed, the paint() gets called. You cannot set your watch by it. An object g that looks like the class Graphics has to be tagged along as a parameter. As Graphics is a predefined class, we require to import the Graphics class, (which is in the java\awt\Graphics subdirectory). The Graphics class has many functions including the drawString(). Give this function its due in the form of three parameters, the string to be displayed, and the x and the y coordinates and promises to display the string at that position. So when the paint is called, "Hello" appears on the screen.

Now that we are aware of the method of displaying, let us write a program that is a little more interesting. We propose to display a string and a value everytime the Mouse is clicked. Key in the following code...

import java.applet.*;
import java.awt.*;
public class zzz extends Applet
{ int i;
public void init()
{ resize(300, 500);
}
public void paint(Graphics g)
{ g.drawString("i....." + i, 10, 50);
}
public boolean mouseUp(Event e, int x, int y)
{ i++;
repaint();
return true;
} 
}

Let us start from the very beginning. A variable i is defined before any other function. This make sure that the variable can be used in any function (for you C++ programmers out there, it is similar to a public variable). A very interesting feature is the mouseUp(). Every time you click with the mouse, the mouseUp() gets called. The mouseUp() is counted upon to return a True or false. And that is the reason why that ugly word 'Boolean' comes into picture (which will be explained at a later stage).Note that the mouseUp() accepts three parameters. The Event is irrelevant to explain at this point of time and it will be explained later with an useful example. The other parameters are x and y coordinates, which are internally calculated everytime the mouse is clicked. That is, if i click at, say, the position (15, 20), then the value of x will automatically become 15 and that of y will be 20. With every click the value of i is increased by 1. Then the repaint() is called, which in turn calls the paint(). This way, with each click we display the string "i...." followed by the value of i. The drawString() takes care of that. Note the plus sign (+), it is used to concatenate or join two strings to be displayed.

They said programming in Java is object-oriented and event-driven. That sent my brains for a toss when I first heard it, but the above program bears a glittering testimony to that. The function mouseUp() gets activated everytime the mouse button is clicked, the paint() is called whenever a window or a screen has to be redrawn etc.

Let us alter this code to display our usual "Hello", but now at the coordinates where the user clicks. Change the code in zzz.java as the following..

import java.applet.*;
import java.awt.* ;
public class zzz extends Applet
{ int a; int b;
public void init()
{ resize(300, 500);
}
public void paint(Graphics g)
{ g.drawString("Hello", a, b);
}
public boolean mouseUp(Event evt, int x, int y) 
{ a=x; b=y;
repaint();
return true;
}
}

Here, a and b are public variables as they are defined outside all the functions. When a variable is public, it can be used inside any function. The logic to the above applet is pretty simple. Everytime the mouse is clicked, the mouseUp() function is called. We can get to know the coordinates where the user has clicked because the coordinates are stored automatically in x and y. These values are assigned to a and b. Now when the repaint() is called, it calls the paint(). Here, the drawString() will display "Hello" at the specified position. But since the specified coordinates are nothing but the coordinates of the place where the user has clicked (a and b), "Hello" will now be displayed at the position where the user clicks.

Our next program draws a line between two clicks of the mouse. That is, a line is drawn between the first and the second click, the third and the fourth click and so on.

import java.applet.*;
import java.awt.* ;
public class zzz extends Applet
{ int a; int b; int c; int d; int e;
 
public void init()
{ resize(300, 500);
}
public void paint(Graphics g)
{ g.drawLine(a, b, d, e);
}
public boolean mouseUp(Event evt, int x, int y) 
{ if (c==0)
{
a=x;
b=y;
c=1; 
}
else
{
d=x;
e=y;
c=0;
repaint();
}
return true;
}
}

We define five public variables a, b, c, d and e. Then the paint() is called by default for the first time.It is passed four parameters, the x and y coordinates of the points between which the line has to be drawn, i.e. the two endpoints of the line. But since the four variables a, b, d and e are currently zero,there is no line displayed. Whenever the user clicks with the mouse, mouseUp() functions gets called. A variable c takes care of the fact whether the click is for the first or the second time. If the click is for the first time (i.e if c is 0), a and b are given the value of x and y. These are the points of the first end of the line. Then c is made 1. The second time the user clicks, c is 1. Therefore, d and e given the values of x and y. c is made 0 again. And the repaint() is called. Now when the paint() is called by the repaint(), the drawLine() will draw a line from (a, b) - the position of the first click, to (c, d) - the position of the second click. In this way, the value of c can be alternated and a line drawn between two successive clicks.

 

Making the clouds look good - Images

 

Let us face it, drawing a line is too dry a thing to do; so let us move on to displaying an image on the screen. And to write an applet that displays an image is simpler than you ever feared. Consider this code...

import java.applet.*;
import java.awt.*;
 
public class zzz extends Applet
{ Image n;
public void init()
{ n = getImage(getCodeBase(), "not.gif");
resize(300, 500);
}
public void paint(Graphics g)
{ g.drawImage(n, 10, 15, this);
}
}

As is amply apparent, the basic structure of the program remains the same. An object n that looks like the class Image is defined. Inside the init(), n is initialised to an image called "not.gif" which exists on our hard disk. (PS Check up the \demo\images directory for more .gif files which are nothing but images). This is done with the getImage() that is a member of the Applet class. As n looks like the class Image, it can use the member functions of that class. The getImage() accepts two parameters, the

getCodeBase() and the name of the .gif file. Now, n contains the image "not.gif". So when the paint() is called using g (which looks like Graphics), we can use n to display the image. The Graphics class has a member function called drawImage(), which is used to actually draw the image (n) on to the screen. This takes four parameters. First is the image that we wish to draw, as is n in our case. The second and the third are the coordinates where we want the image to be displayed. The fourth parameter is this. If you are a C/C++ programmer, you are well-versed with this, but for the rest it should suffice right now to say that this refers to the current object ( pun unintended :-) ).

Now, the same image can be displayed at the coordinates where the user clicks by using the mouseUp() and trapping the coordinates where the mouse was clicked. If you have not got it already, the code for this will be..

import java.applet.*;
import java.awt.* ;
 
public class zzz extends Applet
{ Image n;
int a; int b;
 
public void init()
{ n = getImage(getCodeBase(), "not.gif");
resize(300, 500);
}
public void paint(Graphics g)
{ g.drawImage(n, a, b, this); 
}
public boolean mouseUp(Event e, int x, int y)
{ a=x;
b=y;
repaint();
return true;
}
}

Before we weave...

Hang on folks, here we have the programs dished out; the explanation will soon follow. Or for the people in the know, This page is under construction . A brief, clunky note about the programs is made to pass for an explanation, but we will be here soon (and hope you will be too!) with more explanatory stuff. As regards now, the programs will probably speak for themselves. :) Thanks for stopping by. See you soon. So long.

It is a poorly-kept secret how programmers quail at embarking on learning a new concept. When they begin, they look like they were waiting for the dentist's drill and by the time they wind up, they give the impression they just got trampled in a thousand-cow stampede! The concept of threads, though relatively fresh, is by no means one of these gut-wrenching features of Java. We will address threads very soon, but let us first consider the following code..

import java.applet.*;
import java.awt.*;
public class zzz extends Applet
{
Image m[];
int i=0;
int a=0, b=0;
int j = 1;
public void init()
{
m = new Image[17];
for (i = 0; i<17; i++)
{
m[i] = getImage(getCodeBase(), "T"+j+".gif");
j++;
}
i=0;
}
public void paint(Graphics g)
{
g.drawImage(m[i], a, b, this); 
}
public boolean mouseUp(Event e, int x, int y)
{
repaint();
i++;
if (i == 17)
i = 0;
a = x;
b = y;
return true;
}
}

From the subdirectory demo/TumblingDuke, we picked up the seventeen *.gif files and this is the way you can animate them.The above code is to display an image out of the 17 every time you click. As seen in the last chapter , an image was displayed wherever you clicked. Here the concept is very much the same, only everytime a new image is displayed. From an array of images, each image is picked up individually. After the 17th image is displayed, the counter is set to 0 again. To acquaint you with these pictures well enough, so that you can percieve the roots of animation clearly, we will now display 15 images at different coordinates.

import java.applet.*;
import java.awt.*;
 
public class zzz extends Applet
{
Image m[];
int i, j = 1;
public void init()
{
resize(600, 400);
m = new Image[17];
for (i = 0; i<17; i++)
{
m[i] = getImage(getCodeBase(), "T"+j+".gif");
j++;
}
}
 
public void paint(Graphics g)
{
g.drawImage(m[0], 5, 10, this);
g.drawImage(m[1], 120, 10, this);
g.drawImage(m[2], 240, 10, this);
g.drawImage(m[3], 360, 10, this);
g.drawImage(m[5], 480, 10, this);
 
g.drawImage(m[6], 5, 100, this);
g.drawImage(m[7], 120, 100, this);
g.drawImage(m[8], 240, 100, this);
g.drawImage(m[9], 360, 100, this);
g.drawImage(m[10], 480, 100, this);
 
g.drawImage(m[11], 5, 190, this);
g.drawImage(m[12], 120, 190, this);
g.drawImage(m[13], 240, 190, this);
g.drawImage(m[14], 360, 190, this);
g.drawImage(m[15], 480, 190, this);
}
}

Now we will display the above-seen images at the same coordinates to get the effect of animation.

import java.applet.*;
import java.awt.*;
 
public class zzz extends Applet
{
Image m[];
int i;
int j = 1;
public void init()
{
m = new Image[17];
for (i = 0; i<17; i++)
{
m[i] = getImage(getCodeBase(), "T"+j+".gif");
j++;
}
i = 0;
}
 
public void paint(Graphics g)
{
g.drawImage(m[i], 50, 100, this); 
}
public boolean mouseUp(Event e, int x, int y)
{
repaint();
i++;
if (i == 17)
i = 0;
return true;
}
}

The next program demonstrates what necessiates the concept of threads.

import java.applet.*;
import java.awt.*;
 
public class zzz extends Applet
{
int i=0;
public boolean mouseUp(Event e, int x, int y)
{
for(int k=0;k<10000;k++)
{
i++;
showStatus("i..."+i);
repaint();
}
return true;
}
public void paint(Graphics g)
{
g.drawString("i..."+i, 50, 100);
}
}

When you run the above program, a click of mouse will take us into the loop of 10000. showStatus() does the work of displaying whatever is passed to it as a parameter.Therefore, the value of i will continuously be incremented and shown as the status. Now, consider the following code...

import java.applet.*;
import java.awt.*;
public class zzz extends Applet
{
int i=0;
Button b;
public void init()
{
b=new Button("hell");
add(b);
}
public boolean mouseUp(Event e, int x, int y)
{
for(int k=0;k<1000;k++)
{
i++;
showStatus("i..."+i);
repaint();
}
return true;
}
public boolean action (Event e, Object o)
{
if("hell".equals(o))
showStatus("button clicked");
return true;
}
public void paint(Graphics g)
{
 
g.drawString("i..."+i, 50, 100);
}
}

Don't despair, the Button is introduced here, only to show that until the loop of incrementing i does not get accomplished, you are hapless with the Button. As for now, rack your brains and run the program, we will soon be back with an elaborate explanation.

Hemming Our Way

Hang on folks, here we have the programs dished out; the explanation will soon follow. Or for the people in the know, This page is under construction . A brief, clunky note about the programs is made to pass for an explanation, but we will be here soon (and hope you will be too!) with more explanatory stuff. As regards now, the programs will probably speak for themselves. :) Thanks for stopping by. See you soon. So long.

Consider this code...

1

zzz.java

import java.applet.*;
public class zzz extends Applet implements Runnable
{
}

That is not really the kind of code you can tear from limb to limb, but let us have a go. When we compile this code, an error called "class zzz must be declared abstract" pops up. This is because whenever we need a thread, we have to use implements Runnable. But a run() is also required.

2

import java.applet.*;
public class zzz extends Applet implements Runnable
{
public void run()
{
showStatus("In Run");
}
}

The run() is specified here. The showStatus() does the work of showing whatever you pass as a parameter in statusbar of your window. Here when we execute, we only get the message "Applet started". The run() does not get called as yet. Now, ladies and gentlemen, we come to the concept of threads. To set the ball rolling (or more specifically, the run()), we need to have a thread. Because the Runnable ...runtime... So here we go.

3

import java.applet.*;
public class zzz extends Applet implements Runnable
{
Thread t;
public void init()
{
t = new Thread();
}
public void run()
{
showStatus("In Run");
}
}

Unless you've not been sleeping lately, you must have realised that we define an object t that looks like a Thread. In the init() we initialise the thread. After all this effort, the thread still does not start to weave! Well, we forgot to assossiate the thread with the run(). For doing this, we have a function called start() in the Thread class. Since t, our thread looks like Thread, we can use the start() by keying it in as t.start(). So here we go...

4

import java.applet.*;
public class zzz extends Applet implements Runnable
{
Thread t;
public void init()
{
t = new Thread();
t.start();
}
public void run()
{
showStatus("In Run");
}
}

5

import java.applet.*;
public class extends Applet
{
Thread t;
public void init()
{
t = new Thread(this);
t.start();
}
public void run()
{
showStatus("In Run");
}
}

 

There, we finally have our first thread running and kicking. When we run the above program, we see "In Run" displayed at the bottom of our window. And like it or not, that is where the status is shown by default. Now that we can rest assured our thread works, let us make it do something for us. Retain the above code. In the run(), add the following lines..

i++;
repaint();

Now that we are calling the repaint(), we also have to have a paint(). So we include it

as follows..

public void paint(Graphics g)
{
g.drawString("i..." + i, 10, 20); 
}

Now that we are using Graphics, we have to import java.awt.* . When you compile and run the program now, the output is sadly simplistic. The status, as before, drawls "In Run". At the coordinates 10, 20 we see "i...1", which is not that picturesque afterall. But wait, that explains one thing. When the run() gets called, the value of i is incremented by 1. So, i increases from 0 to 1. Now the repaint() calls the paint(). Here the drawString() puts "i...1" at 10, 20. That implies that the run() function gets called once, does its work and then the program does nothing further. To demonstrate this concept a little more clearly, let us make the run() do a little more work. Retaining the above code as it is, add the following lines to the run()...

i++; repaint();
i++; repaint();

This time, i is first displayed as 1, then 2 and then 3. This is because the repaint() is being called thrice. (In reality, though, you only see "i...3" owing to the speed of your computer).How about putting the repaint() and the incrementing of i in a while loop? Remove all the i++ and repaint()s from your run() and put the following instead...

while(true)
{
i++;
repaint();
}

As expected, this will show us the value of i being incremented non-stop. This is because of the while(true) loop. (For those who are confused about the while construct, the while loop continues till the condition (specified with it) is true. As soon as it becomes false, the loop stops. Here since we have the condition permanantly as true, it is an endless loop.)

6

import java.applet.*;
import java.awt.*;
public class zzz extends Applet implements Runnable
{
Thread t;
int i;
Button b;
public void init()
{
t = new Thread(this);
t.start();
b = new Button("hell");
add(b);
}
public void run()
{
while(true)
{
i++;
repaint();
}
}
public boolean mouseUp(Event e, int x, int y)
{
b.reshape(x,y,30,50);
return true;
}
public void paint(Graphics g)
{
g.drawString("i..."+i,10,20); 
}
}

When you execute this program, you'll see that wherever you click, the button followsit and is displayed at that coordinates. The value of i changes along with it.

7

import java.applet.*;
import java.awt.*;
public class zzz extends Applet implements Runnable
{
int i = 0, j = 1, k = 0;
Image m[];
Thread t;
Button b;
public void init()
{
m = new Image[17];
for (i=0; i < 17; i++) 
{
m[i]=getImage(getCodeBase(),"T"+j+".gif");
j++;
}
t=new Thread(this);
t.start();
b= new Button("hell");
add(b);
}
public void run()
{
while (true)
{
repaint();
k++;
if (k==17)
k=0;
}
}
public boolean mouseUp(Event e, int x, int y)
{
b.reshape(x,y,40,50);
return true;
}
public void paint(Graphics g)
{
g.drawImage(m[k],10,25,this);
}
}

This program draws the images for you with the button behaving in the same way as in the earlier program. This explains, in a simple way, the potential and the function of threads. Without a thread, we could not think of performing two tasks at the same time. For instance, if we were to display a set of images continously and at the same time try to trap the click of a mouse (with mouseUp()), there as no way we could do it. With a thread, we can have programs working independently. (A point to be ted here is that the images, or the *.gif files were put by us in the directory where we have our *.java and the *.class files). 8

import java.applet.*;
import java.awt.*;
public class zzz extends Applet implements Runnable
{
int i = 0, k = 0, j = 1;
Image m[];
Thread t;
Button a,b,c,d;
public void init()
{
m = new Image[17];
for (i=0; i<17; i++)
{
m[i]=getImage(getCodeBase(),"T"+j+".gif");
j++;
}
t=new Thread(this);
a= new Button("start");
b=new Button("stop");
c=new Button("suspend");
d=new Button("resume");
add(a);
add(b);
add(c);
add(d);
}
public void run()
{
while (true)
{
repaint();
k++;
if (k==17)
k=0;
}
}
public boolean action(Event e, Object o)
{
if("start".equals(o))
{
t.start();
return true;
}
if("stop".equals(o))
{
t.stop();
return true;
}
if("suspend".equals(o))
{
t.suspend();
return true;
}
if("resume".equals(o))
{
t.resume();
return true;
}
return false;
}
public void paint(Graphics g)
{
g.drawImage(m[k],10,25,this);
}
}

This program introduces the concept of a thread being suspended, resumed, started or stopped. A thread (or the independent program) when started, can be suspended(stopped temporarily), then resumed for as many times as required. But once stopped, it cannot be started again.

More than one thread

9

import java.applet.*;
import java.awt.*;
public class zzz extends Applet implements Runnable
{
int i = 0;
Thread a,b;
public void init()
{
a = new Thread(this);
b = new Thread(this);
a.start();
b.start();
}
public void run()
{
while(true)
{
i++;
repaint();
showStatus(a.getName());
showStatus(b.getName());
} 
}
public void paint(Graphics g)
{
g.drawString("i..."+i,10,20);
}
}
 

The above program has two threads a and b. Both of them call the same run(). To show this effect, we put showStatus() which will tell us which thread is running. Actually, since both the threads are calling the same run(), the display output will alternate between the two threads. This is because we provide getName() as the parameter. The getName() will get the name of the current thread. (That's not a joke)

10

import java.applet.*;
import java.awt.*;
public class zzz extends Applet implements Runnable
{
Thread a;
public boolean mouseUp(Event e, int x, int y)
{
a = new Thread(this);
a.start();
return true;
}
public void run()
{
while(true)
{
showStatus(a.getName());
}
}
}
 

Here everytime you click, a new thread is being created because inside the mouseUp() we initialize a thread everytime. Therefore, the showStatus now will show the name of a new thread everytime you click.

11

import java.applet.*;
import java.awt.*;
public class zzz extends Applet implements Runnable
{
Thread a;
public boolean mouseUp(Event e, int x, int y)
{
a = new Thread(this);
a.start();
return true;
}
public void run()
{
while(true)
{
showStatus(Thread.currentThread().getName()); 
}
}
}

This one is not much different from the previous one. Only this time, we get as an output the names of all the threads. Let me explain. In the earlier program, everytime you clicked a new thread was being created but since the getName() was being assossiated with that thread only (a.getName()), in the run() we could only see the name of that thread. Here again a new thread is being created, but due to the currentThread(), we get the name of all the threads, continuously.

12

import java.applet.*;
import java.awt.*;
class ttt extends Thread
{
int i;
zzz b;
public ttt(zzz a)
{
b=a;
}
public void run()
{
while(true)
{
i++ ;
b.repaint();
}
} 
}
public class zzz extends Applet 
{
ttt t;
public void init()
{
t = new ttt (this);
t.start();
}
 
public void paint(Graphics g)
{
g.drawString("i..."+t.i,10,30);
}
}
 

Instead of having all the threads use the same run(), we can derive a class from the Thread class. As seen in the above program, we have our own class ttt which looks like Thread. This class has a run() in it. Now when we define an object t that looks like ttt, we can exclusively use the run() of ttt.

13

import java.applet.*;
import java.awt.*;
class ttt extends Thread
{
int i;
zzz b;
public ttt(zzz a)
{
b=a;
i=0;
}
public void run()
{
while(true)
{
i++ ;
b.repaint();
}
}
}
class uuu extends Thread
{
int j;
zzz c;
public uuu(zzz d)
{
c=d;
j=0;
}
public void run()
{
while(true)
{
j++;
c.repaint();
}
}
}
public class zzz extends Applet 
{
ttt t;
uuu u;
public void init()
{
t = new ttt (this);
u = new uuu (this);
t.start();
u.start();
t.setPriority(Thread.MIN_PRIORITY);
u.setPriority(Thread.MAX_PRIORITY);
}
public void paint(Graphics g)
{
g.drawString("i..."+t.i,10,30);
g.drawString("j..."+u.j,10,60);
}
}

 

To make the concept of deriving from Thread a trifle clearer, we have two threads here u and t. We also introduce here the concept of priority. Yep! you can set priority for the threads. Here we give t a maximum priority and u a minimum one. Therefore the value of i, which is related to the t thread will increase at a slower rate and that of j will be faster.

14

import java.applet.*;
import java.awt.*;
class ttt extends Thread
{
int i;
zzz b;
public ttt(zzz a)
{
b=a;
i=0;
}
public void run()
{
while(true)
{
b.repaint();
i++ ;
if ( i== 17)
i=0;
}
}
}
class uuu extends Thread
{
int j;
zzz c;
public uuu(zzz d)
{
c=d;
j=0;
}
public void run()
{
while(true)
{
c.repaint();
j++;
if(j==8)
j=0;
}
}
}
public class zzz extends Applet 
{
ttt t;
uuu u;
int p,q;
Image m[];
Image n[];
public void init()
{
t = new ttt (this);
u = new uuu (this);
t.setPriority(Thread.MIN_PRIORITY);
u.setPriority(Thread.MAX_PRIORITY);
m = new Image[17];
n = new Image[8];
q=1;
for(p=0; p<17;p++)
{
m[p] = getImage(getCodeBase(),"T"+q+".gif");
q++;
}
q=1;
for(p=0; p<8;p++)
{
n[p] = getImage(getCodeBase(),"B"+q+".gif");
q++;
}
t.start();
u.start();
}
public void paint(Graphics g)
{
g.drawImage(m[t.i],10,30,this);
g.drawImage(n[u.j],150,30,this);
}
}

Here we have two animations at the same time. And by now you must be well-versed with animation techniques. Two arrays of *.gif are displayed successively. If you find the images are running at a preposterously fast pace, you can set priorities for them.

15

import java.applet.*;
import java.awt.*;
class ttt extends Thread
{
int i;
zzz b;
Graphics g;
public ttt(zzz a)
{
b=a;
i=0;
g=b.getGraphics();
}
public void run()
{
while(true)
{
g.drawImage(b.m[i],10,20,b);
i++ ;
if ( i== 17)
i=0;
}
}
}
class uuu extends Thread
{
int j;
zzz c;
Graphics g;
public uuu(zzz d)
{
c=d;
j=0;
g=c.getGraphics();
}
public void run()
{
while(true)
{
g.drawImage(c.n[j],150,20,c);
j++;
if(j==8)
j=0;
}
}
}
public class zzz extends Applet 
{
ttt t;
uuu u;
int p,q;
Image m[];
Image n[];
public void init()
{
t = new ttt (this);
u = new uuu (this);
t.setPriority(Thread.MIN_PRIORITY);
u.setPriority(Thread.MAX_PRIORITY);
m = new Image[17];
n = new Image[8];
q=1;
for(p=0; p<17;p++)
{
m[p] = getImage(getCodeBase(),"T"+q+".gif");
q++;
}
q=1;
for(p=0; p<8;p++)
{
n[p] = getImage(getCodeBase(),"b"+q+".gif");
q++;
}
t.start();
u.start();
}
}

In the previous programs, we have relied on the paint() to put the images on the screen. But that, besides making the code longer, also adds a lot of flickering to the animation. One way to remove this is to use getGraphics(), as is shown above.

16

import java.applet.*;
import java.awt.*;
class ttt extends Thread
{
int i;
zzz b;
Graphics g;
public ttt(zzz a)
{
b=a;
i=0;
g=b.getGraphics();
}
public void run()
{
while(true)
{
g.drawImage(b.m[i],10,20,b);
i++ ;
if ( i== 17)
i=0;
}
}
}
class uuu extends Thread
{
int j;
zzz c;
Graphics g;
public uuu(zzz d)
{
c=d;
j=0;
g=c.getGraphics();
}
public void run()
{
while(true)
{
g.drawImage(c.n[j],150,20,c);
j++;
if(j==8)
j=0;
try
{
sleep(1000);
}
catch(Exception e)
{
}
}
}
}
public class zzz extends Applet 
{
ttt t;
uuu u;
int p,q;
Image m[];
Image n[];
public void init()
{
t = new ttt (this);
u = new uuu (this);
m = new Image[17];
n = new Image[8];
q=1;
for(p=0; p<17;p++)
{
m[p] = getImage(getCodeBase(),"T"+q+".gif");
q++;
}
q=1;
for(p=0; p<8;p++)
{
n[p] = getImage(getCodeBase(),"b"+q+".gif");
q++;
}
t.start();
u.start();
}
}

As the images refresh too fast in the last program, you can use the sleep() to delay their drawing a little. A thread can be made to work slower by asking it to sleep. The try and catch might remind you of baseball, but it is Java's novel way of trapping any errors that might pop up during the execution of the program.

17

import java.applet.*;
import java.awt.*;
class ttt extends Thread
{
int i;
zzz b;
Graphics g; public ttt(zzz a)
{
b=a;
i=0;
g=b.getGraphics();
}
public void run()
{
while(true)
{
g.drawImage(b.m[i],10,20,b);
i++ ;
if ( i== 17)
i=0;
b.showStatus("i..."+i);
}
}
}
class uuu extends Thread
{
int j;
zzz c;
Graphics g;
public uuu(zzz d)
{
c=d;
j=0;
g=c.getGraphics();
}
public void run()
{
while(true)
{
g.drawImage(c.n[j],150,20,c);
j++;
if(j==8)
j=0;
c.showStatus("j..."+j);
}
}
}
public class zzz extends Applet 
{
ttt t;
uuu u;
int p,q;
Image m[];
Image n[]; Button o;
public void init()
{
t = new ttt (this);
u = new uuu (this);
m = new Image[17];
n = new Image[8];
q=1;
for(p=0; p<17;p++)
{
m[p] = getImage(getCodeBase(),"T"+q+".gif");
q++;
}
q=1;
for(p=0; p<8;p++)
{
n[p] = getImage(getCodeBase(),"b"+q+".gif");
q++;
}
t.start();
u.start();
o = new Button("hell");
add(o);
}
public boolean mouseUp(Event e, int x, int y)
{
o.reshape(x,y,40,30);
return true;
}

Here we manouvre with three threads. Two of them take care of simplistic animation (which must have become second nature to you by now) and the third takes of a button which moves everytime you click.

18

import java.applet.*;
import java.awt.*;
 
class uuu implements Runnable
{
int i; zzz b;
public uuu(zzz a)
{
b=a;
i=0;
}
public void run()
{
while(true)
{
i++;
b.repaint();
}
}
}
public class zzz extends Applet
{
Thread t;
uuu u;
public void init()
{
u = new uuu(this);
t = new Thread(u);
t.start();
}
public void paint(Graphics g)
{
g.drawString("i..." + u.i, 10, 40);
}
}

As you must have noticed, till now we have been initializing t by passing 'this' as a parameter. That means, in plain English, that the run() will be called from the current class, i.e., zzz. But this time, we've replaced 'this' with u, which looks like our own class uuu. So the run() specified in the class uuu will be called. Meanwhile, uuu is a class that has not been derived from the Thread class, but it implements Runnable.

19

import java.applet.*;
import java.awt.*;
class uuu implements Runnable
{
int i; zzz b; 
public uuu(zzz a)
{
b=a;
i=0;
}
public void run()
{
while(true)
{
i++;
b.repaint();
}
}
}
class ttt extends Thread
{
zzz b;
int j;
public ttt(zzz a)
{
b=a;
j=0;
}
public void run(()
{
j++;
repaint();
}
}
public class zzz extends Applet
{
Thread h;
uuu u;
ttt t;
public void init()
{
u = new uuu(this);
h = new Thread(u);
t = new ttt(this);
h.start();
t.start();
}
public void paint(Graphics g)
{
g.drawString("i..."+u.i,10,40);
g.drawString("j..."+t.j,10,80);
}
}

This was just another example of how a class which has not been derived from Thread can work. Here we have two threads and our pet variables i and j being incremented everytime.

JavaBeans : The Beans of the Future

 Beans in the Market

 If you enquire about the types of beans available in the market, you are bound to get a variety of answers. There are french beans, large beans, small beans, and so on. Then some intelligent friend of your's might say that JavaBeans are also available. Let us leave all the other beans to the vegetable vendors, cooks and mothers to figure out and talk about JavaBeans. The first thoughts of JavaBeans might get your minds drifting away to the ungrazed pastures on the island of Java (Indonesia) where coffee beans are grown. But it's not so. In short, JavaBeans have something to do with the much talked about programming language, Java.

Before knowing what a JavaBean is, let's look into the world of COMPONENTS and CONTAINERS . Seeing these BIG words used by shipment fellas, you don't have to get bogged down and think about the fettering consequences JavaBeans could have on your lives. You don't have to look out for some intravenous JavaBeans infusion in the market, since you'll be spared the time and money, searching for such an infusion. Patience, is what we ask of you . Just join us in our ride to ecstasy and experience the enlightenment that knowledge can endow upon you.

First, let's get our basics clear with a true-to-life example.

Suppose we had two programmers and a client. Programmer A has come out with the latest E-MAIL program with a great user interface. The client is delighted with A and is ready to buy his program. But fortunately or unfortunately the client is weak in English, and sends programmer A a letter saying

" I will take your prouduct only if you can inculude spelcheck in it."

Signed : client

Seeing the pitiable state of his client's English, A takes it to be his moral responsibility to include spellcheck in his program. He neither has the time nor the patience to sit down and write a spellcheck program. So, he goes to the market and buys a spellcheck from B and includes it in his E-MAIL program. Now B's program is the component, which is added to A's program(container). While looking for a spellcheck, A did not consider any and every spellcheck available. Only that program which complied with, or followed the set of rules put forth by A, got the deal.

We should drive home the fact that a COMPONENT must follow a certain set of rules given by the CONTAINER. Sun Microsystems developed a set of rules to enable Java programs to be used as components, which they named 'The JavaBeans'. They also developed a reference container for these JavaBeans, to show the world, the rules to be followed while using them.

 

Anatomy of a Bean :

For God's sake, this is not a botany tutorial. We are making our first attempts at studying the internal structure (anatomy) of a component (Javabean). We are dealing with the latest technology and we sincerely hope that you get this bean working. Let's jump into the

unfathomable / great

ocean full of

bewilderness / bliss.

Go through the entire tutorial and strike out which-ever is not applicable.

Create a subdirectory. Consult astrologers to give it the right name, because we sincerely believe that "Well begun is half (the work) done".

  We consulted Shri.Astro Maharaj (SAM) who laid our JavaBean Foundation Stone (JFS) by naming our subdirectory as jfs. We were even forced to print the legal statement in order to keep ourselves litigation free.

Legal Statement : JFS has no relation whatsoever with JFC .

All Rights Reserved by S.A.M copyright xxxxxx

Bare Minimum Necessities(BMN) for learning JavaBeans

1. Windows 95

2. JDK 1.1.x

3. SCQ

The first two BMN's are heard of but, what is the third BMN ?Is it some new software in the market?

These are questions which usually cross the mind of any sensible person. The answer !! Oh! it's very simple. SCQ is what every man should have to enable him to surge ahead in life

A). It is an abbreviation where, S- Sense of humor .

C- Courage, for accepting challenges .

And Q- a Querying mind .

c:\ jfs\>edit zzz.java

Program 1:

zzz.java

import java.applet.* ;
import java.awt .* ;
public class zzz extends Applet
{	
	public void paint(Graphics g)
	{
	 g.drawString ("FrenchBean",10,10);
	}
}

This Program ends here.!!!

We had this printed , just in case you were trying to turn pages, unable to believe that a Javabean (an eight lettered word ), can be such a simple program. Then, what was all the hype about technology, we mentioned earlier ?

There is one thing every person must understand about any new technology. It always makes life easier by doing all the bad (complex) jobs for us. So to succeed in the market it has to be very simple to use. Enough philosophy for now, let's get down to work . JavaBean is just another Java program which can be used as a component in a container.

An Ode to the Jars :

Bungee jumping, skiing, scuba diving and surfing the net are the hobbies of millions, around the world. But did you ever try to think why surfing the net comes last on the list of hobbies of most people? It 's because of the amount of time you have to wait before things appear on your screen.

When a person goes to a search engine on the Internet and asks for some information, he is connected to a different site where this information is available. The required data is in the form of a HTML document i.e. he first connects to the server, and gets the HTML document. Let us suppose that the particular document contains an animation that requires a number of .gif files to be displayed, one after another. Before showing up on the screen, the application might therefore ask for a few .gif files, some .class files, etc. Everytime the next picture has to be displayed, a .gif file has to be obtained from the server. To retrieve each file, a special request has to be sent to the the server, and the bytes have to be transferred to the client. Moreover there is a lot of congestion on the net. The time taken for the transfer of the required bytes depends on the quality of the line, congestion on the server (too many clients accessing the same server) etc. Statistically speaking , even if we were to send you a message saying "Hello", 40 additional bytes of data(known as a TCP/IP header) would have to be transferred along with this message. So the gist is that each time there is a transfer of actual meaningful data from or to the client, there is also a transfer of an additional 40 bytes of data, irrelevant to us.

Suppose your friend gave you a mystery novel. By the time you reached the climax, you found out that the other part of the book was missing. Anxious to read the other part , you went to your friend's place, but in vain. Your friend had left for some place and wouldn't be returning until the next day. You would be helpless and have no other alternative, but to wait . Had you friend been thoughtful enough, he would have given you the entire book, in one piece.

Sun Microsystems has, in fact, been thoughtful enough, not to give us things in bits and pieces. Hence they introduced the concept of JARS. All the .gif files, .class files, ect, related to a particular application are put in the jar and can be compressed . On the server, the HTML file has the appropriate tags for the jar. So when the client asks for the HTML file that contains the Java animation, the server is kind enough to send the whole jar to the client. Now, at one go, the client has all the required information. The client does not have to ask the server, (who is always busy) again and again for the files relating to the particular application. In this way, both the server and the client save precious time. All this has been done to make the life of net surfers easier. Mind you, the previous program can be called a JavaBean only when put in a jar file .

Back to the zzz.java program previously written

1) For compiling our code, give the following command

c:\jfs> javac zzz.java

2) edit zzz.mf // The manifest file

zzz.mf

Manifest-Version : 1.0
Name : zzz.class 
Java-Bean : True 

3) Now, let's see what the command ' jar ' is all about.Actually, ' jar ' is a program whose function is to put all the required files into the jar. 

4)c:\jfs> jar cfm zzz.jar zzz.mf zzz.class

This command is used to include all the files of a particular application in the jar file .

Look at the word we have written after ' jar ', namely ' cfm '. Each and every character of ' cfm ' has some significance. This is shown below.

c : create

f : file

m : manifest file also included

This word ' cfm ' is followed by the name of the Manifest file. A manifest, in the transportation business, refers to a list of things that have to be shipped across. The Manifest file also contains a list of all the .class files, .gif files, etc, that go into the jar. It also informs the jar that, of all the files included in it, only zzz.class is the JavaBean, while the other files are support files for this JaveBean. After the name of the Manifest file, we give the name of the JavaBean zzz.class and all the other files connected with it .

 

5) c:\jfs>copy zzz.jar c:\bdk\jars

Of course, this command copies our jar file into the jars subdirectory in the bean development kit. These directories are created when the Beans Development Kit is being installed. Sun Microsystems has created a reference container for the JavaBeans, called the BeanBox. This container has been designed to look for any jar file that it requires in the directory c:\bdk\jars.

 6) We get out of our subdirectory and give the following command

c\:>cd \bdk\beanbox

c:\bdk\beanbox>run

Voila, and our javabean is right there at the bottom of the Beanbox ToolBar.

Click and drag our javabean (zzz) into the beanbox and don't be surprised to find a "Frenchbean" on it. This is, after all the same string we had written in the program zzz.java. Now, to bring the explicit button in the ToolBar into the beanbox, we first click on the button after which, we position the mouse on the beanbox. Then we click in the Beanbox to see the button displayed. Now that we have a button and a Javabean(zzz) in the Beanbox , we must be satisfied, but , NO!! We want something more !!We want to connect both the button and the Javabean in some way.

First we click on the freshly brought button, and then look into the various options in the EDIT menuitem in the Beanbox. Now, logically speaking, we are searching for the functions which the buttonpush can do for us, hence we must checkout the Action Performed in the buttonpush option of the Events submenuitem.

On selecting the ActionPerformed option for a buttonpush , we find a jazzy red line, with one end fixed at the button and the other end, free to move with the mouse. Now position our mouse on our zzz javabean in the Beanbox and click on it. By doing this, we are actually connecting the button with our zzz javabean. As soon as we click on the zzz javabean , an Event Target Dialog (dialog box with this heading) pops up in the Beanbox.. This dialog box has a big list of functions which the javabean contains, and anyone of them can be assigned to our pushbutton. Of the many functions in the dialog box, only one seems to be both familiar and mysterious i.e. Hide, so we select it, click on OK and wait for the fun.

Now let's emulate the disappearing act of Houdini . Press the pushbutton, of course with a click of the mouse and see the "Frenchbean" disappear i.e. the javabean (zzz) in the beanbox disappears.

The Fundamentals of a Property :

Now, it's time for some fun. To begin with, we first look into the Toolbox (beanbox frame) on the left of our screen and select the Juggler icon . We have to bring it into our beanbox , before the fun begins. The procedure is similar to obtaining the explicit button in the beanbox. There is something known as the property sheet, just to the right of the beanbox. Drag this property sheet to a convenient position. Can we interact with the Juggler ? This is the first question in our Querying minds. The answer is, YES WE CAN !! But first, let's take a closer look at the property sheet. It has a property called Animation Rate, which can be changed by the user. So, what are we waiting for ? Let's enjoy ourselves, by changing the value of the property and watching the Juggler, juggling to our commands (Actually, when we increase the property rate, the juggling becomes slow and vice-versa ). Such properties, believe us, are fun to play with, if you are not a programmer. But what if God decided that you'll be a programmer in this life. You have two alternatives, either pray to God to have mercy on you or accept the challenge. Take our word for it and accept the challenge of getting your fundas clear.

So, what is a property?

In short, it is a variable which can be changed by the user.

Now, it is very easy to fix the value of a certain variable i.e.initialize it in the program itself. In any program, it is easy to write a series of statements that will cause some code to be executed if a certain variable is greater than a particular value. But it is very difficult to define a variable in such a way that it can be changed by the user and run in real time .(i.e. the effect of the change in the variable is seen in the output instantaneously. Then how do we incorporate a property which can be changed by the user?

Every property has to have a ' get ' and a ' set '.

Only two things can be done with a variable.

i) set ii) get

 

example :

Suppose we say ,

i = 10

By this , we are setting the variable i to 10 .

and when we have i on the right i.e.

something = i + 4

we are getting(returning) the value of the variable i for some other purpose .Hence, for i to be a variable for the user (property), we need to specify two functions , Get and Set . The function which says set has to be given the value 10, whereas the function which says get has to return this value .

Actually something known as the Introspection API and the reflection API go through the code and give us a property for the set and get functions.

zzz . java

import java.applet.* ;
import java.awt.* ;
public class zzz extends Applet 
{
int aa =10 ;
public void paint (Graphics g)
{
	 g.drawString ("Great" + aa, 1, 1) ;
}
 
public void setxx(int i)
{
	 aa = i ;
}
 public int getxx ( )
{
	 return aa ;
}
}

This is a Javabean only after thrown into a jar . Hence run the batch file that follows after editing the zzz.mf file as before .

a .bat

	javac zzz.java
	jar cfm zzz.jar zzz.mf zzz.class 
	copy zzz.jar c:\bdk\jars 
	cd \bdk\beanbox 
	run 

 

Hey!! There, we have our property xx in the property sheet . Next to this, we see a value 10 which can be changed by us. The result is seen in the Beanbox in real time.

The results of the experiments with the property sheet are as follows:

when xx =10 , we see " Great 10 " in the beanbox .

and suppose it is changed to xx = 100 , we see " Great 100" in the Beanbox .

Shake yourself up !!! You've done it !!and that too all by yourself.You've just written your own property . We are oozing with confidence and bubbling with enthusiasm so, let's not waste time and get down to something even more interesting.

Simulating our own function :

Previously, to enact Houdini, you clicked on ActionPerformed for a PushButton and chose a target method ( assigned to the PushButton ) i.e. Hide . We can actually get our own function in the Event Target Dialog . For this, we make modifications in the previous program of a property.

 

Remove the "getxx" and the "setxx" functions from the previous program, and put the following function in their place.

public void abc( )
{
aa = 1000 ;
repaint ( ) ;
}

Now, run the a.bat file for compilation of the .java code , creation and inclusion of the files into the jar file and finally, copying the jar file into the jars subdirectory.

Then we go through the whole procedure of obtaining our tool zzz and the explicit button into the beanbox and proceed to the Event Target Dialog by clicking on Action Performed of a buttonpush as before. The function abc ( ) that we included in our code is up on the list . To see the magic of our function, we select it and click on OK. We then click on the button and see the following change in the beanbox.

"Great 10 " to " Great 1000"

Smart Question : Why did we choose only abc ( ) and not any other name for our function, like xyz etc ?

Answer : So that, you find it right on top of the list, and don't have to sweat searching for your function named xyz in the Event Target Dialog .