Introduction

 

Java, whether you love it, or hate it, is here to stay and it is claimed to have taken the entire cyber world by storm. Like everyone's favorite language C, Java too has made an ever-lasting impression in the software industry. Therefore, when the history of computers will be written, its name will be up there with the stars. It's being pushed aggressively by Sun and is growing by leaps and bounds. There are many Java programmers out there with more joining the party every day.

 

Java started out as a bit of an accident. A team under Bill Joy was working at Sun on a new programming language for embedded applications. Java was originally expected to work in toasters and fridges, not on modern computers! The initial prognosis for Java was not good and it was only the rise of the Internet, which saved Java from oblivion. Since then, neither the Net, Sun nor Java has looked back and all have grown from strength to strength.

 

We start off assuming that you have no knowledge of any programming language at all. We're going to be teaching you features of Java but one concept at a time and would like to take things real slow and easy. We believe that the best way to learn is to try and absorb just one concept at a time. We're here to help you learn, not to overwhelm you. We like the concept of freedom, especially when it comes to information. We've occasionally picked up ideas for our examples from programs we've found online or in the product documentation. We've got information from so many sources, we can't credit them all, but we are grateful to them. In turn, we'd like you to use the code you'll find within in any way you wish.

 

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++.

 

While surfing the Internet, the browser enables you to view web pages. However, technically, the browser connects to a web server and requests for an html page.

 

Prior to the inception of Java, the downloaded file contained no intelligence. In a sense, the web page was static. But not for long, since Sun Microsystems resolved the 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.

 

With this briefing on the origin of Java, let us start on our journey to unfold the features of this language.

 

JAVA, The Programming Language

 

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 syntax. Also, Java as a language has taken a lot from C++, therefore any coder well conversant with the C++ way of coding will be able to adapt to this new language effortlessly.

 

The java sdk can be downloaded off the net from the Sun website : http://java.sun.com. Since our focus will be on the use of Java where it is most prevalent today, the server, download the Enterprise Edition of Java. (J2EE 1.4 SDK) which is approx 110 MB large.

 

As per the installation guide,

Once the file is successfully downloaded, install it on your windows machine. The installation will create a subdirectory Sun in C: and a program group in the start menu option – Programs – Sun Microsystems

 

We will not get into the nitty-gritty of the installation at the moment and leave things as they are. Start off with coding our very first java program.

 

Create a sub directory called javaprg in C:\ to save all your files and open any text editor to key in the following program

 

c:\javaprg>edit z.java

 

z.java

class zzz

{

}

 

Once done, save the file. 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 identified by its name and represents a collection of entities. In this program, we have named the class as zzz. In case you are sleepy, you might think of it as a snore, in that case, change the name to awaken. 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 clubbing various things. 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 classname and then the '{' 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.

 

The code entered in z.java is in text format, which has to be converted to machine language before being executed. The task of converting a text file into its binary form is that of the compiler. So we now need to run this smallest Java program through a Java compiler, which in the Java programming language is called javac. Javac is part of the Java Software Development Kit that comes bundled with J2EE.

 

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:\Sun\AppServer\jdk\bin;%PATH%

 

C:\javaprg>dir

 Directory of C:\javaprg

 

06/18/2004  04:44p      <DIR>          .

06/18/2004  04:44p      <DIR>          ..

04/06/2004  01:59p                  17 z.java

04/06/2004  01:59p                 178 zzz.class

 

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. For the compiler, the class name is of significance hence 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. A java program executing in a browser is called an applet. 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, which is used to embed an applet in an HTML page. To understand this better, create a file called a.html using a text editor with the following text.

 

a.html

<applet code=zzz.class></applet>

 

What does this mean? <applet> is a tag and </applet> indicates the end of it. The word following the tag is called an attribute, thus code is an attribute to the applet tag, which requires the name of the class file in which the code resides, zzz.class. You can simply write zzz, instead.

 

