Brrr....Its Hot : -
We briefed you on what the Java ballyhoo is all about. Bet you are throbbing for the innards of Java programming by now. We will get down to that right off the bat.
Before we hop on to savor the wondercoffee, however, let up get clear on one thing. The Java mug actually has two shades to it. For one. You can write applets (as discussed in the previous part of this thread of articles), which will wriggle down the cast skeins of Internet cables on to a user's terminal, with the browser picking up the cudgels to execute them. As the other shade, you can write Java standalone programs, which will compile and execute on the user's local machine. As promised, in this series, we will master the techniques of creating such stand-alone Java programs and calling them your own (though we really like calling internet-independent programs).
Owing to security reasons, there is an array of functionalities which the applets are denied by the rather rigid duo of Java and the Java-enabled browser. On the other hand, the stand-alone programs are, fortunately, spared from the security rigmarole. That gives us one good reason to pursue such programs.
Unfortunately for the people who want to run without bothering to learn to walf first, we will stick to our rituals, that is, a step-by-step approach to programming. As regards our naming conventions, we do not intend to inculcate style-specific practices. Quite the contrary, we intend development of initiative and understanding. Hence, the names of our classes, functions and variables will not exceed three letters. In case you overlooked, the presence of classes etc. Also presupposes the fact that the reader is versed to a reasonable extent with C/C++
With that widget of wisdom up our sleeve, let's take the first sip. Make sure you are in the DOS mode and running a text editor of your choice. (According to our reliable astrologer, Edit serves the purpose well enough).
zzz.java
class aaa
{
}
Well, that's admittedly a simple program. We define a class by the name of aaa. Mark that the name of our java file is zzz.java, which implies that the names of the class and the .java file do not matter so much now, though they will soon begin to. Hopefully, you know that the program has to be compiled before it can be executed. The Java compiler is called javac. So now we key in the following command at the DOS prompt.
javac zzz.java
The compilation process turns out to be comfortably peaceful and a file called aaa.class is created by javac. Which indicates that Java makes .class files instead of the usual .obj (the cheeky chappies at Sun were always creative with their names anyway). It is now a fair idea to try and execute the program. For this, we have to type :
java aaa
Bet you have realized that this command would actually read : java aaa. Class since we are trying to execute the .class file. But a period (.) is supposed to be a part of file path in Java, so we'd rather you skip the .class part out. The program, though successfully compiled, refuses to run without hassles. It flings the error message : In class aaa: vodi main(String argv[]) is undefined. If anything, that error message smacks nostalgically of C -- main() and all. So we very willingly add the main() to our code. Consider the following code...
zzz.java
class aaa
{
void main( String s[] ) { }
}
Our main() has one argument -- an array called s. This array will contain strings, hence the String. It is similar to your argv in C, the only variation being, the number of parameters are not specified. A point to be noted here is that arrays in Java and C differ slightly. C gave no errors even if you tried to refer to an element outside the actual size of the array. That is, assuming we have an array a[10]. The size of the array is 10. While using C, we could cheerfully say a[11] in the program without any errors, though the output would be some out-of-this-world junk. Java, however, has built-in error checks that keep a track of the number of members and prevent us from going beyond the specified limit.
When we javac the above code, it compiles quite conveniently. However, it refuses to run. This time the error shown is : In class aaa: main must be public and static. By default, the main() is private and hence, the others cannot avail of it. The simple reason why it must be public is that it should be visible to others (e.g., other classes, other programs and very importantly, our own Java Run time system). In plain English, when we say java aaa, the Java runtime system contacts the class aaa, looks for a function called main() init. But since the function has not been declared as public, the system cannot look into it.
As regards static, a C++ programmer should be very well-versed with it. Ordinarily, to access a function inside a class, we have to define an object that looks like that class and access the function through the object. But by defining main() as static, we can access it directly, without needing to create an object that looks like class aaa. So we modify the code as follows...
zzz.java
class aaa
{
public static void main( String s[] ) { }
}
After all those changes, the program finally works. But sadly, there is no attractive output because we have admittedly done nothing in the main(). Let us go right ahead and add some code. Retain the name of the java file.
class aaa
{
public static void main( String s[] )
{
System.out.println("in main");
}
}
Everytime we use java, we have a free reign to use the objects that are pre-created, so we are spared the burden of creating our own objects. One very helpful of these objects is System (and note the case because Java is pretty unforgiving with case-errors), which in turn has various other objects in it. In our case, the object is called out. From out, w use a function or a method called println, which can safely be likened to printf in C. Just like printf, whatever we snuff inside the double quotes will be snuffed out on the screen. So when we run this program, ofcourse after compiling, it will display the string "in main".
A program in any self-respecting language is virtually useless unless it makes use of variables. Since Java is surely one of them, let us add a variable to the code...
class aaa
{
public static void main( String s[] )
{
int i = 0;
System.out.println( "in main.i.."+i );
}
}
We choose to call our variable i. It is of the type int, and it is inside main(). It is initialized to 0. That very eloquently shows that Java looks and feels like C/C++. However, the println scores over the strict, old printf. Note that we are displaying a string - - "in main.i.." and the variable i.Unlike C, Java figures out how to display two different data types at the same time, chucking out the fuss involved in the cumbersome conversions.
The output of the above program will be...
in main i..0
The object String has a member called length. Since s (in the definition of the main()), looks like a String, we can access length through s. That's what our next program speaks about.
class aaa
{
public static void main( String s[] )
{
int i;
i = s.length;
System.out.println("in main.i.."+i);
}
}
When you run the above program, with the command line being java aaa, you will see the output:
This is because the command line has to have some arguments besides the java aaa. For instance, if you type out java aaa a b c, the output will bein main.i...0
Which is to say that the object String works very much like argv[] of C, while the length can be likened to argc. The array s stores the command line arguments (that is, whatever you type besides java aaa) and length counts the number of extra arguments typed in. Now if we want to display the actual elements, we can do that by saying s [0, s [1] and so on. In our case, for example, when we say s[0] it will print the a, s[1] will print b and s[2], c). Let us see for ourselves how...in main.i...3
class aaa
{
public static void main( String s[] )
{
int i;
i = s.length;
System.out.println("in main.i.."+i);
System.out.println("in main s[0] ..." + s[0]);
}
}
If you run the above program without any extra parameters, it will display the error..
java.lang.ArrayIndexOutOfBoundsException
To check for that, we can modify the program a little...
class aaa
{
public static void main( String s[] )
{
int i;
i = s.length;
System.out.println("in main.i.."+i);
if (i > 0)
System.out.println("in main s[0] ..." + s[0]);
else
System.out.println("no parameters");
}
}
In the above program, we check whether the user has entered anything other than java aaa with the if condition. That is because i stores the number of these extra arguments. If the user has entered nothing, we display "no parameters", otherwise we display the first additional argument. All the arguments can be displayed inthe following way...
class aaa
{
public static void main( String s[] )
{
int i;
i = s.length;
System.out.println("in main.i.."+i);
if (i > 0)
for (int j = 0; j < i; j++ )
System.out.println("in main .."+ j +"..." + s[j]);
else
System.out.println("no parameters");
}
}
The above code checks for the presence of extra arguments, and if present, it displays all of them.
Consider this code for another minor revelation...
class aaa
{
int i = 0;
public static void main( String s[] )
{
System.out.println( "i.." + i );
}
}
Here the compilation will give an error saying : can't make static reference to a nonstatic variable I in class aaa. That is because main() is a static function and static functions cannot refer to any variables outside their own body. Whereas, in the above program, our variable I is a global variable, i.e., it is defined outside any function. So it cannot be referred by the main()
Mr. Vijay Mukhi
Ms. Sonal Kotecha
Mr. Shashank Tripathi
Vijay Mukhi's Computer
Institute
VMCI, B-13, Everest Building, Tardeo, Mumbai 400 034, India
Tel : 91-22-496 4335 /6/7/8/9
Fax : 91-22-307 28 59
e-mail : vmukhi@giasbm01.vsnl.net.in
http://www.vijaymukhi.com