Java Tutorial Part 1 - Basics

This is the first in a series of tutorials which I hope will give you some knowledge of Java Programming. Those of you familiar with the OO paradigm from C++ will find many similarities as will those hackneyed C gurus making the switch. Java and its namesake JavaScript already are the next big thing in web and application programming technologies (look around the web and also at Corel's Suites if you need any further convincing). Remember however that the two are very different, JavaScript is an evolving scripting language used to extend the capabilities of HTML pages, where as Java applications are stand alone, apart from their shared name the two are very different.

To start Java coding you'll need only a few resources. As Java is still relatively new the developers at Sun are giving it away for free to encourage its use (I'm informed that this remains the intention forever), so browse over to http://www.sun.com and download the entire JDK (Java Development Kit), its around 19.5Mb's. In these tutorials I will use v1.2.1 and v1.2.2 of the JDK. Historically, Java started at v1.0 which is now  fairly obselete, although older programs will still compile with deprecation. Setting up the JDK environment should be as easy as breathing, under Windows (95 & NT) machines you'll need to make just 2 changes.

Set the environment variable CLASSPATH to point at your C:\Jdk122\bin directory, this can be achieved using either autoexec.bat or the settings under System in Control Panel (NT) and place the very same directory on the PATH too.

Too write Java programs you'll need initially nothing more fancy than a text editor, NotePad or UltraEdit are good choices, you might be lucky enough to have a dedicated program with its own IDE. As in any programming tutorial we'll start with the universally accepted "Hello World" example. At the end of this page you will be able to download this first set of examples to save typing.

// Prints Hello World!, your first Java Program.
class HelloWorld {

  public static void main (String[] args) {
    System.out.println ("Hello World!");
  } // method main

} // class HelloWorld

I'll analyse this to the point at which you cry :-). The first line of the program is a comment, the // is a carry over from C++ and continues to the end of the line (good comments in programs are good programming practise, excessive or mystic comments are not), Java also provides a means to comment over several lines, like so.

/*
Incredibly interesting comment here, hopefully
explaining to the new project leader what the 
code actually does.
*/

Moving on, the second line is termed as a class definition, later on we'll see how this slots into the OO (object oriented) programming model. The class HelloWorld could have been called anything we liked, we chose HelloWorld purely on a descriptive basis. A class is essentially a collection of methods (sometimes termed functions) and data and runs from the opening { to the } on line 8. Inside our class is the main() method where execution begins (note that all Java programs have a main() method). The public, static and void words will be explained later, as will the String[] and args which are not used in this program.

Like Windows, Java consists of a core API (Application Programming Interface), this can be thought of as your own personal off-the-shelf library of pre-written and bug tested code, software re-use is a key feature of OO programming and you probably have no desire to 're-invent the wheel' so to speak. System.out.println (read as 'printline') is one such method and is used for outputting strings to the console, you will probably want to obtain a good reference for the Java API, download it from Sun or invest in one of the very good O'Reilly books (Java in a Nutshell (the Javan tiger)).

To compile and run the above example we do the following :-

F:\Jdk122\bin>  javac HelloWorld.java  (Remember the filename must be the same as the class).
F:\Jdk122\bin>  java HelloWorld  (Run the program).

Before you even comment, the Java console compiler is VERY slow (under both Windows and *nix), note that after compiling, javac generated a .class file which is the interpreted bytecode for your program.

Choosing Identifier and Variable Names

When writing Java programs of any substance you will certainly have to choose class, method and variable names (these are all termed as 'identifiers'). Java's variable naming convention is case-sensitive so hours_worked is NOT the same as Hours_Worked. Intelligent naming of your variables makes your code easier to read and understand and is a matter of common sense, consider the following names for yourself :-

i <-- What is it?.
length <-- Good description if used in conjunction with other comments.
my_temporary_variable_for_internal_program_use <-- You'd love typing this one.
transient <-- Reserved for use by Java.

In our first program we used System.out.println to output our message to the console, as the name might suggest 'println' outputs our string and moves to the next line. You could also have used the print method i.e. System.out.print if you didn't wish to implement a carriage return.

Concatenation

Concatenation is a long word describing a very elegant and simple concept, lets look at some code :-

// Subtract 2 numbers and print the result.
class Subtract {

  public static void main (String[] args) {
    System.out.println ("The result of 10 minus 6 is " + (10-6));
  } // method main

} // class Subtract

What happens here is simple yet important, the + is the string concatenation operator which combines 2 strings into 1 (end to end) e.g. "This JAVA tutorial" + "is interesting and lucid" would be concatenated to "This JAVA tutorial is interesting and lucid", which of course it is :-). The extra parenthesis (brackets) around the (10-6) results in the subtraction being performed first, hence the program first calculates 10-6 and then concatenates the result to our string. The console output is therefore :-

The result of 10 minus 6 is 4

Command Line Arguments

Often when writing simple Java programs you'll want to process command line arguments, much like DOS commands. In Java the main method always accepts potential arguments, these are accepted as character strings and are designated using the args keyword, args[0] being the first argument, args[1] the second and args[10] the eleventh and so on. Lets process a command-line argument :-

// Takes a command-line argument and prints it to the console.
class CommandLine {

  public static void main (String[] args) {
    System.out.println ("Your command-line arguments were " + args[0] " and " + args[2]);
  } // method main

} // class CommandLine