Html files are best viewed using a browser, however, there is a possibility that you may have neither Internet Explorer nor the Netscape browser. Not only did Sun consider this possibility but also when they first released java there were no browsers that supported it. So, bundled with the SDK comes a test browser called appletviewer that can execute only java applets. At the command prompt, type appletviewer a.html

 

C:\javaprg>appletviewer a.html

Warning: <applet> tag requires width attribute.

 

The appletviewer comes 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 appletviewer as in

C:\javaprg>appletviewer a.html

Warning: <applet> tag requires height attribute.

 

The appletviewer now 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.

 

C:\javaprg>appletviewer a.html

load: zzz.class is not public or has no public constructor.

java.lang.IllegalAccessException: Class sun.applet.AppletPanel can not access a

member of class zzz with modifiers ""

        at sun.reflect.Reflection.ensureMemberAccess(Reflection.java:57)

        at java.lang.Class.newInstance0(Class.java:302)

        at java.lang.Class.newInstance(Class.java:261)

        at sun.applet.AppletPanel.createApplet(AppletPanel.java:617)

        at sun.applet.AppletPanel.runLoader(AppletPanel.java:546)

        at sun.applet.AppletPanel.run(AppletPanel.java:298)

        at java.lang.Thread.run(Thread.java:534)

 

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. And, nobody is granted access to anything that is private. 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

{

}

 

Then,

 

C:\javaprg>javac z.java

z.java:1: class zzz is public, should be declared in a file named 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! The rationale here is that once the .class file is created, 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

 

and then

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

        at sun.applet.AppletPanel.createApplet(AppletPanel.java:617)

        at sun.applet.AppletPanel.runLoader(AppletPanel.java:546)

        at sun.applet.AppletPanel.run(AppletPanel.java:298)

        at java.lang.Thread.run(Thread.java:534)

 

Here it shows you a different error, ClassCastException

 

These lines just don't make sense!, that’s why this book. You may read from up or from bottom, it still is greek and latin. 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 simply program code. More on this just two programs later.

 

A class consists of functions. The appletviewer has been told to call certain functions in the .class file or lets say, appletviewer expects the applet to have some code or functions in it. Unfortunately, these functions are not available in our file as the class in the program is empty and hence the error.

 

To avoid adding all that code required by the appletviewer manually, we take a simpler route by picking an existing class supplied by Sun comprising of these functions. This 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

{

}

 

The word extends signifies that if the class Applet contains 20 functions, then they would get added to class zzz. It is like physically keying all of them yourself. Now let's run javac once again.

 

C:\javaprg>javac zzz.java

zzz.java:1: cannot resolve symbol

symbol  : class Applet

location: class zzz

public class zzz extends Applet

                         ^

1 error

 

The error messages seem to get vague with every new version of the software product. In the early release of java, the message was

 

zzz.java:1: Superclass Applet of class zzz not found.

public class zzz extends Applet

^

1 error

 

which was a lot more descriptive. The explanation given then was

 

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 will stick to the above explanation for now as understanding symbols in a class file for a newbie would be very strenuous.

 

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' at the bottom of the window.

 

Ha!!!

 

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' expected

public Class zzz extends java.applet.Applet{}

       ^

1 error

 

Slight ignorance and be ready to call for aspirins.

 

 Well, be on your guard and don't say we didn't warn you.

 

Now, we move towards understanding functions with the help of this program

 

zzz.java

public class zzz extends java.applet.Applet

{

public void init()

{

resize(300,40)

}

}

 

A function is nothing but code or collection of program statements. We are well aware that there is a function called resize in the Applet class. In order to call a function, you need the function name, which in our case 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.

 

Java is one more programming language like C and C++. Moreover, Java is a wholesale copy from C and C++. It retains the use of round brackets for functions. Along the way you will observe that  C++ and Java are very similar. If you know one of them then shifting 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

 

