Men are amused by anything. That is why professional ice hockey is so popular. That is why Disneyland runs into lengthier balance sheets than the scientific museums. And that is why something like Java is touted as the next Glasnost (well, unless you are a snoozebucket, you are probably aware of Java, the language that is bowling the world over). Make way. Here comes the stuff our forefathers warned us about. It is mightier than the sword, the pen and usually, the programmer. A thousand and one news-breakers and articles have done their rounds on how Java is invariably an isotope of C++ minus the warts and pimples, on how it is going to give the Internet an upbeat facelift, on how...... But wait. The last thing you want to do is to sit back and worship the greatness of a language; you want to use it. The one sad hitch with today's software is that the so-called tutorials and manuals are scarcely meant for anyone to understand. Take the samples bundled with Java for instance. How would you like the idea of brooding over a hundred-line sample code to begin with? What these codes fail to do is spark an interest among the wide-eyed newbies. ( Between you and me, I suspect that is the state-of-the-art way of doing graffitti on aspiring programmers :) ). That's precisely what we aim to do here - to give you the first few sips of Java (seasoned not to burn your tongue). Our approach is simple. As far as possible, we will add a line at a time and expect you to try it out (if we exceed that, we apologize). The worst thing that could happen by trying to learn programming in this way is that we might lead to grazing down of a few more trees (we will use more paper, right). But at least we can comprehend the language better. Undoubtedly, Java has flung open a whole slew of possibilities to spruce up a page on the Internet. Every little Johnny in the world, who has anything close to a GK, knows that Java can change lives. How is the question. Before we begin, let us make a few things clear. First, to learn programming in Java, it is undoubtedly a prerequisite to have a passing knowledge of C++ or we'd rather you sit over the weekend with a load of beer and cheetos in the fridge and atleast a dozen aspirins in the drawer :) . Secondly, the programs in Java here are explained in a simple, understandable manner and hence anybody expecting a display of rhetorical caliber is in for a disappointment of his lifetime. Just like an artist's potrait speaks for itself, we'd rather have Java speak for itself too. Third, while each concept is clearly explained, we prefer to keep our distance from the 'gears and cogs' of the language. And yes, it is also assumed you have downloaded the Java Develoment Kit. (For those who came in late, the software can be downloaded from the address http://www.javasoft.com ) Some Conventions that we swear by We are not concerned with inculcating obedience or influencing the programming style of our readers; quite the contrary, we intend the development of initiative. The simplicity that will inevitably be exhibited in our code and explanation is merely a method to refrain from pedantic. The idea is not to win a prize in computer literature but to shorten your learning curve. The naming conventions that we will adhere to include: The variables that we use will be of one letter, for instance i, j, g
etc. When we started learning java 5 years ago, we made an attempt to put up tutorials relating to different aspects of Java programming language on http://www.vijaymukhi.com. Since it was ranked as one of the best online tutorials then, we have decided to add a few of these tutorials to our very first book on Java. A lot has changed since then but most of the code written still works. We would like to thank our writer then, 'Shashank Tripathi' for having used the best langauge and vocabulory thereby making it an interesting readable literature. PS: Some programs will repeat in a few chapters, but the explanation given here will give you a different insight into this widely used language. Applets "Ours is the age of substitutes; instead of principles, we have slogans; instead of genuine ideas, 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 subdirectory under the root called, say, "xxx". Then set the path to \(javadirectory)\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 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 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 file alongwith the width and the height 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. a1.java 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.zip
which is within a java subdirectory. 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... 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 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... a1.java 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. > ren a1.java 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 compile the new java file using javac and 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. 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 classes.zip ). 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.
When you compile this java file, you will get one warning. Warnings can be ignored for the time being. 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 a 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.. 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.
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... zzz.java
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.. zzz.java public void init() public boolean mouseUp(Event e, int x, int y) At Work Then Straight dope on The Abstract Windows Toolkit If your most fiendish nightmare is drowning in a bowl of alphabet soup, maybe you'd better re-think your Java-oriented strategies; because you are about to leap into a scaffold of functions that come wrapped up, ribbon and all, to help you give that graphical look! And yep, from a fairly prudent perspective, The Abstract Windows Toolkit as it is called, with its horde of teeny-weeny functions, does indeed provide the underpinnings for the user-friendly Graphic interface. In this section, we will tinker with these little widgets that come bunched up as the AWT. Before embarking on any sort of coding, let us look at the following diagram... Button In the init(), we add a button called "hell". When you run this program, you will see a button with the name (or the label ) "hell" on the screen. That's not great shakes afterall, but you just wrote your first AWT program! TextField Like running the earlier program presented you with a button, this one will give you a text field. That is nothing but a single line edit box on the screen. Well, I don't mind going on like that for each and every wee feature, showing you one new thing at a time, but its the space that counts (not to mention your patience). Hence, I guess it should suffice to say that like the above objects,i.e, Button and Textfield, the following can also be created. TextArea add(new TextArea()); This is similar to a huge text field, that is, it covers a larger area than the Textfield. While trying the text area, I'd rather you maximise the applet window because it comes like a multiple line edit box on the screen. Choice add(new Choice()); Choice is a word straight out from the Jargon Dump (which, incidentally, is the favourite hang-out of the techno-nerds!). A Choice() adds a drop down list box. List This will display a dry list box displayed on the screen. Dry because there will be no options given. (Well you wouldn't want to use their options anyway). Checkbox add(new Checkbox()); Unless you bought your computer to serve as the world's most expensive doorstop, you are well-versed with the check-boxes. In Java, this is the way you create your own checkboxes. CheckboxGroup :The Windows aficionados know it as the radio-buttons. Scrollbar add(new Scrollbar()); Remember how you scroll through your love letters? Well, ulterior motives aside, you are well-versed with the scrollbars (unless ofcourse, your fiancee is a DOS-diehard). Label add(new Label("Good")); Here, let us meet the most drab member of the AWT family. Just plain text that drawls on the screen whatever you pass it as a parameter. Actually Getting down to work Now that we are a little better than AWT-bumpkins, let us unwrap it all
one by one and pick up the pieces from the toolkit cornucopia...
Buttons Here we have a button b added, very much the same as our first AWT program but for one hair-breadth difference. In this way, we have an object b that looks like a Button . Therefore, we can also use the functions of the class Button . With this in mind, let us proceed to the next one... setLabel() Out here we first add the button b with the name of "i...0"(because i is 0 in the beginning). Then we include the mouseUp() where we change the label or the name of the button with the setLabel() . Meanwhile, we have a variable i which we increment everytime the user clicks with the mouse. The increased value of i is displayed as the name of the button. reshape() This program demonstrates how the button or any other feature in the AWT like the text field, list box etc can be moved to any coordinate and resized. For our button b , we use the reshape() which means we want to change the shape and the position of our button. It is apparent that the reshape() consumes four parameters. The coordinates of the position where we want the button to be, and its width and height. getLabel() When we can set a label to a button, it ofcourse is possible to get the
label of the button as well. The above program explains how the getLabel()
functions. It will become a little clearer with the following program...
When the user clicks with the mouse, it is checked if the label of the
button is "hello" or "hi". If it is "hello",
the label is being changed to "hi" and vice versa. If a button
is beginning to give you the pips, let's move on to a little higher level.
Three is a crowd. That's why we have three buttons here. The buttons a, b and c are assigned the names "Hide", "Show" and "Hello" respectively. And then, for reasons other than impressing you, we use the action() instead of the variety of mouse functions. The actions function uses the parameters Event and Object . If clicked inside any of the button, the Object o stores the string that is the label of that particular button. Inside the action() function, which keeps a record of all the actions of the user, we have the condition. If the user clicks on the button named "Hide", o will be "Hide" and in that case we are hiding the button. If, on the other hand , the user has clicked on "Show", we show back the button.
This program works exactly like the previous one. But instead of hide() and the show() , we have the enable() and the disable() . It is hard to find another program more self-explanatory. Most of the functions that work with buttons also work with other members of the AWT, for e.g., a textfield can be hidden/shown or disabled/enabled too. TextField We create a TextField 60 characters long and a button to go along with
it. When clicked on the button, first the text already present in the
TextField will be shown in the status bar. Then, its text of is set to
"Hello how are you". The programs here can be a little hard
for the people not really conversant with programming. It can be further
simplified as follows... appendText() We have a text field that has 5 lines and 60 columns. In the action() we don't say setText, but appendText . This means that the text provided in this way will be added on to the text already present in the text field. CheckboxGroup The CheckboxGroup is, in effect, a collection of checkboxes. But, too weirdly to be argued, the CheckboxGroup looks like our usual radio buttons. Here we create an object g that looks like a CheckboxGroup, and in the init function, we initialize it. We add to it three Checkboxes, named "Good", "Bad" and null respectively (null is not a name, it means that no name has been given). We also have to tell that the checkbox belongs to which CheckboxGroup, as in our case is g . The third parameter tells which Checkbox will be currently active. In plain English, this means that when we run the program, the third one will be active. After that if we click in, say, the Checkbox a, and then clicked inside the window, the showStatus() will show us that the "state of a..." is true and that of c is false. Choice l = new List(); We have a List l and a list box (or a Choice as it is called). To the Choice , we add three items with addItem ... xxx, yyy and zzz . Likewise, to the List we add a1, a3 and a2 . We are not really drunk to have the order as a1, a3, a2 and our basic arithmetic is not all that weak either. It is plainly to demonstrate that the items do not get added in a sorted order. After adding the items to the List and Choice , we add them to the Applet window with the add() . That, and a little tinkering with the functions of the previous examples will have you deft in Lists and choices in minutes. delItem() First a list of 5 members is created (though only 3 will be visible because we specify so) and added to the applet window. A button called "remove" is created. When the user clicks on this button, we delete the item number 1 from the list using delItem() . Note that when we specify 1, the second item gets the scissors because the items start from 0 onwards. Also the 'false' that we specify in the statement new List() (or for the C++ folks, in the constructor) means that multiple selection will not be allowed from the list. If we want to allow multiple selection of the items in a list, we have to specify it as true. consider the following code... Multiple Selection Now you can select more than one options of the list at the same time.
zzz.java When an item of the list is selected, the showStatus() will display the number of the item selected and its name on the status line. The getSelectedIndex() returns the number of the item that was selected, and the getSelectedItem returns a string that is the name of the item selected. countItems() Scrollbars The above program gives you a horizontal scrollbar with 1 as the minimum value for the scroll bar and 100 as the maximum value/limit. The parameter 10 is the starting point. Everytime we click, we increase the value of the scrollbar by 5. A noteworthy feature is that we'd rather have the borderlayout because the scrollbars are better off in the corners. I still have to see a scrollbar which reposes in the centre of a window. Labels Inside the init(), we initialize a Label and call it "good".
We add it to the current Applet window. When you run the above code, you
see a label on the screen. Here we explicitly state the layout we desire, viz., BorderLayout. Then we add the Label to the North. In this way, we can control the positioning of a label. Text Area With the setForeground() function, the color of the TextArea is set to blue. The inside() , if fed with two parameters, obediently tells us if the mouse is inside the scope of the text area or not. Depending on whether the mouse is within the text region or outside it, we alternate background colors. If inside, then red, if out, blue. Side by side, the showStatus also shows whether the cursor is "in" the text area or not. zzz.java
getText() We have a button and two text areas. The button is named "click".
The text area called t is placed at 10, 50 and the one called u is placed
at 5, 10. But notice the difference. u is given a text to be displayed
as an initial text ("Hello ..."). Now, when the user clicks
on the button, we get the text of u and show it as the status. Therefore,
the status will be "Hello ...". Quite a simpleton program, this one. We have a list with 5 items and
a text area. Now the names of all the items in the list are to be appended
to the text area. Even a blonde could crack this one :) But consider the
following code and try to figure what it does...
Or try another modified form of this one: zzz.java } Threads: The stretchy skeins of possibilities 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.. From the animator examples in the subdirectory demo, we picked up the ten *.gif files and this is the way you can animate them.The above code is to display an image out of the 10 every time you click. As seen in the earlier programs, 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 10th 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 10 images at different coordinates. zzz.java public class zzz extends Applet g.drawImage(m[6], 5, 130, this); Now we will display the above-seen images at the same coordinates to
get the effect of animation. public class zzz extends Applet The next program demonstrates what necessiates the concept of threads. zzz.java 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... zzz.java 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. While it is against our religious beliefs to cavil over trivia, it is
also essential to know of some Tid-bit functions that come along with
threads. They might come in handy when threads try to play hob with you.
Let us check out the first one, which, infact, is the solution to an array
of problems. The toString() does the work of converting the relevant details into
a string form. Here we use toString() with t, so the 'relevant details'
are the details of the thread t. When this converted string is specified
as a parameter to the showStatus, the value is displayed on the show status.
The list(), (which is the only new thing introduced here - in case you
are wondering about the necessity of the above program), tells you what
are the components of the current window and what are the threads currently
executed. The ThreadGroup() will list the different threads executed at the moment
when clicked with the mouse. But the hitch is that this output is available
only in the DOS shell,i.e., if you switch to the DOS shell from the Windows
environment. The super() will give a name to the thread (whatever provided as the parameter will be the name given to the thread). In the ttt class, we name it as "good". In the mouseDown(), we set the name of the thread u to "bad". So, now the run(), which is supposed to show the name of the thread will alternate between "good" and "bad". zzz.java The yield() As must be evident, while creating the new thread t, we are also giving
it the name of "good". This is another way of giving your thread
a name. Now when we show the status of the thread, the getName() will
display "good". class uuu extends Thread
Brrr....Its Hot : - We briefed you on what the Java ballyhoo is all about. Bet you are throbbing for the innards of Java programming by now. We will get down to that right off the bat. Before we hop on to savor the wondercoffee, however, let up get clear on one thing. The Java mug actually has two shades to it. For one. You can write applets , which will wriggle down the cast skeins of Internet cables on to a user's terminal, with the browser picking up the cudgels to execute them. As the other shade, you can write Java standalone programs, which will compile and execute on the user's local machine. As promised, in this series, we will master the techniques of creating such stand-alone Java programs and calling them your own (though we really like calling internet-independent programs). Owing to security reasons, there is an array of functionalities which the applets are denied by the rather rigid duo of Java and the Java-enabled browser. On the other hand, the stand-alone programs are, fortunately, spared from the security rigmarole. That gives us one good reason to pursue such programs. Unfortunately for the people who want to run without bothering to learn to walf first, we will stick to our rituals, that is, a step-by-step approach to programming. As regards our naming conventions, we do not intend to inculcate style-specific practices. Quite the contrary, we intend development of initiative and understanding. Hence, the names of our classes, functions and variables will not exceed three letters. In case you overlooked, the presence of classes etc. Also presupposes the fact that the reader is versed to a reasonable extent with C/C++ With that widget of wisdom up our sleeve, let's take the first sip. Make
sure you are in the DOS mode and running a text editor of your choice.
(According to our reliable astrologer, Edit serves the purpose well enough).
Well, that's admittedly a simple program. We define a class by the name of aaa. Mark that the name of our java file is zzz.java, which implies that the names of the class and the .java file do not matter so much now, though they will soon begin to. Hopefully, you know that the program has to be compiled before it can be executed. The Java compiler is called javac. So now we key in the following command at the DOS prompt. javac zzz.java The compilation process turns out to be comfortably peaceful and a file called aaa.class is created by javac. Which indicates that Java makes .class files instead of the usual .obj (the cheeky chappies at Sun were always creative with their names anyway). It is now a fair idea to try and execute the program. For this, we have to type : java aaa Bet you have realized that this command would actually read : java aaa. Class since we are trying to execute the .class file. But a period (.) is supposed to be a part of file path in Java, so we'd rather you skip the .class part out. The program, though successfully compiled, refuses to run without hassles. It flings the error message : In class aaa: vodi main(String argv[]) is undefined. If anything, that error message smacks nostalgically of C - main() and all. So we very willingly add the main() to our code. Consider the following code... zzz.java Our main() has one argument - an array called s. This array will contain strings, hence the String. It is similar to your argv in C, the only variation being, the number of parameters are not specified. A point to be noted here is that arrays in Java and C differ slightly. C gave no errors even if you tried to refer to an element outside the actual size of the array. That is, assuming we have an array a[10]. The size of the array is 10. While using C, we could cheerfully say a[11] in the program without any errors, though the output would be some out-of-this-world junk. Java, however, has built-in error checks that keep a track of the number of members and prevent us from going beyond the specified limit. When we javac the above code, it compiles quite conveniently. However, it refuses to run. This time the error shown is : In class aaa: main must be public and static. By default, the main() is private and hence, the others cannot avail of it. The simple reason why it must be public is that it should be visible to others (e.g., other classes, other programs and very importantly, our own Java Run time system). In plain English, when we say java aaa, the Java runtime system contacts the class aaa, looks for a function called main() init. But since the function has not been declared as public, the system cannot look into it. As regards static, a C++ programmer should be very well-versed with it. Ordinarily, to access a function inside a class, we have to define an object that looks like that class and access the function through the object. But by defining main() as static, we can access it directly, without needing to create an object that looks like class aaa. So we modify the code as follows... zzz.java After all those changes, the program finally works. But sadly, there is no attractive output because we have admittedly done nothing in the main(). Let us go right ahead and add some code. Retain the name of the java file. zzz.java Everytime we use java, we have a free reign to use the objects that are pre-created, so we are spared the burden of creating our own objects. One very helpful of these objects is System (and note the case because Java is pretty unforgiving with case-errors), which in turn has various other objects in it. In our case, the object is called out. From out, w use a function or a method called println, which can safely be likened to printf in C. Just like printf, whatever we snuff inside the double quotes will be snuffed out on the screen. So when we run this program, ofcourse after compiling, it will display the string "in main". A program in any self-respecting language is virtually useless unless
it makes use of variables. Since Java is surely one of them, let us add
a variable to the code... We choose to call our variable i. It is of the type int, and it is inside
main(). It is initialized to 0. That very eloquently shows that Java looks
and feels like C/C++. However, the println scores over the strict, old
printf. Note that we are displaying a string - - "in main.i.."
and the variable i.Unlike C, Java figures out how to display two different
data types at the same time, chucking out the fuss involved in the cumbersome
conversions. in main i..0 When you run the above program, with the command line being java aaa, you will see the output: in main.i...0 This is because the command line has to have some arguments besides the java aaa. For instance, if you type out java aaa a b c, the output will be in main.i...3 Which is to say that the object String works very much like argv[] of C, while the length can be likened to argc. The array s stores the command line arguments (that is, whatever you type besides java aaa) and length counts the number of extra arguments typed in. Now if we want to display the actual elements, we can do that by saying s [0, s [1] and so on. In our case, for example, when we say s[0] it will print the a, s[1] will print b and s[2], c). Let us see for ourselves how... zzz.java If you run the above program without any extra parameters, it will display the error.. java.lang.ArrayIndexOutOfBoundsException To check for that, we can modify the program a little... zzz.java In the above program, we check whether the user has entered anything other than java aaa with the if condition. That is because i stores the number of these extra arguments. If the user has entered nothing, we display "no parameters", otherwise we display the first additional argument. All the arguments can be displayed inthe following way... zzz.java The above code checks for the presence of extra arguments, and if present, it displays all of them. Consider this code for another minor revelation... Here the compilation will give an error saying : can't make static reference
to a nonstatic variable i in class aaa. That is because main() is a static
function and static functions cannot refer to any variables outside their
own body. Whereas, in the above program, our variable i is a global variable,
i.e., it is defined outside any function. So it cannot be referred by
the
We believe we have made our technique sufficiently clear by now. Ofcourse, with the kind of programs illustrated here, we can not look forward to a prize in the field of computer sciences. But yes, we make no compromises with our fundamentals. As regards the concepts of Java, there are quite a few potatoes in the sack. We promise to bring you all of them in elaborate detail and with a similar simple, step-by-step approach to programming. Whatever the implications of how Java is being accepted as a popular language or how it is starting a whole new revolution, one fact remains undeterred. It definitely is the harbinger of a dynamic future. Sun Microsystems, by introducing the unprecedented concept, has planted a stake in the sand. What we make out of it is in our hands. With a little help from my friends There are so many of us out there goofing up our programs trying hard to figure out the myriad concepts of Java and so few who actually seem to be getting anywhere. The least we can do is be together in cyberspace and share our experiences and knowledge. All your comments, queries, headaches, suggestions and experiences, both of the moments of bright flashes of understanding and the baffling times are welcome. You can reach us at : vmukhi@vsnl.com. We might serve as Java Aspirins for your digital headaches :) . |