1.
Evolution of Java
Things that you are
aware of today haven’t always existed nor have they suddenly emerged. They have
evolved over a period of time to fulfill our ever-growing needs. Similarly,
Java has evolved as the savior to meet the growing needs of the world. It
incorporates useful elements from languages like C and C++.
When you surf the
Internet, you use a browser, which is also called a user agent, that enables
you to view web pages and transfer data over the Internet. The most familiar among
the browsers are Netscape Navigator and Internet Explorer. So what happens when
you view a web page? Technically speaking, you connect to a web server and
download an html file. In other words, this html file comes over onto your
computer. Before Java, the downloaded file contained no intelligence. In that
sense, the web page was static. Sun Microsystems answered our need for dynamism
by developing Java. Java brought with it the ability to download an actual
program and at the same time execute it in our browser.
‘Will Java save the
world or not?’ Inquisitive as you may be, wait a while and you will enjoy the
fruits of patience. The philosophy of Java and its history can be understood
only gradually, in light of the knowledge you will soon gain.
Having looked into the
brief origin of Java let us start on our journey.
JAVA, The Programming
Language
Let us begin with the
basics. Every programming language has certain rules and programs written in
that language have to follow these rules. A similarity can be drawn to spoken
languages like English, French, etc. each of which has its own rules.
Given below is the
smallest program written in the Java Programming language. To begin writing
your first program, you must click on the Start button, go to the dos prompt
and type edit z.java. But before typing in edit, create a sub directory called
javaprg where you will save all your files. We have called the sub directory
javaprg but you can call it by any name
you like.
c:\javaprg>edit z.java
z.java
class zzz
{
}
Now, type the code
given above. Once you have written the code, you must save the file. In order
to do so, activate the menu option File by pressing the keys Alt-F and then the
menu option Exit. Press Y at the MessageBox which asks you whether you want to
save the file or not.
We have done our
coding under Windows but you can do the same under Linux or any other Operating
System, the results will be the same.
Let’s understand the
code.
This program begins
with the word class. A class is a collection. Every class is identified by its
name. In this program, we have named the class zzz. In case you are sleepy, you
might think of it as a snore, in that case, change the name to awake. In other
words, a class can be given any name you like. But if you’d rather followed our
naming conventions, then name it zzz.
A class being a
collection obviously means you have to put something in it. In order to contain
something in a class use curly braces,’{‘ to indicate the start and ‘}’ to
indicate the end of a collection.
The program must begin
with the word class followed by ‘{‘ and ‘}’. This is what we mean by
programming language rules. Each programming language has its own grammar, its
own syntax for writing code.
Every Java program has
to have at least one class and anything to do with Java has to be placed in a
class.
Now, something has to
understand the code that you have just typed and that something is the
compiler. So you now need to run this, the smallest Java program, through a
Java compiler and execute it. The compiler in the Java programming language is
called javac. Javac is part of what is called the Java Development Kit or JDK
in short. The JDK can be freely downloaded from the Sun Microsystems site. In
order to execute your program, give the command javac z.java at the dos prompt.
C:\javaprg>javac z.java
No errors, Great!! Now
execute the dir command.
( If you see any errors on your screen, set the path variable as c:\javaprg>set PATH=c:\jdk1.2.2\bin;%PATH% )
C:\javaprg>dir
Volume in drive C is SONAL
Volume Serial Number is 0661-13EE
Directory of C:\javaprg
. <DIR> 04-26-00 4:11p .
.. <DIR> 04-26-00 4:11p ..
ZZZ~1 CLA 178 04-26-00 4:15p zzz.class
Z~1 JAV 17 04-26-00 4:12p z.java
2 file(s) 195 bytes
2 dir(s) 5,214.56 MB free
You will see two files
listed. One is the .java file that you created and the other is a file with the
.class extension. Javac - the java compiler expects the java program to have a
.java file extension.
On closer observation,
you will notice that the .class file is displayed as zzz.class. The name of the
.java file i.e. z.java is of little importance to the java compiler. The
compiler gives weight to the class name, which
in our case is zzz. Thus, the file named zzz.class gets created. Had we
named the class xxx, the resultant file would have been xxx.class.
Applets
As mentioned earlier,
one of the advantages of Java is that it enables you to create programs that
execute within a browser. Henceforth, we will call a java program an applet.
Thus, an applet is a java program which
can be executed within a browser. It helps transform the static HTML
pages into documents full of life, interaction and vitality.
How can we execute an
applet in a browser?
Browsers only
understand html or html tags. Amongst these tags there is one by the name of
applet. You embed an applet in an HTML page using the applet tag. To understand
this better, create a file called a.html. This can be done using any word
processor. Type the following code:
a.html
<applet code=zzz.class></applet>
What does this mean?
<applet> is a tag and </applet> indicates the end of the tag. The
code attribute is used to provide the name of the class file, which in our case
is zzz.class. Alternatively, you can simply write zzz. Our code resides in the
class file. Now that you have embedded the applet in an HTML file by the name
of a.html, you will need to open a.html
in a browser.
You can use Internet
Explorer or Netscape Navigator to open this file. However, there is a
possibility that you may have neither IE nor Netscape. Not only did Sun
consider this possibility but also when they first released java there were no
browsers that supported it. Hence they gave us a browser that understands only
the applet tag, one that can run only java applets. They called this browser
the appletviewer.
We will use the
appletviewer. At the command prompt type appletviewer a.html
C:\javaprg>appletviewer a.html
Warning: <applet> tag requires width attribute.
Warning: No Applets were started. Make sure the input contains an <applet> tag.
usage: appletviewer [-debug] [-J<javaflag>] [-encoding <character encoding type> ] url|file ...
What do these warnings
mean? The appletviewer has come back with warnings saying that it needs an
attribute called width.
Since the applet will
be shown in the browser window, it needs the width to ascertain how large
width-wise, the window should be. Add the width attribute in the html file as
follows:
a.html
<applet code=zzz.class width=200></applet>
Now run the applet
viewer by typing the following:
C:\javaprg>appletviewer a.html
Output
Warning: <applet> tag requires height attribute.Warning: No Applets were started. Make sure the input contains an <applet> tag.usage: appletviewer [-debug] [-J<javaflag>] [-encoding <character encoding type> ] url|file ...
The appletviewer comes
back asking for another attribute called height. Java doesn’t seem to believe
in the ‘reveal all’ concept, it divulges slowly. You have no choice but to add
the height attribute in a.html. The order here is not important, the attributes
can be interchanged. A browser would display the applet in its window. Thus, it
wants to know the width and height of the window it should give the applet.
Your code should
resemble the following:
a.html
<applet code=zzz.class width=200 height=300></applet>
Run the appletviewer.
It should run this time.
C:\javaprg>appletviewer a.html
Finally, the appletviewer seems to give no
problems. You see a small window, at the bottom of which, are displayed some
messages and finally it says, Start: applet not initialized.
The above indicates
that the applet didn’t work. We have an error. Close the window and return to
dos. Here you will see the following error message or messages.
load: zzz.class is not public or has no public constructor.
java.lang.IllegalAccessException: zzz
at java.lang.Class.newInstance0(Native Method)
at java.lang.Class.newInstance(Class.java:241)
at sun.applet.AppletPanel.createApplet(AppletPanel.java:508)
at sun.applet.AppletPanel.runLoader(AppletPanel.java:444)
at sun.applet.AppletPanel.run(AppletPanel.java:282)
at java.lang.Thread.run(Thread.java:479)
The message says that
zzz.class is not public. What does this message mean? Error messages are rarely
meant to be user friendly and can sometimes be difficult to decipher.
A Java program is
executable code that comes across the net on to your computer. It could be
programmed to delete your entire hard disk. In that case, you would refrain
from visiting sites on the Internet due to lack of security. To prevent such
hazards Java has a lot of inbuilt security features.
The first form of
security is that if you have a class and you don’t put the word public in front
of it Java will make it private. Since it is private nobody cannot access it.
Thus, by default, every class is private. This is like security in many modern
operating systems. You are not allowed to access anything unless you are given
explicit permissions to do so.
Having understood
this, we can rectify the error by adding the word public in front of the class.
z.java
public class zzz
{
}
Now say:
C:\javaprg>javac z.java
z.java:1: Public class zzz must be defined in a file called “zzz.java”.
public class zzz
^
1 error
We still have an
error. The program now wants the name of the Java file and the name of the
class file to be the same. Sounds stupid doesn’t it! Once you create the .class
file you don’t need the .java file.
Don’t abandon Java yet! We have an error only because we have not
followed the conventions, the rules of the language. After all, Rules are
Rules! As preposterous as they may be, they are not to be questioned.
Abiding by the rules,
we rename this file to zzz.java.
c:\javaprg>ren z.java zzz.java
Now say:
C:\javaprg>javac zzz.java
Voila! No errors. Run
appletviewer with a.html. Cross your fingers and hope that all works well.
C:\javaprg>appletviewer a.html
As usual another
error!!! The same window that we saw earlier ...Start:applet not initialized.
Close the window and
get back to dos. You will see the following:
java.lang.ClassCastException: zzz
at sun.applet.AppletPanel.createApplet(AppletPanel.java:508)
at sun.applet.AppletPanel.runLoader(AppletPanel.java:444)
at sun.applet.AppletPanel.run(AppletPanel.java:282)
at java.lang.Thread.run(Thread.java:479)
Here it shows you a
different error, ClassCastException : zzz
Now you know why you
bought this book.....these lines just don’t make sense! You may read from up or from bottom, it still looks
like greek. We have learnt with experience that error messages are not meant to
be readable. If we knew what they meant, we wouldn’t make any mistakes.
Let’s get back to some
serious work. A class consists of functions. But what are functions? A function
is just program code. More on this just two programs later.
A class consists of
functions. The appletviewer has been told to call certain functions in your
.class file. Appletviewer expects your applet to have some code or functions in
it. Unfortunately, these functions
are not available in your file. Currently,
the class in your program is empty. To avoid adding all that code required by
the appletviewer, we will use an existing class supplied by Sun comprising of
these functions. This existing class is called Applet.
Sun documented the use
of the word extends to inform the Java compiler to merge all the functions or
code from the Applet class to our class zzz. Have your code match the
following:
zzz.java
public class zzz extends Applet
{
}
Extends simply means
that if the class Applet contains 20 functions, then those functions get added
to zzz. It is like physically keying them in yourself. Now let’s run javac once
again.
C:\javaprg>javac zzz.java
zzz.java:1: Superclass Applet of class zzz not found.
public class zzz extends Applet
^
1 error
This time the error
reads: ‘Superclass Applet of class zzz is
not found’. When you borrow money from someone, he becomes the lender and
you the borrower. In the same way, whenever you take code from another class,
in this case Applet, it becomes a super class or if you like using new words
Applet is the baseclass and zzz the derived class. We must incorporate these
words in our vocabulary to learn Java. The name of the super class is not
Applet; it is java.applet.Applet. In case you are wondering about the long
names, let us remind you that you can’t argue with rules. Rewrite your code as
given below and then run javac.
zzz.java
public class zzz extends java.applet.Applet
{
}
Run javac and you
won’t get any errors. Running appletviewer won’t give errors either. But you
won’t see anything other than ‘Applet
Started’. Finally, Mission
Accomplished!!!
Some more java conventions
Let’s be adventurous,
put all the code on the same line. Remove the line-breaks and put no spaces
other than those between the words. You will find that everything works fine.
zzz.java
public class zzz extends java.applet.Applet{}
Thus, all that extra
‘white space’ doesn’t bother the Java complier. You can use these to make your
program neater and thus more readable.
Java as a language is
case-sensitive. If you replace the ‘c’ of class with a capital ‘C’, it will
give you errors. It will assume it to be something other than class. So,
remember everything is case sensitive except the {} ( ;-)) . Go ahead, make the
change and see for yourself!
zzz.java
public Class zzz extends java.applet.Applet{}
C:\javaprg>javac zzz.java
zzz.java:1: ‘class’ or ‘interface’ keyword expected.
public Class zzz extends java.applet.Applet{}
^
zzz.java:1: ‘{‘ expected.
public Class zzz extends java.applet.Applet{}
^
zzz.java:1: Public class Class must be defined in a file called “Class.java”.
public Class zzz extends java.applet.Applet{}
^
3 errors
You make one error and
you get three errors instead! isn’t that dumb!
So, be on your guard
and don’t say we didn’t warn you.
Let’s finally understand functions with the help of this
program.
zzz.java
public class zzz extends java.applet.Applet
{
public void init()
{
resize(300,40)
}
}
What you are writing
right now, these lines of code, is what is called a program. And a function is
nothing but program code. We know that there is a function called resize in the
class called Applet. In order to call a function, you need the function name.
In this case, it is resize. The resize function requires two values, the width
and the height. This is because resize changes the width and the height of the
applet window.
Since we are learning
to speak Java, let’s call these ‘values’, ‘parameters’. The first parameter is
the width and the second is the height. These values are passed to the function
within the ‘(‘ and ‘)’ brackets. Like Java, there are other programming
languages like C and C++. Java is a wholesale copy from C and C++. It retained
the use of round brackets. We can’t change it to square brackets because that
is not the syntax for functions. Consequently, C++ and Java are similar. If you
know one of them then moving on to the other is relatively simple. Compile the
above program using javac. More errors! The error says: ‘;’ expected.
C:\javaprg>javac zzz.java
zzz.java:5: ‘;’ expected.
resize(300,40)
^
1 error
When we see the ‘)’ of
the function, we know that the function is over. But nothing seems obvious to
the Java compiler. It requires us to put a semicolon at the end of the
statement. Carriage returns don’t matter but semicolons are a must. But why
semicolon, why not dots? The developers of Java were asked to choose a
character that would indicate the end of a statement. Since they couldn’t agree
on a common character they decided to use their grandma’s recipie- They did “eenie,meenie,mina,mo”
and their finger was pointing at the semicolon and hence they decided on the
semicolon! You see RULES are RULES... C requires semicolons, so does C++ and
Java uses them too.
Make your program
error free by putting a semicolon after resize, just as we have done in the
following program. Execute it and see the window size change.
zzz.java
public class zzz extends java.applet.Applet
{
public void init()
{
resize(300,40);
}
}
All code in Java must
be written within functions. Hence we say that a class is a collection of
functions. Here we haven’t put the code of resize, instead we have given it the
parameters it requires and then put the semicolon. By doing so, we are calling
the resize function. The code within this function accepted the values and did
the needful to resize the window.
Thus, you can call a
function by specifying the function name, including the parameters and ending
it with a semicolon.
We didn’t explain
something in the earlier example and that is the function init. Now is the time
for it. We will also tell you what the words void and return mean. We created
the function by naming the function init and preceded it with the word void.
Void means nothing. Here, void is the return type. Return type indicates the
type of value the function will return. That means a function can return a
number or a string or something else entirely. So, what we are trying to say is
that since the init function is preceded with the word void it is not returning
any value. It is of significance to note that functions may or may not return
values.
In our program, we
have the words public and void preceding the function name. To understand this,
delete the word public. Your program should look as follows:
zzz.java
public class zzz extends java.applet.Applet
{
void init()
{
resize(100,400);
}
}
Run it and you will
surely see an error.
C:\javaprg>javac zzz.java
zzz.java:3: The method void init() declared in class zzz cannot override the method of the same signature declared in class java.applet.Applet.The access modifier is made more restrictive.
void init()
^
1 error
The error clearly
indicates that there is a function/method called init in java.applet.Applet and
we haven’t written it in the way it should have been in the class zzz. The init
in Applet has the word public and hence we have to make it public too. Rules...
remember? Now, public has to be called something, so why not call it a
modifier. If there is a function with the same name in the class from which you
are borrowing, they both have to have the same modifiers, otherwise, you can’t
override it.
Here, we have created
a function called init. We’ve created it because we are using the open and
close curly braces {}. Then we are calling a function called resize(). The
difference between creating and calling a function is that you call a function
using round brackets () and end with a semicolon but you create a function using curly braces {}.
We must write the word
public in front of init() or else others will not be able to use it or call it
and also because of the earlier error. You probably noticed that init(), though
it is a function, doesn’t have a semi-colon(;) following it. This is because
when we call a function we put a semicolon whereas when we create a function we
do not. Here we are creating a function called init().
Why do we have to
create a function called init? This is because when the appletviewer starts up,
it calls a function called init. If we have it in our code within the zzz class
then our init() gets called, otherwise, the one from java.applet.Applet gets
executed. In our earlier program, when we did not include ‘extends
java.applet.Applet’ we got an error. This was because one of the functions
appletviewer calls is init().
If you were to replace
the small ‘i’ in init() with a capital ‘I’, then the appletviewer will call the
init code in Applet and that code doesn’t do anything. As you can see Case
matters.
zzz.java
public class zzz extends java.applet.Applet
{
void Init()
{
resize(100,400);
}
}
We will now extend our
definition of a class by saying that a class is a collection of functions and
within functions you can call other functions.
Let us quickly
summarize what we have just learnt.
The appletviewer or
any java enabled browser calls init(). Since we included the code of init() in
zzz, our function was called. From our function init(), we called another
function, resize, which changes the size of the window. The code of resize is
in java.applet.Applet. So we now know how to call and create a function.
Let’s go one step
further and take a look at the next program.
zzz.java
public class zzz extends java.applet.Applet
{
public void init ()
{
System.out.println(“hi”);
}
}
Delete the resize
function and instead call another function System.out.println. This function
takes one parameter, which in this example is hi. Unlike numbers, strings must
be enclosed within double quotes.
On running this
program neither javac nor the appletviewer will complain. But nothing gets
displayed in the applet window either. Close the window and go back to dos, you
will see hi displayed on the screen.
C:\javaprg>javac zzz.java
C:\javaprg>appletviewer a.html
hi
System.out.println is
a function with a long name. It is like resize. The function ends with a semicolon
indicating that we are calling this function. The resize function can be called
as it is because it is found in java.applet.Applet which is a class made
available to us. System.out.println is also a function which is given to us by Java and hence using
it will not result in any error. This function takes a string as a parameter.
The next program says
System.out.println (”bye”+ii); it gives you an error saying that it does not
know what ii is.
zzz.java
public class zzz extends java.applet.Applet
{
public void init ()
{
System.out.println(”bye”+ii);
}
}
C:\javaprg>javac zzz.java
zzz.java:5: Undefined variable: ii
System.out.println(”bye”+ii);
^
1 error
We will now introduce
the concept of variables, an integral part of computer programming.
zzz.java
public class zzz extends java.applet.Applet
{
public void init()
{
int ii;
System.out.println(”bye”+ii);
}
}
This program includes
int ii; ii is a variable that looks like an int. int is the short form for
integer. int is a class just like Applet or zzz and is one which the java
compiler knows. All variables are stored in memory, they are words that hold or
store a value. To be able to refer to a vaiable, you have to give it a name. In
our program, we have named the variable ii.
Now that the variable
has been created it must be given a value otherwise you see the following
error..
C:\javaprg>javac zzz.java
zzz.java:6: Variable ii may not have been initialized.
System.out.println("bye"+ii);
^
1 error
So we give the
variable ii a value, 10 .
zzz.java
public class zzz extends java.applet.Applet
{
public void init ()
{
int ii;
ii=10;
System.out.println(“hi” + ii);
}
}
C:\javaprg>javac zzz.java
C:\javaprg>appletviewer a.html
hi10
What about the ‘+’
sign? The ‘+’ sign enables you to display the string ‘hi’ along with the value
of the variable ii. Hence the program displays hi10. The ‘+’ here does not mean
add, it means concatenate. Have you been wondering why these named memory
locations are called variables? They are called variables because their values
can vary.
The next program makes
it clear as to why variables are called variables.
zzz.java
public class zzz extends java.applet.Applet
{
public void init ()
{
int ii;
ii=10;
System.out.println(“hi” + ii);
ii=20;
System.out.println(“hi” + ii);
}
}
C:\javaprg>javac zzz.java
C:\javaprg>appletviewer a.html
hi10
hi20
In this program, ii is
assigned a value 10 initially. The first println displays hi10. Then the value
of ii is changed to 20. The second println prints out hi20.
zzz.java
public class zzz extends java.applet.Applet
{
public void init ()
{
int ii;
ii=10;
System.out.println(ii);
ii= ii +20;
System.out.println(“hi” + ii);
}
}
C:\javaprg>javac zzz.java
C:\javaprg>appletviewer a.html
10
30
In the above program,
initially ii has a value 10. println prints the value of ii ,which is 10.
Thereafter, we have ii= ii+20. Looks confusing, isn’t it! Whenever you see ‘=’,
always start by looking to the right of the sign. On the right we have ii+20.
You know that ii has a value 10, so this statement is read as 10+20. This
evaluates to 30 and is given to the variable on the left side of the ‘=’ sign
i.e. ii. So the value 30 is stored in ii. println will now display 30.
Thus, a variable is a
word in which you store a value and its value can change. Where ever you use a
variable you can use a number and wherever you use a number you can replace it
with a variable.
int is commonly
referred to as a datatype but in Java it is called a class. zzz is also a class. A class can now be
redefined as a collection of variables and functions.
Just as we had created
our own function init, we create pqr. This function contains the line
System.out.println(“hi”); Hence when pqr is called from init, hi is displayed.
zzz.java
public class zzz extends java.applet.Applet
{
public void init ()
{
pqr();
}
public void pqr()
{
System.out.println(“hi”);
}
}
C:\javaprg>javac zzz.java
C:\javaprg>appletviewer a.html
hi
We now create one more
function named xyz. We are now calling the function xyz from the function pqr.
zzz.java
public class zzz extends java.applet.Applet
{
public void init ()
{
pqr();
}
public void pqr()
{
xyz();
}
public void xyz()
{
System.out.println(“In xyz”);
}
C:\javaprg>javac zzz.java
C:\javaprg>appletviewer a.html
In xyz
In the above program,
the pqr function is calling the function xyz. The xyz function has a println,
which displays “In xyz”.
But you cannot have
xyz call pqr as it will go into an indefinite loop .
Our next program
passes a value to the function pqr.
zzz.java
public class zzz extends java.applet.Applet
{
public void init ()
{
pqr(200);
}
public void pqr(int z)
{
System.out.println(“hi”+z);
}
}
C:\javaprg>appletviewer a.html
hi200
This program shows how
parameters or values are passed to functions.
Here, the value 200 is being passed to the function pqr. The function
pqr receives it in int z. What is z? It
looks like an int. Actually, we are creating a variable called z, which will
store the value passed to pqr. Variables can be called by any name. Earlier we
used a variable ii and now we are using z. You could have called it ‘x’, the
choice is yours! z is also called a parameter.
System.out.println is used to display the value.
Our next program has a
function called paint. It takes a value Graphics g. Just like the function pqr
had a parameter z that looked like int, here g is a parameter which looks like
Graphics. To put it a little more technically, we can say that paint and pqr
are both called with one parameter.
zzz.java
public class zzz extends java.applet.Applet
{
public void paint (Graphics g)
{
System.out.println(“hi”);
}
}
We did not create
Graphics; it is available to us free. That’s what we are assuming. Run javac
and you will get an error.
C:\javaprg>javac zzz.java
zzz.java:3: Class Graphics not found.
public void paint ( Graphics g)
^
1 error
You have already come
across similar errors. The name is not Graphics; it is java.awt.Graphics. The
best way to learn a language is to speak it! Speak big names! Write big names!
Change Graphics to java.awt.Graphics and you don’t get an error, everything
seems fine, but you don’t see anything on the screen either.
zzz.java
public class zzz extends java.applet.Applet
{
public void paint ( java.awt.Graphics g)
{
}
}
When it comes to
speaking, we do so readily but most of us shirk writing. Keeping that in mind,
we will use Graphics to make it concise but will also introduce a new statement
as in import java.awt.* with a semicolon
zzz.java
import java.awt.*;
public class zzz extends java.applet.Applet
{
public void paint ( Graphics g)
{
}
}
‘*’ implies
everything. Note that the semicolon is a part of its syntax. Import does a
search and a replace. Since writing the entire class name is tedious, whenever
it sees the name of a class it adds java.awt. So it adds java.awt to every
classname that gives an error. It will not add to java.applet.Applet because it
didn’t give an error. So Graphics automatically becomes java.awt.Graphics.
Let’s do the same thing for Applet. So we
now have two imports.
zzz.java
import java.awt.*;
import java.applet.*;
public class zzz extends Applet
{
public void paint ( Graphics g)
{
}
}
The first thing that
the compiler does is tries Applet as java.awt.Applet. It realizes that it still
gives an error. It then tries as java.applet.Applet and realizes that the error
is removed. Basically, the order doesn’t matter. If you prefer using short
names, then you will have to use the import statements.
Thus, you could write
the longest of programs without using the word import. But the only problem is
that your hands will get very tired. Java gave us a problem by giving us long
names but at the same time provided a solution to it by giving the import
statement.
In the next example,
we have included two import functions and a single paint function. The paint
function calls g.drawString.
zzz.java
import java.awt.*;
import java.applet.*;
public class zzz extends Applet
{
public void paint ( Graphics g)
{
g.drawString(“Hi”);
}
}
As of now, we will ignore
what the dot in drawString really means. With the knowledge you have already
gathered, it must be clear to you that drawString is a function ( ) and ends
with a semicolon. Thus, in effect, we are calling a function. On running the
program, you will get an error saying ‘drawString has wrong number of
arguments’.
C:\javaprg>javac zzz.java
zzz.java:7: Wrong number of arguments in method.
g.drawString(“Hi”);
^
1 error
Arguments and
parameters are words that can be used interchangeably. Similarly, functions are
analogous to methods.
This is why people
like programming in Java. You are like a child and Java the mother. You make a
mistake and you get a spanking! Drawstring must be called with a certain number
of parameters. Goof up and you get errors!
If you are feeling
sleepy and you are not drinking coffee, you can’t write code in Java ;-)
Let’s analyze the
reason behind the error. In order to draw a string you must state at what
location on the screen the string is to be displayed. That would mean providing
3 parameters. The first is the string followed by the x and the y coordinates.
Rewrite this function with the new set of parameters- “Hi”, 5, 50. The
x-coordinate and the y-coordinate are 5 and 50 respectively.
zzz.java
import java.awt.*;
import java.applet.*;
public class zzz extends Applet
{
public void paint ( Graphics g)
{
g.drawString(“Hi”,5,50);
}
}
NOTE: In dos, the character-based screen is
divided into 80 characters and 25 lines. In a graphical user interface, the
screen is divided into dots called pixels. It is commonly referred to as
resolutions. The costlier the monitor and the video card, the better the
resolution!! The resize function and the width and height attributes in the tag
applet need their parameters to be pixels .
Run the appletviewer.
You will see Hi displayed at 5, 50 i.e. (x, y) in the applet window.
The paint function
gets called every time Windows wants to redraw the screen and we can’t tell in
advance how many times that is going to happen.
zzz.java
import java.awt.*;
import java.applet.*;
public class zzz extends Applet
{
public void paint ( Graphics g)
{
int ii;
ii=5;
g.drawString(“Hi”,ii,50);
}
}
Once again, just to
revise the concept of variables, use int ii and initialize ii to 5. In the
drawString, instead of giving 5, put ii. This is the first use of a variable;
you can place it wherever there is a number.
In the next example,
as a re-revision, we have put two drawStrings and changed ii by saying ii = ii
+ 20 and given drawString again.
zzz.java
import java.awt.*;
import java.applet.*;
public class zzz extends Applet
{
public void paint ( Graphics g)
{
int ii;
ii=5;
g.drawString(“Hi”,ii,50);
ii=ii + 20;
g.drawString(“Hi”,ii,50);
}
}
The first drawString
displays the string at 5 and the second
at 5+20 ie 25.
zzz.java
import java.awt.*;
import java.applet.*;
public class zzz extends Applet
{
public void init()
{
int ii;
}
public void paint ( Graphics g)
{
ii = 5;
g.drawString(“Hi”,ii,50);
}
}
In the init function
we are creating a variable ii and in paint we are initializing it to 5. The
Java compiler, at this stage, will give an error.
C:\javaprg>javac zzz.java
zzz.java:11: Undefined variable: ii
ii = 5;
^
zzz.java:12: Undefined variable: ii
g.drawString(“Hi”,ii,50);
^
2 errors
You get these
errors because variables in one
function are not accessible in another function. Variables, by default, are
local. Local variables are only available to the function in which you have
created them. So ii is available only in init. It has a short life. It is alive
only between the ‘{‘ and the ‘}’ brackets. If you want all functions in a class
to access the variable, the only option is to place it outside the function.
zzz.java
import java.awt.*;
import java.applet.*;
public class zzz extends Applet
{
int ii;
public void init()
{
ii = 100;
}
public void paint ( Graphics g)
{
ii = 5;
g.drawString(“Hi”,ii,50);
}
}
A variable when placed
outside the function is called a public variable. Every function in the class
can access a public variable. Hence we don’t get any errors in the above
program. The init function changes the value of ii to 100. Paint changes it to
5. Finally, what gets displayed is the last one and that is 5. So you see Hi on
the top of the screen at 5,50 and not at 100,50. If you remove the line ii=5
from paint then ii will retain the value 100.
There is a subtle
difference between System.out.println and drawString in terms of displaying a
variable with a string. The only difference is that println draws in the dos
box and drawString writes in your graphics screen. In the following program, we
have used the same ‘+’ and displayed the value of the variable with hi. A
variable can be used constantly. That means you can use it multiple times on
the same line or in the same function. This program outputs Hi5 on top of the
screen at 5,50.
zzz.java
import java.awt.*;
import java.applet.*;
public class zzz extends Applet
{
int ii;
public void init()
{
ii = 200;
}
public void paint (Graphics g)
{
ii = 5;
g.drawString(“Hi “+ii,ii,50);
}
}
The next example will
strengthen your understanding of the concept of public variables. Again, we
have declared ii as a public variable.
zzz.java
import java.awt.*;
import java.applet.*;
public class zzz extends Applet
{
int ii;
public void init()
{
ii = 20;
pqr();
}
public void paint (Graphics g)
{
g.drawString(“Hi “+ii,ii,50);
}
public void pqr()
{
ii = 80;
}
}
In init, the variable
ii is initialized to a value 20. Then the function pqr is called. pqr
reinitializes ii to 80. Hence in paint, the value displayed with Hi is 80.
In the next example,
we will pass the public variable ii as a parameter to the function pqr()
zzz.java
import java.awt.*;
import java.applet.*;
public class zzz extends Applet
{
int ii;
public void init()
{
ii = 40;
pqr(ii);
}
public void paint (Graphics g)
{
g.drawString(“Hi “+ii,ii,50);
}
public void pqr(int jj)
{
ii = jj + 20;
}
}
The public variable ii
is initialized to 40 by init. Then pqr is called with one parameter i.e. ii. In
the pqr function, the value of ii, which is 40, is stored in jj. jj + 20
increases the value to 60 which is assigned to ii. In paint, ii will display
its value as 60. A program can be made as complicated as you like. But if we
had replaced the line ii = jj + 20 with jj = ii + 50 , then changing jj does
not change ii.
zzz.java
import java.awt.*;
import java.applet.*;
public class zzz extends Applet
{
int ii;
public void init()
{
ii = pqr();
}
public void paint (Graphics g)
{
g.drawString(“Hi “+ii,ii,50);
}
public int pqr()
{
return 80;
}
}
This program is
getting very interesting! ii is a public variable available to all. Instead of
passing ii as a parameter to the pqr function, we say ii=pqr();. Here pqr is a
function, which is public. If you notice, instead of void, this function returns
an int. Previously, we used void, implying that the function did not return a
value. The pqr function now returns 80. The return value of pqr is stored in
ii. It returns a value using the statement return 80. 80 is the value that will
be given to ii. This is how functions return values. By saying return 80 all
that happens is that pqr() gets replaced by 80, the return value.
More on the return statement...
zzz.java
import java.awt.*;
import java.applet.*;
public class zzz extends Applet
{
int ii;
public void init()
{
ii = pqr();
}
public void paint (Graphics g)
{
g.drawString(“Hi “+ii,ii,50);
}
public int pqr()
{
return 80;
ii = 200;
}
}
javac gives the
following error.
C:\javaprg>javac zzz.java
zzz.java:14: Return required at end of int pqr().
public int pqr()
^
zzz.java:17: Statement not reached.
ii = 200;
^
2 errors
After the word return,
we have included one more line i.e. ii=200. Return is an end to a piece of
code. No lines of code are executed after the return statement. Most of the
other programming languages don’t give an error, but Java is different in its
ways. In Java, you cannot write any code after the return statement.
zzz.java
import java.awt.*;
import java.applet.*;
public class zzz extends Applet
{
int x,y;
public void init()
{
x = 10 ; y = 20;
}
public void paint ( Graphics g)
{
g.drawString(“Hi “, x , y);
}
public boolean mouseDown(Event e, int x1 , int y1)
{
}
}
In the above program,
we have added one more function named mouseDown. This function returns a boolean
value. Boolean is a logical value, either true or false. mouseDown is called
with 3 parameters; Event e, int x1 and int y1 are the three parameters. x1 and
y1 are two variables of type int and e looks like Event. On compiling the
program, you will get the following error:
C:\javaprg>javac zzz.java
zzz.java:14: Return required at end of boolean mouseDown(java.awt.Event, int, int).
public boolean mouseDown(Event e, int x1 , int y1)
^
Note: zzz.java uses or overrides a deprecated API. Recompile with “-deprecation “ for details.
1 error, 1 warning
Here, mouseDown
returns a boolean, but in our code we have no return statement with a true or a
false, hence the error. If a function has a return value other than void then
it must return a value. You can return either true or false, it doesn’t really
matter, as long as you return a boolean value.
Let’s look at another
version of this example.
zzz.java
import java.awt.*;
import java.applet.*;
public class zzz extends Applet
{
int x,y;
public void init()
{
x = 10 ; y = 20;
}
public void paint ( Graphics g)
{
g.drawString(“Hi “, x , y);
}
public boolean mouseDown(Event e, int x1 , int y1)
{
x = x1 ; y = y1;
return true;
}
}
In this example, the
mouseDown function returns true. Alternatively, you can return false instead of
true. As long as you return a boolean value, your program will work fine. In
this program, it doesn’t matter whether you return true or false but in other
cases it may matter as to what mouseDown returns. x and y are two public variables.
You can create them separately by saying int x; int y; But when you want to
create 20 variables it is easier saying int x,y,z,a,b,... all at a stretch. It
is an alternative method, where we use ‘,’ as a separator.
The compiler will
display a warning which can be ignored.
The init function
initializes x and y to 10 and 20 respectively. g.drawString takes the values 10
and 20 for x and y. Now run your program using the appletviewer.
Click with the mouse
in the window. Stop clicking! As of now nothing happens. Now minimize the
window and then maximize it. Surprisingly, you see hi at the location where you
clicked or where you last clicked.
Let’s understand what
this means.
The mouseclick in the
window was trapped by the mouseDown function. The parameters x1 and y1 tell you
where the mouse was clicked. e, which is an object that looks like Event, tells
us how we clicked. How we clicked? Aren’t all mouse clicks the same? Actually,
they aren’t because not only can we click, but we can click with the control
key or the shift key depressed and so on. Event will give us information as to
whether these keys were pressed while we clicked. We will not go into further
details regarding this as ours is but a simple click.
Before the mouseDown
returns true, x and y are initialized to x1 and y1, which represent the
location where the mouse was clicked. They are public variables and are thus
accessible from within the mouseDown function too. On minimizing and maximizing
the window, paint gets called with the new values. Hence you see hi at a
different position; the position where you clicked.
Unless the window is
not minimized and maximized, the paint function doesn’t get called. It gets
called either at the start or when the window has to be redrawn. To demonstrate
this, we will now call paint through another function called repaint which
exists in the Applet class.
zzz.java
import java.awt.*;
import java.applet.*;
public class zzz extends Applet
{
int x,y;
public void init()
{
x = 10 ; y = 20;
}
public void paint ( Graphics g)
{
g.drawString(“Hi “, x , y);
}
public boolean mouseDown(Event e, int x1 , int y1)
{
x = x1 ; y = y1;
repaint();
return true;
}
}
The repaint function calls paint and hence the ‘hi’ follows the mouse click. Make sure that every time you make changes to your code, you compile it again using javac, and then run the appletviewer.
zzz.java
import java.awt.*;
import java.applet.*;
public class zzz extends Applet
{
int ii = 0;
public void paint (Graphics g)
{
ii++;
g.drawString(“Hi “+ii,5,50);
}
}
In the above program,
the value of ii increases every time the function paint gets called. i++ can
also be written as i=i+1. When you run the program, initially the value of the
variable will be 1 because paint gets called once. When you minimize and
maximize the window, paint gets called. Now click the restore button to restore
the window back to its original size. Now paint gets called twice. We cannot
really decide when and who calls paint. Whenever Microsoft Windows realizes
that your window needs to be redrawn, it calls paint. It can call paint once or
it can call paint 20 times. The important point to note is that it is only
through paint that you can write to the screen.
zzz.java
import java.awt.*;
import java.applet.*;
public class zzz extends Applet
{
int ii = 0;
public void paint (Graphics g)
{
g.drawString(“Hi “+ii,5,50);
}
public boolean mouseDown(Event e, int x1 , int y1)
{
ii++;
repaint();
return true;
}
}
In the above program,
each time you click in the window, repaint gets called. But before doing that,
the value of ii is incremented by 1. ii is a public variable hence you see the
value change.
Every program should
have some sort of intelligence built into it. A programming language offers
features that make the program more intelligent and more generic. Our program
doesn’t have such features as yet. This is because we haven’t given it the
ability to decide whether a certain piece of code should be executed or not. We
will use the next program to demonstrate this.
zzz.java
import java.awt.*;
import java.applet.*;
public class zzz extends Applet
{
int ii = 0;
public void paint (Graphics g)
{
if ( true )
g.drawString(“Hi “+ii,5,50);
}
public boolean mouseDown(Event e, int x1 , int y1)
{
ii++;
repaint();
return true;
}
}
In this program, we
have included the word ‘if’ followed by true in round brackets. When you run
this program, you realize that it’s output is no different from that of the
previous program.
Now change the ‘true’
to ‘false’ as shown below. You will observe that g.drawString doesn’t get
called at all. You will see a blank screen.
zzz.java
import java.awt.*;
import java.applet.*;
public class zzz extends Applet
{
int ii = 0;
public void paint (Graphics g)
{
if ( false )
g.drawString(“Hi “+ii,5,50);
}
public boolean mouseDown(Event e, int x1 , int y1)
{
ii++;
repaint();
return true;
}
}
Let’s understand the
reason behind it. The if statement lets you include decision making in your
program. It decides whether to execute the next line or not. When the if
statement evaluates to true, it executes the next line. When it evaluates to
false, the next line is skipped. This program now has the ability to either
execute or not execute a piece of code.
The following program
will make this concept clearer.
zzz.java
import java.awt.*;
import java.applet.*;
public class zzz extends Applet
{
int ii = 0;
public void paint (Graphics g)
{
if ( ii >= 3 )
g.drawString(“Hi “+ii,5,50);
}
public boolean mouseDown(Event e, int x1 , int y1)
{
ii++;
repaint();
return true;
}
}
ii is a variable which
increments by 1 when you click in the window. The mouseDown function calls
repaint which inturn calls paint. In paint, the if condition checks whether the
value of ii is greater than or equal to 3. When you click within the window for
the first time, the value of ii will be 1, so the if condition is now read as
(1 >=3). Since the condition is false, the if statement becomes if (false).
As we have seen in the earlier program, if the if statement evaluates to false,
it ignores the next line. So hi is not displayed on the screen. The third click
will initialize ii to 3. Since 3 = 3, the if condition becomes true and hi is
displayed along with 3 on the screen.
This is how, depending
on certain conditions, you can decide whether code should be called or not.
To understand > or
< try out the next program. > and + - * are all called operators.
zzz.java
import java.awt.*;
import java.applet.*;
public class zzz extends Applet
{
public void init()
{
Sysetm.ou.println(3>8);
Sysetm.ou.println(8>3);
}
}
In the next program,
after the if statement, two drawString functions are called and passed Hi and
Bye respectively.
zzz.java
import java.awt.*;
import java.applet.*;
public class zzz extends Applet
{
int ii = 0;
public void paint (Graphics g)
{
if ( ii >= 3 )
g.drawString(“Hi “+ii,5,50);
g.drawString(“Bye “+ii,5,100);
}
public boolean mouseDown(Event e, int x1 , int y1)
{
ii++;
repaint();
return true;
}
}
Here, each time you
click in the window Bye gets displayed on the screen but Hi gets displayed only
after the 3rd click. This implies that the if condition works only for the next
line i.e. it either ignores or executes the next line. The rest of the code is
beyond its control. If you want multiple statements to be affected by the if
statement use curly braces ‘{}’. Now include both the drawString functions
within curly braces.
zzz.java
import java.awt.*;
import java.applet.*;
public class zzz extends Applet
{
int ii = 0;
public void paint (Graphics g)
{
if ( ii >= 3 )
{
g.drawString(“Hi “+ii,5,50);
g.drawString(“Bye “+ii,5,100);
}
}
public boolean mouseDown(Event e, int x1 , int y1)
{
ii++;
repaint();
return true;
}
}
In this program, after
the third click both the drawStrings get executed. Both ‘Hi’ and ‘Bye’ are
displayed only after the third click.
You can try the same
code with different operators like
<, >, <=, >=
Example:
if (i >3) , if (i<3), if(i <=3), if (i >=3)
Let’s try this program
using the ‘=’ operator.
if( ii = 3 )
This will give you an
error.
C:\javaprg>javac zzz.java
zzz.java:8: Incompatible type for if. Can’t convert int to boolean.
if ( ii = 3 )
^
Note: zzz.java uses or overrides a deprecated API. Recompile with “-deprecation “ for details.
1 error, 1 warning
This results in an
error because a condition should result in a logical value i.e. it must be a
boolean value. Here ‘=’ is assigning a value 3 to ii, it is not
asking whether ii is
equal to 3 or not. The ‘=’ attempts to assign ii a new value.
Using ‘==’ solves this
problem. The if statement now becomes if (ii == 3). When you run the program,
click slowly because the if condition will evaluate to true only once.
zzz.java
import java.awt.*;
import java.applet.*;
public class zzz extends Applet
{
int ii = 0;
public void paint (Graphics g)
{
if ( ii == 3 )
{
g.drawString(“Hi “+ii,5,50);
g.drawString(“Bye “+ii,5,100);
}
}
public boolean mouseDown(Event e, int x1 , int y1)
{
ii++;
repaint();
return true;
}
}
The ‘==’ compares ii
with a certain value. You may not want a certain piece of code to be executed
if the variable meets a certain value. In such a case use !=, the ‘not equal
to’ operator. The following program supports this statement.
zzz.java
import java.awt.*;
import java.applet.*;
public class zzz extends Applet
{
int ii = 0;
public void paint (Graphics g)
{
if ( ii != 3 )
{
g.drawString(“Hi “+ii,5,50);
g.drawString(“Bye “+ii,5,100);
}
}
public boolean mouseDown(Event e, int x1 , int y1)
{
ii++;
repaint();
return true;
}
}
The drawString
functions are called for all values of ii except 3. The next program reveals
how a condition can be reversed.
zzz.java
import java.awt.*;
import java.applet.*;
public class zzz extends Applet
{
int ii = 0;
public void paint (Graphics g)
{
if ( ! ( ii >= 3) )
{
g.drawString(“Hi “+ii,5,50);
g.drawString(“Bye “+ii,5,100);
}
}
public boolean mouseDown(Event e, int x1 , int y1)
{
ii++;
repaint();
return true;
}
}
‘!’ allows you to
negate a condition. !( ii >= 3), is the same as (ii < 3). You can use two
different approaches to do the same thing, either say if (ii < 3) or if (! (
ii>=3)).
In the previous
examples, if the condition was true, code was executed and when false, nothing
happened. You probably felt limited, because it only lets you execute a
statement when the condition is true. The next example takes care of this,
showing us how to use an else with our if. The additional else statement will
execute the code following it only when the if condition evaluates to false.
zzz.java
import java.awt.*;
import java.applet.*;
public class zzz extends Applet
{
int ii = 0;
public void paint (Graphics g)
{
if ( ii <= 3)
g.drawString(“Hi “+ii,5,50);
else
g.drawString(“Bye “+ii,5,20);
}
public boolean mouseDown(Event e, int x1 , int y1)
{
ii++;
repaint();
return true;
}
}
If the condition ii
<= 3 evaluates to true then Hi will be displayed, otherwise, Bye will be
displayed.
The next program will
show you how you can use the if statement intelligently.
zzz.java
import java.awt.*;
import java.applet.*;
public class zzz extends Applet
{
int ii = 0;int a,b,c,d;
public void paint (Graphics g)
{
g.drawLine(a,b,c,d);
}
public boolean mouseDown(Event e, int x1 , int y1)
{
if ( ii == 0)
{
a = x1; b = y1;
ii = 1;
}
else
{
c = x1 ; d = y1;
ii = 0;
repaint();
}
return true;
}
}
In this program, the
variable ii is initialized to 0. The mouseDown function facilitates the
trapping of the mouse click. The if condition is used in the mouseDown
function. If the condition evaluates to true i.e. if ii is equal to 0, the
click positions which are stored in x1 and y1 are assigned to the public
variables a and b respectively. After that, ii is initialized to 1. With the
second click the code for else is called. The click positions are given to a
different set of public variables i.e. c and d. ii is then reinitialized to 0.
Then the repaint() indirectly calls paint. The paint function calls the
drawLine function which belongs to the Graphics class. drawLine takes 4
parameters, the first two determine where the line begins and the next two fix
the end of the line.
In a nutshell, the
first click calls code initializing the variables a and b. With the second
click the variables c and d are initialized. Thus, clicking twice draws a line
between the two clicks.
Conclusion
In this chapter, we
have seen how Java has taken the entire on-line world by storm. We have seen
how Java applets are embedded in the HTML pages. We showed you variations of
programs right from a simple Java applet to more complex ones. This was done
using various combinations of operators in the if statement and some basic
functions. These together with the concept of objects and classes were used to
introduce to you the concept of object-oriented programming and what Java as a
programming language has in store for us.