The ')' marks the end of the function logically but seems to be very ambiguous 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 simply copies it.

 

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 parameters it requires and then ended it with a semicolon. In this manner, 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 the init function in the previous example because it would be too early to divulge into functions. Now is the time for it. We will also explain the words void and return.

 

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 be prepared to see an error.

 

C:\javaprg>javac zzz.java

zzz.java:3: init() in zzz cannot override init() in java.applet.Applet;

attempting to assign weaker access privileges; was public

void init()

     ^

1 error

 

The error clearly indicates that there is a function/method called init in java.applet.Applet and in zzz, we haven't written it in the way it should be. The init in Applet has the word public and hence we have to make it public too. Rules... remember?

 

The word ‘public’is termed as a modifier. If there exists a function with the same name in the class from which you are borrowing, they both must have the same access privileges, otherwise, you can't override it.

 

In class, we have created a function called init by using the open and close curly braces {}. Within this function, the resize() is being called. 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. Besides, the function in the base class has the modifier public preceding it. 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. But if the class is not extended from java.applet.Applet, an error is due to be reported since there is no trace of init function anywhere.

 

Nevertheless, if you were to replace the small 'i' in init() with a capital 'I', then the appletviewer will call the init code in the Applet class bypassing your code completely. So, you see Case matters.

 

zzz.java

public class zzz extends java.applet.Applet

{

void Init()

{

resize(100,400);

}

}

 

We will now extend the 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(). It there exists an init() in zzz, then it is executed otherwise the one from Applet gets called. From our init(), we called another function, resize, which changes the size of the window. The code of resize is in java.applet.Applet.

 

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.

 

Neither javac nor the appletviewer complains on the newly inserted code, however 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

 

Dos Output

hi

 

System.out.println is a function very similar to resize other than having a long name. The function ends with a semicolon indicating that it is being called. Like the resize function whose code was made available through the Applet class, System.out.println is a function whose code is provided by Java. This function takes one parameter of type String.

 

The next program is modified a bit with the function taking the parameter as "bye"+ii. This change is not acceptable hence an error reporting complete ignorance on ii.

 

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: cannot resolve symbol

symbol  : variable ii

location: class zzz

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, a short form for integer.

 

int is a class just like Applet or zzz which is recognized by the java compiler. All variables are words that are identified by a name and hold or store a value. Besides, they are given definite space in memory.

 

Once the variable is created, it must be given a value otherwise you see the following error.

 

C:\javaprg>javac zzz.java

zzz.java:6: variable ii might 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 of 10 initially. Therefore, the first println displays hi10. Then the value of ii is changed to 20. As a result, 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

hi30

 

In the above program, initially ii has a value 10. The println function 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; 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, which holds a value and its value can change. Wherever a variable is used, it can be replaced with a number and vice-versa.

 

int is commonly referred to as a datatype but in Java it is called a class. zzz is also a class. So, now we can broaden the definition of a class to be a collection of variables and functions.

 

Similar to the init function, a user-defined function called pqr is created with a single line of code, 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 that will be called from the pqr function.

 

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 calls the function xyz. The xyz function has a println, which displays "In xyz".  On the other hand, having xyz call pqr  will lead to an indefinite loop .

 

Our next program passes a value to 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. Similar to function pqr that had a parameter z of type int, here g is a parameter that looks like Graphics. Technically, paint and pqr are functions both called with one parameter.

 

zzz.java

public class zzz extends java.applet.Applet

{

public void paint (Graphics g)

{

System.out.println("hi");

}

}

 

The Graphics type, like int, comes bundled in Java. That's what we are assuming. However, javac posts an error.

 

C:\javaprg>javac zzz.java

zzz.java:3: cannot resolve symbol

symbol  : class Graphics

location: class zzz

public void paint (Graphics g)

                   ^

1 error

 

