[Top bar]
[Bottom bar]
This document is available in: English  Castellano  ChineseBig5  Deutsch  Francais  Nederlands  Portugues  Russian  Turkce  Korean  

[Photo of the Author]
by Jose M. Fernández
<fgcia(at)correoweb.com>



Translated to English by:
Miguel A Sepulveda <sepulveda(at)linuxfocus.org>

Content:

 

Programming with Java, part I

[Ilustration]

Abstract:

This is the first article in a series about Java programming. The first part will describe Java as a language, its general characteristics and the location of the most relevant sources of information.



 

Introduction

This begins a series of articles that will describe Java's programming language and its development environment. As a first goal I will try to stay away from issues concerning the history of the language, microwaves, washing machines.. (if any one is really interested it can be read in multiple publications, even in pink literature). I will also stay away from Duke (Java's mascot), a little guy with a huge nose and triangle shape body that shakes its hands to rhythm of a marimba and reminds me those old American science fiction movies.

There is a little bit of a fad in this Java phenomenom. Every computer magazine of any worth writes about it, there are many software companies that sell products for developing Java applets, and few web sites do not have a Java applet or two.

Through this series I will try as much as possible to investigate in depth and learn (altogether) this programming language, which is simple for basic things but at the same time is quite complex and difficult to master because it is constantly evolving.

Our goal with the first few articles is to provide a description of the language in general so that later on we can go into more in depth subjects like applets, network-related projects, JDBC, beans, etc.

I should emphasize that Java is a general purpose language, it is not exclusively used to write applets for webpages, although that is what made it very popular. We can not get stuck with only that aspect of Java because there are many other alternatives that can be even more interesting than java applets.

This first article is more descriptive than practical.In the next article,we will explore the fundamental characteristics of the language, and the development environment. Only at the end will we see an example of java programming.

 

Origin

Java was conceived by James Gosling, Patrick Naughton, Chis Warth, Ed Frank and Mike Sherindan at Sun Microsystem Inc. in 1991, in its first 18 months of life. Between 1992 and 1995 Bill Joy, Arthur Van Hoff, Jonathan Payne, Frank Yellia, Tim Lindolm collaborated in the maturity of the initial prototype.

From the dates it is clear that Java is previous or at least simultaneous to WWW -- until 1991 Tim Berners Lee had not developed the HTML language.

The syntax of Java is very similar to C and its object oriented characteristics is also similar to C++. Java is a coherent and logically consistent programming language.

The similarities with C and C++ may give the impression that Java is a version of C++ for the Internet, but there are important theoretical and practical differences. Especially since Java improves and refines the object oriented paradigm compared to C++.

The internet has launched Java and made it a language universally known, and simultaneously Java has had a profound effect on the Internet since it broadened the range of objects that can be move freely in cyberspace (dynamical self-executable programs).

 

Obtaining and Installing Java

There are several tools crucial for Java programming. Incidentally I will always refer to the GNU/LINUX environment (just in case anyone gets lost):

The current ELF based implementation for Linux requires a kernel 1.2.13 or later.

I will use the JDK (Java Development Kit) environment , Netscape version 2.0.14 or later, and a text editor like Xemacs. We will always work under Xwindows . Although it is not always necessary , it is required when developing Applets and programs with a graphical interface.

The JDK distribution can be downloaded from the following website:

http://www.blackdown.org/java-linux.html

From this site one can select a convenient mirror in order to download the files rapidly. A few months ago the last version was JDK-1.1.3 (the one used for this article) but in my last visit I saw version 1.19 already there. Note that if we download everything it is about 24 Mb! Nevertheless downloading only what is trictly necessary takes about 12 Mb (patience!).

After uncompressing the archives with gunzip there is no obstacle to start working.

Normally we would install the distribution in the directory /usr/local, thus creating a subdirectory /JDK1.1.3 and within the following:

/doc Official documentation in HTML format

