Shlurrrpp......Java
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
“ The essence of magic is simplicity “
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.
The functions will be of two letters, e.g., aa() , bb() etc.
The class names will be three letters, e.g., zzz 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
A
Tweak of Lemon...
“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
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 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
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.zip which is within a java
subdirectory.
a1.java
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...
a1.java
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 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
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.
> 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.
zzz.java
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...
zzz.java
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 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.
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...
zzz.java
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;
}
}
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..
zzz.java
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.
zzz.java
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.
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, initially 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...
zzz.java
import java.applet.*;
import java.awt.*;
public class zzz extends Applet
{ Image n;
public void init()
{ n = getImage(getCodeBase(), “cow.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 “cow.gif” which
exists on our hard disk. (PS Check up the \demo directory for more .gif files;
gif files 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 “cow.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..
zzz.java
import java.applet.*;
import java.awt.* ;
public class zzz extends Applet
{ Image n;
int a; int b;
public void init()
{ n = getImage(getCodeBase(), “cow.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;
}
}
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
zzz.java
import java.applet.*;
import java.awt.*;
public class zzz extends Applet
{ public void init()
{ add(new Button (“hell”));
}
}
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
zzz.java
import java.applet.*;
import java.awt.*;
public class zzz extends Applet
{ public void init()
{ add(new 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
add(new 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...
Controls
The little yet useful underpinnings for the
Graphical look
Buttons
We said a while ago that this tutorial was
tailor-made for you. How in blazes could a tailor do without buttons ? Try out
the following code...
zzz.java
import java.applet.*;
import java.awt.*;
public class zzz extends Applet
{ Button b;
public void init()
{ b = new Button(“hell”);
add(b);
}
}
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()
zzz.java
import java.applet.*;
import java.awt.*;
public class zzz extends Applet
{ Button b;
int i=0;
public void init()
{ b=new Button(“i...” + i);
add(b);
}
public boolean mouseUp(Event e, int x, int y)
{ i++;
b.setLabel(“i...” + i);
return true;
}
}
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()
zzz.java
import java.applet.*;
import java.awt.*;
public class zzz extends Applet
{ Button b;
int i = 0;
public void init()
{ b = new Button(“hell”);
add(b);
}
public boolean mouseUp(Event e, int x, int y)
{ b.reshape(x, y, 30, 40);
return true;
}
}
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()
zzz.java
import java.applet.*;
import java.awt.*;
public class zzz extends Applet
{ Button b;
int i = 0;
public void init()
{ b=new Button(“hello”);
add(b);
}
public boolean mouseUp(Event e,int x, int y)
{ showStatus(b.getLabel());
return true;
}
}
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...
zzz.java
import java.applet.*;
import java.awt.*;
public class zzz extends Applet
{ Button b;
public void init()
{ b=new Button(“hello”);
add(b);
}
public boolean mouseUp(Event e,int x, int y)
{ if(b.getLabel()==”hello”)
b.setLabel(“hi”);
else
b.setLabel(“hello”);
return true;
}
}
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.
Hide and seek
zzz.java
import java.applet.*;
import java.awt.*;
public class zzz extends Applet
{ Button a, b, c;
public void init()
{ a = new Button(“Hide”);
b = new Button(“Show”);
c = new Button(“Hello”);
add(a);
add(b);
add(c);
}
public boolean action(Event e,Object o)
{ if(“Hide”.equals(o))
{ c.hide();
}
if(“Show”.equals(o))
{ c.show();
}
return true;
}
}
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.
zzz.java
import java.applet.*;
import java.awt.*;
public class zzz extends Applet
{ Button a, b, c;
public void init()
{ a = new Button(“Enable”);
b = new Button(“Disable”);
c = new Button(“Hello”);
add(a);
add(b);
add(c);
}
public boolean action(Event e,Object o)
{ if(“Enable”.equals(o))
{ c.enable();
}
if(“Disable”.equals(o))
{ c.disable();
}
return true;
}
}
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
zzz.java
import java.applet.*;
import java.awt.*;
public class zzz extends Applet
{ Button b;
TextField t;
public void init()
{ b = new Button(“click”);
t = new TextField(60);
add(b);
add(t);
}
public boolean action (Event e, Object o)
{ if (“click”.equals(o))
{ showStatus(t.getText());
t.setText(“Hello how are you”);
}
return true;
}
}
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...
public boolean action (Event e, Object o)
{ String s; boolean b;
s = “click”;
b = s.equals(o);
if (b)
{ showStatus(t.getText());
t.setText(“Hello how are you”);
}
return true;
}
appendText()
zzz.java
import java.applet.*;
import java.awt.*;
public class zzz extends Applet
{ Button b;
TextArea t;
public void init()
{ b = new Button(“click”);
t = new TextArea(5,60);
add(b);
add(t);
}
public boolean action (Event e, Object o)
{ if (“click”.equals(o))
{ showStatus(t.getText());
t.appendText(“Hello how are you”);
}
return true;
}
}
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
zzz.java
import java.applet.*;
import java.awt.*;
public class zzz extends Applet
{ CheckboxGroup g;
Checkbox a, b, c;
public void init()
{ g = new CheckboxGroup();
add(a = new Checkbox(“Good”, g, false));
add(b = new Checkbox(“Bad”, g, false));
add(c = new Checkbox(null , g, true));
}
public boolean mouseUp(Event e, int x, int y)
{ showStatus(“state of a...” + a.getState() + “
state of c...” +c.getState());
return true;
}
}
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
zzz.java
import java.applet.*;
import java.awt.*;
public class zzz extends Applet
{ List l;
Choice c;
public void init()
{ c=new Choice();
c.addItem(“xxx”);
c.addItem(“yyy”);
c.addItem(“zzz”);
l = new List();
l.addItem(“a1”);
l.addItem(“a3”);
l.addItem(“a2”);
add(l);
add(c);
}
}
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()
zzz.java
import java.applet.*;
import java.awt.*;
public class zzz extends Applet
{ List l;
Button b;
public void init()
{ b = new Button(“Remove”);
l = new List(3, false);
l.addItem(“aaa”);
l.addItem(“bbb”);
l.addItem(“ccc”);
l.addItem(“ddd”);
l.addItem(“eee”);
add(l);
add(b);
}
public boolean action (Event e, Object o)
{ if(“Remove”.equals(o))
{ l.delItem(1);
}
return true;
}
}
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
zzz.java
import java.applet.*;
import java.awt.*;
public class zzz extends Applet
{ List l;
public void init()
{ l = new List(3,true);
l.addItem(“aaa”);
l.addItem(“bbb”);
l.addItem(“ccc”);
l.addItem(“ddd”);
l.addItem(“eee”);
add(l);
}
}
Now you can select more than one options of the list
at the same time.
getSelectedIndex() and getSelectedItem()
zzz.java
import java.applet.*;
import java.awt.*;
public class zzz extends Applet
{ List l;
int i=0;
String s;
public void init()
{ l = new List(3,false);
l.addItem(“aaa”);
l.addItem(“bbb”);
l.addItem(“ccc”);
l.addItem(“ddd”);
l.addItem(“eee”);
add(l);
}
public boolean handleEvent(Event e)
{ if (e.target instanceof List)
{ i=l.getSelectedIndex();
s=l.getSelectedItem();
showStatus(“Name..”+s+”..no..”+i);
}
return true;
}
}
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()
zzz.java
import java.applet.*;
import java.awt.*;
public class zzz extends Applet
{ List l;
public void init()
{ l = new List(3,false);
l.addItem(“aaa”);
l.addItem(“bbb”);
l.addItem(“ccc”);
l.addItem(“ddd”);
l.addItem(“eee”);
add(l);
}
public boolean mouseUp(Event e, int x, int y)
{ showStatus(“Number of items..”+l.countItems());
l.clear();
return true;
} }
When clicked with the mouse, the countItems() will
display the number of items in the list box on the status line. The clear()
should clear the list but for some old grudge, it does not. (Beta version?)
Scrollbars
zzz.java
import java.applet.*;
import java.awt.*;
public class zzz extends Applet
{ Scrollbar s;
public void init()
{ setLayout(new BorderLayout());
s = new Scrollbar(Scrollbar.HORIZONTAL,10,5,1,100);
add(“North”,s);
}
public boolean mouseDown(Event e, int x,int y)
{ s.setValue(s.getValue()+5);
showStatus(“value “ + s.getValue());
return true;
}
}
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
zzz.java
import java.awt.*;
import java.applet.*;
public class zzz extends Applet
{ public void init()
{ Label l=new Label(“good”);
add(l);
}
}
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.
zzz.java
import java.applet.*;
import java.awt.*;
public class zzz extends Applet
{ public void init()
{ setLayout(new BorderLayout());
Label l=new Label(“good”);
add(“North”,l);
}
}
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
zzz.java
import java.applet.*;
import java.awt.*;
public class zzz extends Applet
{ TextArea t;
public void init()
{ t=new TextArea();
add(t);
}
public boolean mouseMove(Event e, int x, int y)
{ t.setForeground(Color.blue);
if (t.inside(x,y))
{ showStatus(“in”);
setBackground(Color.red);
}
else
{ showStatus(“out”);
setBackground(Color.blue);
}
repaint();
return true; }
}
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
import java.applet.*;
import java.awt.*;
public class zzz extends Applet
{ TextArea t;
public void init()
{ t=new TextArea();
add(t);
}
public boolean handleEvent(Event e)
{ if(e.target instanceof TextArea)
{ t.setForeground(Color.blue);
setBackground(Color.red);
}
else
{ setBackground(Color.blue);
}
repaint();
return false;
}
}
With this porgram, we introduce the handleEvent() .
If the user types inside the textarea or has the mouse inside the region (this
is determined through instanceof ), the foreground color is set to blue and the
background color to red.
getText()
zzz.java
import java.applet.*;
import java.awt.*;
public class zzz extends Applet
{ Button b;
TextArea t,u;
public void init()
{ b = new Button(“click”);
t = new TextArea(10,50);
u = new TextArea(“Hello ...”,5,10);
add(b);
add(t);
add(u);
}
public boolean action (Event e, Object o)
{ if (“click”.equals(o))
{ showStatus(t.getText()+”.....”+u.getText());
}
return true;
}
}
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 ...”.
zzz.java
import java.applet.*;
import java.awt.*;
public class zzz extends Applet
{ List l;
TextArea t;
Button b;
int i=0;
public void init()
{ t = new TextArea(3,10);
l = new List(3,false);
b= new Button(“click”);
l.addItem(“aaa”);
l.addItem(“bbb”);
l.addItem(“ccc”);
l.addItem(“ddd”);
l.addItem(“eee”);
add(l);
add(t);
add(b);
}
public boolean action(Event e, Object o)
{ if(“click”.equals(o));
{ i = l.countItems();
for(int j = 0; j < i; j++)
t.appendText(l.getItem(j));
}
return true;
}
}
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...
zzz.java
import java.applet.*;
import java.awt.*;
public class zzz extends Applet
{ List l, m;
Button a, b, c;
TextArea t;
int i = 0;
String s;
public void init()
{ l = new List(3, false);
m = new List(5, false);
a = new Button(“Add”);
b = new Button (“Del”);
c = new Button(“Go”);
t = new TextArea(5,30);
l.addItem(“aaa”);
l.addItem(“bbb”);
l.addItem(“ccc”);
l.addItem(“ddd”);
l.addItem(“eee”);
add(l);add(a);add(b);add(c);
add(m);add(t);
}
public boolean action(Event e, Object o)
{ if(“Add”.equals(o))
{ s=l.getSelectedItem();
m.addItem(s);
}
if (“Del”.equals(o))
{ if (m.countItems() > 0)
{ i=m.getSelectedIndex();
m.delItem(i);
}
}
if(“Go”.equals(o))
{ t.setText(“ “);
for(int k = 0; k < m.countItems(); k++)
t.appendText(m.getItem(k)+”...”);
}
return true;
}
}
Cryptic clues: Add will add to the other list box,
delete will delete from the second list, go will show the items in the second
list on the text area
Or try another modified form of this one:
zzz.java
import java.applet.*;
import java.awt.*;
public class zzz extends Applet
{ List l,m;
Button a,b,c;
TextArea t;
int i=0;
String s;
public void init()
{ l = new List(3,false);
m = new List(5,false);
a = new Button(“Add”);
b = new Button (“Del”);
c = new Button(“Go”);
t = new TextArea(5,30);
l.addItem(“aaa”);
l.addItem(“bbb”);
l.addItem(“ccc”);
l.addItem(“ddd”);
l.addItem(“eee”);
add(l);add(a);add(b);add(c);
add(m);add(t);
}
public boolean action(Event e, Object o)
{ if(“Add”.equals(o))
{ i=l.getSelectedIndex();
s=l.getSelectedItem();
m.addItem(s);
l.delItem(i);
}
if (“Del”.equals(o))
{ if (m.countItems() > 0)
{ s=m.getSelectedItem();
i=m.getSelectedIndex();
m.delItem(i);
l.addItem(s);
}
}
if(“Go”.equals(o))
{ t.setText(“ “);
for(int k = 0; k < m.countItems();k++)
t.appendText(m.getItem(k)+”...”);
}
return true;
}
}
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..
zzz.java
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[10];
for (i = 0; i<10; 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 == 10)
i = 0;
a = x;
b = y;
return true;
}
}
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
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[10];
for (i = 0; i<10; 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, 30, this);
g.drawImage(m[2], 240, 50, this);
g.drawImage(m[3], 360, 70, this);
g.drawImage(m[5], 480, 100, this);
g.drawImage(m[6], 5, 130, this);
g.drawImage(m[7], 120, 170, this);
g.drawImage(m[8], 240, 200, this);
g.drawImage(m[9], 360, 230, this);
}
}
Now we will display the above-seen images at the
same coordinates to get the effect of animation.
zzz.java
import java.applet.*;
import java.awt.*;
public class zzz extends Applet
{
Image m[];
int i;
int j = 1;
public void init()
{
m = new Image[10];
for (i = 0; i<10; 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 == 10)
i = 0;
return true;
}
}
The next program demonstrates what necessiates the
concept of threads.
zzz.java
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...
zzz.java
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.
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.
zzz.java
import java.applet.*;
import java.awt.*;
public class zzz extends Applet implements Runnable
{
public void run()
{
}
public boolean mouseUp(Event e, int x, int y)
{
Thread t;
t = new Thread(this);
showStatus(t.toString());
return true;
}
}
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.
zzz.java
import java.applet.*;
import java.awt.*;
public class zzz extends Applet implements Runnable
{
public void run()
{
}
public boolean mouseUp(Event e, int x, int y)
{
Thread t;
t = new Thread(this);
t.start();
list();
return true;
}
}
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.
zzz.java
import java.applet.*;
import java.awt.*;
public class zzz extends Applet implements Runnable
{
public void run()
{
}
public boolean mouseUp(Event e, int x, int y)
{
Thread t;
t = new Thread(this);
showStatus(t.getThreadGroup().toString());
t.getThreadGroup().list();
return true;
}
}
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.
zzz.java
import java.applet.*;
import java.awt.*;
class ttt extends Thread
{
zzz a;int i=0;
ttt( zzz z)
{
super(“good”);
a = z;
}
public void run()
{
while ( true)
{
i++;
a.repaint();
a.showStatus(getName());
}
}
}
class uuu extends Thread
{
zzz a;int j=0;
uuu(zzz z)
{
a = z;
}
public void run()
{
while ( true)
{
a.showStatus(getName());
j++;
a.repaint();
}
}
}
public class zzz extends Applet
{
uuu u;
ttt t;
public void init()
{
u = new uuu (this);
t = new ttt (this);
t.start();
u.start();
}
public boolean mouseDown(Event e, int x,int y)
{
u.setName(“bad”);
return true;
}
}
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
import java.applet.*;
import java.awt.*;
public class zzz extends Applet implements Runnable
{
public void run()
{
}
public boolean mouseUp(Event e, int x, int y)
{
Thread t;
t = new Thread(this, “good”);
showStatus(t.getName());
return true;
}
}
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”.
zzz.java
import java.applet.*;
import java.awt.*;
class ttt extends Thread
{ zzz a;
int i=0;
ttt( zzz z)
{ a = z;
}
public void run()
{ while ( true)
{ yield();
i++;
a.repaint();
a.showStatus(getName());
}
}
}
class uuu extends Thread
{ zzz a;int j=0;
uuu( zzz z)
{ a = z;
}
public void run()
{ while ( true)
{ j++;
a.repaint();
a.showStatus(getName());
}
}
}
public class zzz extends Applet
{ uuu u;
ttt t;
public void start()
{ u = new uuu (this);
t = new ttt (this);
t.start();
u.start();
}
public void paint(Graphics g)
{ g.drawString(“i ..” + t.i,1,20);
g.drawString(“j ..” + u.j,1,60);
}
}
BREWING JAVA — THE FIRST
SIP
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).
zzz.java
class aaa
{
}
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
class aaa
{
void main( String s[] ) { }
}
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
class aaa
{
public static void main( String s[] ) { }
}
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
class aaa
{
public static void main( String s[] )
{
System.out.println(“in main”);
}
}
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...
zzz.java
class aaa
{
public static void main( String s[] )
{
int i = 0;
System.out.println( “in main.i..”+i );
}
}
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.
The output of the above program will be...
in main i..0
The object String has a member called length. Since
s (in the definition of the main()), looks like a String, we can access length
through s. That’s what our next program speaks about.
zzz.java
class aaa
{
public static void main( String s[] )
{
int i;
i = s.length;
System.out.println(“in main.i..”+i);
}
}
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
class aaa
{
public static void main( String s[] )
{
int i;
i = s.length;
System.out.println(“in main.i..”+i);
System.out.println(“in main s[0] ...” + s[0]);
}
}
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
class aaa
{
public static void main( String s[] )
{
int i;
i = s.length;
System.out.println(“in main.i..”+i);
if (i > 0)
System.out.println(“in main s[0] ...” + s[0]);
else
System.out.println(“no parameters”);
}
}
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
class aaa
{
public static void main( String s[] )
{
int i;
i = s.length;
System.out.println(“in main.i..”+i);
if (i > 0)
for (int j = 0; j < i; j++ )
System.out.println(“in main ..”+ j +”...” + s[j]);
else
System.out.println(“no parameters”);
}
}
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...
zzz.java
class aaa
{
int i = 0;
public static void main( String s[] )
{
System.out.println( “i..” + i );
}
}
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
main() . The only way to access in a case as this is
by making i static. This can be done by rewriting the first line in the function as static
int i = 0;
Before we bid adieu
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 :) .