This error has been revisited. The name is not Graphics; it is java.awt.Graphics. Change Graphics to java.awt.Graphics and everything seems fine, but you don't see anything on the screen either. The best way to learn a language is to speak it! Speak big names! Write big names!

 

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 any name of a class it adds java.awt. So it adds java.awt to every classname that gives an error. But, it does not add to java.applet.Applet because no errors are reported. So Graphics automatically becomes java.awt.Graphics. Let's do the same thing for Applet. 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 names Applet as java.awt.Applet. It detects an error, therefore it names it as java.applet.Applet and tries to wipe it out.

 

Basically, the order doesn't matter. If you prefer using short names, then use the import statements.

 

Thus, you could write the longest of programs without using the word import but it tends to get tiresome. Java gave us a problem in having long names but at the same time provided a solution by introducing the import statement.

 

In the next example, we have included two import functions and a single paint function. The paint function calls another function 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: cannot resolve symbol

symbol  : method drawString (java.lang.String)

location: class java.awt.Graphics

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 make one mistake and it gets reported instantly! Goof up and you get errors! It is evident that drawString takes a certain number of parameters.

 

Let's analyze the reason behind the error. In order to draw a string, you must state the position on screen for the string to be displayed. That would mean providing 3 parameters. The first is the string followed by the x and the y coordinates. Drawstring takes 3 parameters to display the string on the screen. 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 applet require values to be in 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 redraws the screen, which is impossible to predict.

 

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.

 

In the next example, as a re-revision, we have put two drawStrings and changed the value of ii with the expression ii = ii + 20. The drawString is given to redraw the string at the new positions.

 

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 it is being initialized to 5. The Java compiler, at this stage, gives an error.

 

C:\javaprg>javac zzz.java

zzz.java:11: cannot resolve symbol

symbol  : variable ii

location: class zzz

ii = 5;

^

zzz.java:12: cannot resolve symbol

symbol  : variable ii

location: class zzz

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. Meaning, that local variables are only available to the function in which they are created. 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 no errors. The init function changes the value of ii to 100. Paint changes it to 5. Finally, what gets taken is the last one and that is 5.

 

Hi is displayed 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 display. The only difference is that println writes in the dos box and drawString draws 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 enhance 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 in 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 subsequently assigned to ii. As a result, 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 would have no effect on 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 a lot more 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 an int value of 80 using the keyword return. 80 is the value that will finally be given to ii. This is how functions return values.

 

With return 80 all that happens is that pqr() gets replaced by 80.

 

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:17: unreachable statement

ii = 200;

^

zzz.java:18: missing return statement

}

^

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 thus it can have a logical value of either true or false. The mouseDown function 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, we get the following error:

 

C:\javaprg>javac zzz.java

zzz.java:16: missing return statement

}

^

1 error

 

Here, mouseDown returns a boolean, but in our code the return statement is missing, 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. At present, it doesn't matter whether the return value is true or false but in real life programs it does 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 for the moment.

 

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 is trapped by the mouseDown function. The parameters x1 and y1 expose the location where the mouse was clicked. Also, e, which is an object that looks like Event, gives details on the click. How we clicked? Aren't all mouse clicks the same? Actually, they aren't because not only can we have a left click by itself, but the click can be 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. Ensure that every time you change 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 paint function gets called. i++ can also be written as i=i+1. At the very start, the value of the variable will be 1 because paint gets called once. When the window is minimized and then maximized, paint gets called again. Now click the restore button to restore the window back to its original size. paint gets called twice this time. We cannot really decide when and who calls paint. It is entirely at the discretion of Microsoft Windows. Whenever the OS feels the 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 the screen can be redrawn.

 

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()

{

System.out.println(3>8);

System.out.println(8>3);

}

}

 

C:\javaprg>appletviewer a.html

false

true

 

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 types

found   : int

required: boolean

if ( ii = 3 )

     ^

1 error

 

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 shows 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 demonstrates the use of if statement more 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. Thereafter, ii is initialized to 1.

 

On 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 and ii is then reinitialized to 0. In the end, 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. As a result, clicking twice draws a line between the two clicks.

 

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.