/demo Demo Java programs

/lib Libraries

/bin Here are the proper tools of JDK.

Inside the directory /lib we find the file "classes.zip"(do not unzip this file), it contains all the compiled classes that can be used by JDK.

Within the root directory we find the file "src.zip", it contains of the source files included in classes.zip. They can not be compiled and they are provided with the distribution for informational purposes only.

 

Development Environment

As mentioned earlier the development tools are located in the /bin directory:

javac : java compiler that transforms the java sources into bytecodes.

Java : java interpreter. Executes java bytecodes.

jre : another interpreter similar to Java, but thought to be for users that do not require all the options available.

appletviewer: tests and runs applets.

jdb: debugger.

javap: disassembler of bytecode files compiled from Java.

javadoc : documentation generator, produces a set of HTML pages describing the public and protected classes, interfaces, constructors, methods and fields. It also produces a hierarchy of classes and an index of all the members.

javah : tool to add native methods (in C) to Java programs.

jar: archives java classes and sources in a Jar archive file.

javakey : tool to maintain digital signatures.

updateAWT : updates the changed names from the AWT1.02 methods in an application.

To work without glitches with the current directory structure I advise you to add /usr/local/JDK1.1.3/bin to the environment variable PATH. If you wish to make the development environment available system wide then fix the PATH variable in the /etc/profile file.

 

Characteristics

Before continuing, we should ask ourselves What is Java? To answer we can respond, as in the JDK manual, that Java is two things, it is a programming language and also a platform.

As a programming language Java is a high level language with the following characteristics (at some point we will examine them in detail):

The first thing that calls our attention is that Java is interpreted. Despite java sources requiring a previous compilation to generate an object in bytecodes, which is already low level code, it has to be interpreted in various platforms.

Thanks to Java bytecodes we can "write once and execute always". We can compile Java programs on a platform and execute them in another completely different architecture that has an implementation of the Java virtual Machine (JVM). For example a Java program can be compiled on a Windows NT platform and run without trouble (at least that is the theory) on a Sun Ultra Solaris.

In general a platform is a hardware/software environment where an application runs. However for Java a platform is only the software environment where it runs, each Java platform has to then run on a hardware platform.

A Java platform has two components:

JVM is an abstract computer where Java precompiled programs can be executed. It was designed to be simple and small because the idea was to install it in all places possible. This simplicity made it possible to spread across all existing platforms, thus providing a common software layer to all and in a very heterogeneous network (such as the Internet) it solves great number of portability issues. As it can be imagined this is quite probably a reason for the unstoppable growth of this technology. Nevertheless the virtual machine should not be viewed merely as a software layer, but as its name indicates, it tries to be a full computer system, little by little we will start to see in the market Java Chips that support real Java machines, credit cards, TV decoders, etc.

Java's API is a large collection of software components that provide a number of utilities, such as a graphical user interface (GUI). They are grouped in libraries (using Java's terminology Java packages). Thanks to these packages it is possible to use Java for many applications besides the well known Applets for the web, we can design Web servers, for example, proxies, mail servers, IRC servers, and practically anything we can imagine that is related with the Internet.

We can classify the API packages into various groups:

Besides this basic API kernel there are also 3D extensions, mobile communications, animations, etc.

We mentioned at the beginning of the section, Java has a series of characteristics we will study in detail:

It is simple:

In Java there is always a reduced number of well defined forms to overtake a task. It offers all the functionality of a powerful language but without the less used and more confusing features often associated with them. Java inherits the syntax of C/C++ and many of the object oriented features of C++. Any programmer familiar with C/C++ will have no problem learning Java. Despite their similarities, Java eliminates a number of C/C++ features, among which are:

  • Pointer arithmetic
  • Registers (struct)
  • Type definitions (typedef)
  • Macros (#define)
  • Need to free memory (free)
  • No multiple inheritance
  • No overload of operators
  • No structures in unions
Is object Oriented: Java was designed from scratch, and as a result its approach to object orientation is clean, useful and pragmatic. The object model for Java is simple and easy to use.
It is distributed: Java was designed with large TCP/IP interconnectivity in mind. In fact, it allows developers to access information on the net as easily as local file.
It is robust: Java is a strongly typed language, this allows type checks on compile-time. It does also some checking during run-time. Memory is managed automatically, since the interpreter implements an automatic garbage collector for objects no more in use. Java itself provides a number of object oriented exception handlers. In a correctly written application all run-time errors can be handled by the program.
It is architecture independent: The main goal of the designers of Java was to "write once, run anywhere, any moment and always". Java code is compiled once into a high-level byte code that is machine independent. This bytecode was designed to be run on any with a run-time system (interpreter) that is machine dependent.
It is secure:

The need for distributed information requires the greatest level of security from the client operating systems. Java provides security thanks to several features in its run-time environment:

  • A bytecode verifier
  • The availability of memory during run-time
  • File access restrictions

Although the compiler only generates the correct code, the interpreter double checks it to ensure that the code has not been modified (intentionally or not) since compilation time. Furthermore the Java interpreter determines the memory availability for classes. Java can be considered one of the most secure applications for any system.

It is portable: Aside from the basic portability of Java, in order to really be architecture independent, Java implements a portability standard: integers are always integers, the GUI consists of an abstract system of windows and therefore it is independent of the architecture (UNIX, PC, Mac).
It is interpreted: To achieve one of the basic goals of Java, platform independence, the java compiler generates an intermediate code (bytecode). It can be executed on any system with the proper interpreter. This paradigm may let us wonder on the possible performance problems of java applications. Nevertheless, and because of this performance concern, Java creators have tried to keep the bytecode design as simple and as easy to translate into machine code as possible in order to keep the highest performance possible.
It is multithreaded: It is simple to write Java applications that can execute several tasks at the same time in a robust way.
It is dynamic: Java does not try to link all the modules that form an application until run-time. This feature helps to link the code dynamically safely and conveniently.

After this long "speech" (much of which can be found in the official Java documentation) one can wonder about the status of Java in the GNU/Linux world. We mentioned earlier the availability of JDK for Linux, which is nothing but a commercial implementation developed by Sun Microsystems (although freely distributable).

There are tools like the compiler GUAVAC under GPL license, that let us compile any Java source without problems. We should also mention a virtual machine called KAFFE under Berkeley license. The last two projects are in a very advanced stage although still need of the Java class libraries from Sun (of free distribution at the moment) in order to have a complete development system.

Several recent projects, still in an early stage, aim at providing development environments to fast and visual applications.

Finally I would like to state that there is a great movement on the net concerning Java and GNU technologies, especially concerning the development of the complete tool box of free-distribution for Java and independent from Sun. We can already understand the importance of Java, and when the fashion is over I am sure that something is going to remain of it (I venture to say a lot of it is here to stay).

 

A First Program in JAVA

After seeing some of the general characteristics of the language let us take a look at a real program. As I mentioned in the introduction, I would like as much as possible to stay away from typical stuff, like the hello world example, instead let us start with a program that draws a square of any dimension we like (a bit complicated but not too much):

File Cuadro.Java
class Cuadro {
public static void main (String args[]) {
        int l ,a;
        if (args.length == 2) {
            l = Integer.valueOf(args[0]).intValue();
            a = Integer.valueOf(args[1]).intValue();
         }
         else {
          l= 20;
          a= 15;
         }
          for (int i=l; i>0; i--){
            System.out.print("*");
            }
            System.out.print("\n");
            for (int i= a-2; i>0; i--){
             System.out.print("*");
               for(int j=l-2; j>0; j--) {
                  System.out.print(" ");
                  }
                  System.out.print("*\n");
                  }
                for (int i=l; i>0; i--){
                System.out.print("*");
                }
              System.out.print("\n");
           }
}

In Java the name given to the source file is very important because it defines a "compilation unit". The file may contain one or more definitions of classes. The compiler expects the source file to have the extension .Java (4 characters) consequently some systems do not support it (DOS or Windows 3.1)

In the example given the name of the class defined coincides with the name of the source file. This is not by chance, in Java all code must be in a class. By convention the name of the class has to coincide with the name of the source file containing the class.. Moreover Java is case sensitive (upper or lower case).

To compile the example from the command line type:

> javac Cuadro.java

The Java compiler (if everything went OK) will generate the file Cuadro.class that naturally contains the binary (bytecode) form and it can be immediately executed by the interpreter as:

> java Cuadro

When java source code is compiled, each class in individually placed in an archive with the same name as the class. It is then a good habit to give the source files the same name as the class contained in them so that the source filename will coincide with the archive.class file.

Despite the simplicity of our example Cuadro.java it helps us understand the fundamentals of Java and in particular the structure of a typical java program.

First take into account that this example is not an applet that can be included in a HTML file but an independent program to be executed by the java interpreter on the command line.

The first line of the program is:

class Cuadro {

The first word is a reserved token of the language, it indicates the definition of a new class named in this case "Cuadro" -- Square in spanish -- The exact definition of the class including all its members follow in between two curly brackets {}. Note that in Java all the activity of a program resides inside a class.

In the following line:

public static void main (String args[]) {

it declares a method named main(). All Java applications start their execution with a method called main() (similar to C/C++). Next let me comment a few details necessary to understand the example (in later articles we will explained them in more depth).

The keyword public control the scope of the member methods of the class. When a class is declared public, then the class can be used by code defined outside the class. The keyword static forces the main() method to be invoked without needing to instigate the class. Void indicates that this method does not return any value. To pass parameters to a function or method one uses the parenthesis written after the name of the function, in our example main takes as parameter a matrix of instances from the class String.

Obviously all the code belonging to the method is also enclosed between curly brackets. Next, in the line:

 int l, a ;

we declare two integer variables. In Java every variable must be declared before it can be used. Notice each instruction in the code ends with a semi-colon ";".

The remains of the code implement a small algorithm that :

  1. Test whether the right number of arguments have been provided
    If (args.length==2)
    
  2. If parameters are provided, then they are assigned to the integer variables:
      l = Integer.valueOf(args[0]).intValue();
      a = Integer.valueOf(args[1]).intValue();
    
  3. Otherwise the variables are initialized to default values:
      l = 20;
      a = 15;
    
  4. The rest of the program is nothing more than the instructions needed to draw a square on the screen. We can point specially to:
    System.out.print()
    

    where print() prints the string passed as argument. System is a predefined class that gives access to the system and out is the output stream connected to the console. Also,

    for (int i=l; i>0; i--)
    

    As expected it behaves as our experience with C/C++ and other languages tells.

A nice piece of homework the reader can do using this little code is to test how to compile it and execute it, but also to test the portability of the code by running the compiled object Cuadro.class under various platforms: Linux, windows 95 (but don't take this as a present!) and see that it runs the same on any platform.

 

Summary

We have gone through some of the general features of Java as a programming language. We have just started to program and there is a long way to go, future articles will give a more in depth description of the language. In the following article we will study the definitions and types of variables, basic instructions, classes, etc. The main specification of the language.

In each article I will give the references, publications and URLs on which I have based the series of articles.


Webpages maintained by the LinuxFocus Editor team
© Jose M. Fernández, FDL
LinuxFocus.org
Translation information:
es --> -- : Jose M. Fernández <fgcia(at)correoweb.com>
es --> en: Miguel A Sepulveda <sepulveda(at)linuxfocus.org>

2002-10-22, generated by lfparser version 2.32

mirror server hosted at Truenetwork, Russian Federation.