Submitting the following to the compiled Java program produces the following result :-

> java CommandLine args0 args1 args2
> Your command-line arguments were args0 and args2

Needless to say this processing of many arguments can be very useful for console based applications.

Classes & Objects

In the 3 examples above we defined class names for our very small programs, this was really just to introduce the concept of a class. In the real world of software, programs are obviously much more complex than these and the class/object definition is much more important. Consider a real-world application such as a game with many players. A class called 'Player' would be defined with various attributes and methods common to all players, for example each player might have a method to move. An object in this case would represent a single player in the game, think of a class as a description of a category of objects and an object as a specific example described by the class. Lets consider some examples (rank each of the following as either a class or object - think of the 'real-world') :-

i). A yo-yo.
ii). CrackZ's favourite yo-yo.
iii). A yo-yo with "Shania Twain is a goddess" written on it.
iv). A website.
v). CrackZ's tutorial on Cimatron v10.6 HASP reversing.

Answers :- i) class (there are lots of yo-yo's in the world), ii) object, assuming I have only one, iii) class (assuming many such yo-yo's exist, iv) class (obvious), v) object, assuming its the only one.

In the 3 above programs we used Java's API to invoke the System.out.println method (part of the System class). Like most component based languages Java has an entire set of 'packages' which provide common functionality. C/C++ programmers will already be familiar with the #include directive, in Java the equivalent statement is import. Specific functionality is provided by various parts of the Java Platform API, a brief list is given below.

java.applet - (applets for the web all import this).
java.awt - Java's Abstract Windowing Toolkit, graphics support.
java.io - Java's I/O support.
java.lang - Automagically imported into all Java components (hence our use of System.out.println without an import statement).
java.math - Maths functions.
java.net - Java's network communications.
java.text - Text outputting.
java.util - Java utilities.

There are several others, like java.rmi, java.security & java.sql but these are applicable only to specific applications and are beyond the scope of this tutorial.

Data Types

In the text above I talked briefly about variables. In Java all such variable are associated with a 'type' which determines the sort of operations we can perform. Consider a trivial program that calculates the circumference of a circle, of course we'd need a variable to represent pi. Java has 4 integer 'types' and 2 floating-point types, consider their ranges below then decide what would be an acceptable type for pi.

Data Type Memory Usage
Byte (byte) 8-bits (range -128 - 127)
Short (short) 16-bits (range -32,768 to 32,767)
Integer (int) 32-bits (range -2,147,483,648 to 2,147,483,647)
Long (long) 64-bits
Float (float) 32-bits (floating point)
Double (double) 64-bits (floating point)

In Java all numeric types are signed (meaning they can hold positive or negative values). Your decision as a programmer upon which type to use should be based on 2 factors, efficiency and precision. There is little point declaring a constant such as pi as an integer type, because precision is important you'd probably want to use a double, by the same token a simple counter from 1 to 100 is overkill declared as a long. Lets extend this by writing a simple program to calculate the circumference of a circle, we will assume our user can provide us with the diameter i.e. π * d = circumference.

To accomplish this we are going to need to prompt the user for input. In Java this isn't as easy as using scanf() or gets() in C, this will introduce you to the concept of streams.

/*
 Calculates the circumference of a circle by prompting the user 
 for the length of the diameter.
*/

import java.io.*; // Required to read input.

class Circumference {

  public static void main (String[] args) throws IOException {

    BufferedReader stdin = new BufferedReader
      (new InputStreamReader(System.in));
    final double PI = 3.141592654;
    int diameter;

    System.out.print ("Enter the length of the radius : ");
    diameter = Integer.parseInt (stdin.readLine());
    System.out.println ("The circumference is : " + (PI * diameter));

  } // method main
} // class Circumference

As you can see, in Java its quite an effort just to do simple console I/O. Lets analyse this program. The first import statement is similar to C's #include <stdio.h>, as you can see the name java.io does imply I/O operations i.e. reading user input. As ever my class name Circumference is for now more descriptive a term rather than anything really meaningful in OO programming. As Java programs inevitably need to handle many forms of input/output e.g. console I/O, files, network connections, all sources of I/O are termed as streams.

The 'throws IOException' requires very detailed explanation, in Java an exception is an object that defines an unusual or erroneous run-time situation, in some cases these exceptions can be a result of programming error or they can be 'caught' and handled by your program. Consider 2 hypothetical and relevant examples, would you want to 'catch' and handle the following 2 exceptions :-

i). A division by 0 error (e.g. 10 / 0).
ii). An error reading the users input.

In i). a division by 0 error must be regarded as a run-time bug and thus you as a programmer would need to eliminate the possibility of this re-occuring, ii). however may be an exception you want to 'catch' and 'handle' before resuming processing. In our example above the readLine method throws an IOException if an error occurs while reading our user input, thus should such an exception occur a run-time error will most likely be the result. BufferedReader is a class defined under java.io which we are making use of, for those of you without a reference, I'll give you the brief description from "Java In A Nutshell", if you plan on serious Java coding this is a must, its the Java equivalent of a Win32 API Guide.

"java.io.BufferedReader : This class applies buffering to a character input stream, thereby improving the efficiency of character input. You create a BufferedReader by specifying some other character input stream that it is to buffer input from."


Return to the Coding Page


© 1998,1999,2000 CrackZ. 1st January 2000.