Friday, June 17, 2005

Wednesday, June 15, 2005

The equals Method

Introduction

The equals method checks objects for equality. The default behavior inherited from class Object is simply to check if the references points to the same object.

public boolean equals(Object obj) {
    return (this == obj);
}

Program

package bloggingjava;

public class Main {
    public static void main(String[] args) {
        String s1 = "ABC";
        String s2 = "ABC";
        String s3 = new String("ABC"); // bad code
        
        System.out.println(s1 == s2);
        System.out.println(s1 == s3);
        System.out.println(s1.equals(s2));
        System.out.println(s1.equals(s3));
    }
}

Output

true
false
true
true

Discussion

Knuth 1996

Author Knuth, Donald E.
Year 1996
Title Selected Papers on Computer Science
Place Stanford, Calif.
Publisher CSLI Publications

Tuesday, June 14, 2005

Installing Java for Linux HOWTO

Linux logo

Java can now be installed from software repositories in many Linux distributions. Fedora, etc. now usually ship with OpenJDK, so you could just use your favorite package manager to install it. See: OpenJDK Installation. You may wish to install the Sun JDK instead as outlined in this document. I no longer have the time to update this HOWTO, but this page will still be here for reference, and will not be deleted.

Disclaimer

Warning: Performing the procedure outlined in this document is at your own risk. The author provides no guarantees, warranties or any liability with respect to any damages or loss of data or any other harm resulting from performing any of the procedures outlined in this document.

Table of Contents

Introduction

This tutorial explains how to uninstall and install the following on the Linux operating system:

  • Java 2 Platform, Standard Edition (J2SE), SDK 1.5.x
  • Java Web Start
  • Java Plug-in for most HTML browsers

If you are struggling with the installation instructions from Sun Microsystems, and your head is filled with more questions than answers concerning the finer points of Java installation on Linux, then this tutorial is for you.

Installing Java on Linux is almost easy, so don't worry that the tutorial is a bit thorough. The text covering the actual J2SE installation is just a few pages long, and you should be up and running Java in no time. Really! Most of the text is there just to keep you out of harms way if you get yourself into trouble.

Note: The tutorial has been tested successfully on the Red Hat Linux 7.2, 7.3, 8.0, and 9 operating system for SDK 1.4.0, SDK 1.4.1, SDK 1.4.2 and SDK 1.5.0.

The tutorial has also been found helpful for users of the Mandrake Linux 8.2 and 9.1 operating system.

Linux commands

If you find yourself stuck on those Linux commands, just take a look at The Linux Cookbook: Tips and Techniques for Everyday Use.

Warning: Do not be surprised if folder and file names, usually based on version numbers, have slightly different names on your installation than in the tutorial. New versions of Linux, J2SE and HTML browsers are released continuously, and I'm only human... Typos based on version numbers are the most reported typo error I get. Keep that in mind if something goes wrong with your installation.

Concept: Use the tab key to complete your typing when you are typing directory or file names, at least when you see the '*' character that the tutorial uses to replace version numbers. You should never copy and paste directly from the examples. The reason for this is that directory names may be different on your Linux version. /usr/java/j + tab may result in Linux writing /usr/java/j2sdk1.8.3/ or whatever.

About the Software

What is jdkgcj?

Once upon a time, Red Hat had a Java version installed called gcj and is part of the GNU Compiler Collection (GCC). gcj does not include a JVM and also lacks a few Java packages like AWT and Swing, so you basically still have a problem and you still need to install J2SE. gcj cunningly uses another program called jdkgcj in order to confuse everyone.

jdkgcj was created by Ark Linux: Easy Desktop Linux to make the gcj (gcj is a front end to gcc) commands more similar to the usual Java commands. An amazingly awful idea, considering that you don't even need jdkgcj in order to use gcj!! This software tend to create problems, so it is described here.

Why is J2SE with NetBeans IDE Cobundle installation not explained?

The tutorial does not describe installation of the NetBeans IDE Cobundle for a number of reasons:

  • Only developers needs NetBeans, and most users should avoid installing the cobundle.
  • J2SE and NetBeans are separate products. You may prefer to install a competing product like eclipse instead of NetBeans.
  • J2SE is installed in the NetBeans folder when installing the cobundle, and the J2SE installation is removed when uninstalling the cobundle.
  • It is much harder to reinstall J2SE or NetBeans independently if you first install the cobundle.
  • It makes the tutorial unnecessarily complicated if yet another installation should be described.

Uninstalling the Software

Before you start the installation, you should always find out if there are any programs that should be uninstalled first. Even if you think that your Linux box is clean, software like jdkgcj could play a trick on you.

jdkgcj uninstallation

Is jdkgcj installed?

To find out if jdkgcj is installed, open a terminal window and type:

[user]$ java -version

If you read something similar to the following message, then jdkgcj has been installed on your computer, and you will no longer be able to compile and run Java programs normally. You should strongly consider removing it.

java version "1.3.1"
jdkgcj 0.2.3
(http://www.arklinux.org/projects/jdkgcj)
gcj (GCC) 3.2.2 20030222 (Red Hat Linux 3.2.2-5)
Copyright (C) 2002 Free Software Foundation, Inc.
This is free software; see the source for copying
conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE.

Uninstalling jdkgcj

Open a terminal window, log in as the super-user and type:

[root]# rpm -e jdkgcj

The jdkgcj package should now be removed, and if J2SE is installed correctly, all Java commands should now work perfectly.

Java Plug-in uninstallation

Uninstalling Java Plug-in for Mozilla browsers

If you are going to reinstall J2SE, you don't need to uninstall Java Plug-in. Just use the -f option for ln when creating a new symbolic link. In the unlikely case that you want to completely remove Java from your Linux box, the procedure of removing the symbolic link is described below.

Open a terminal window, log in as the super-user and type:

[root]# rm /usr/lib/mozilla/plugins/libjavaplugin_oji.so
rm: remove symbolic link `/usr/lib/mozilla/plugins/libjavaplugin_oji.so'? y

J2SE uninstallation

RPM in self-extracting file uninstallation

Note: If you have RPM on your Linux box, you should first find out if Java is already installed using RPM. If Java is not installed using RPM, you should skip reading.

Opening a terminal window. Try to find the j2sdk package by typing:

[user]$ rpm -q j2sdk

Optionally, show all RPM packages by typing:

[user]$ rpm -qa

If RPM reports a package similar to j2sdk-*-fcs, or jdk-* then Java is installed with RPM.

Note: Normally, you do not need to uninstall J2SE with RPM, because RPM is able to uninstall the old J2SE when installing a new version! You may skip reading, unless you want to remove J2SE permanently.

Warning: If you want to uninstall the NetBeans IDE, it must be uninstalled before you uninstall J2SE, because the InstallShield Wizard uninstaller is a Java application!

In order to uninstall J2SE using RPM, open a terminal window, log in as the super-user and type:

[root]# rpm -e j2sdk-*-fcs

Self-extracting file uninstallation

This part of the tutorial has not been updated for a while...

Find out if Java is installed in some folder. Common catalogues are /usr/java/j2sdk* or /opt/j2sdk_nb/j2sdk*/bin/java. When you have located the folder, you may remove the folder.

Warning: You should be certain that Java is not already installed using RPM before removing the folder!

java.sh file

You may delete the java.sh file in /etc/profile.d/ if you want to remove J2SE permanently.

Installing the Software

J2SE installation

If you need to compile Java source code, and most of us do sooner or later, you should install the SDK. Don't bother installing the JRE, because it's included in the SDK anyway.

Note: If you download JRE instead of SDK, you will only be able to run Java applets and applications. SDK contains JRE and also essential tools to program in Java.

You may need to compile Java applications now and then even if you are not a programmer, because some applications are distributed as source only and must be compiled. If you plan on just using Java applets, you may go ahead and install JRE. Installing JRE is identical to SDK installation, except for slightly different filenames and missing development tools & APIs.

Note: There are two installation files for Linux, and you need only one of them. What file you want to download depends on your prefered installation method:

  • RPM in self-extracting file, using the Red Hat Package Manager (RPM)
  • Self-extracting file, doing everything yourself

Warning: The SDK file names changes frequently! You should always start your search for the latest files at http://java.sun.com/

RPM in self-extracting file installation

Note: RPM in self-extracting file is the recommended installation method in this tutorial. If your Linux has RPM installed and if you want to install and maintain Java in a similar way as other RPM packages, you should follow these instructions. Red Hat Linux and Mandrake Linux usually have RPM. Otherwise follow the instructions for self-extracting file.

To continue the Java installation, download the Linux RPM in self-extracting file called jdk-*-linux-i586-rpm.bin (for example jdk-1_5_0-linux-i586-rpm.bin.)

Open a terminal window and give the file execute permission:

[user]$ chmod +x jdk-*-linux-i586-rpm.bin

File access permissions should now be:

[user]$ ls -l
-rwx--x--x    1 user     user     44566787 oct  5 18:20 jdk-*-linux-i586-rpm.

You should also check that the download file size is the same as printed on the download page.

Log in as the super-user and execute the file:

[root]# ./jdk-*-linux-i586-rpm.bin

Read the "Sun Microsystems, Inc. Binary Code License Agreement". (As if... It's about 1 MB of lawyer mumble jumbo basically telling you that you just agreed to sell your soul to Sun Microsystems, Microsoft, SCO, Kodak and who else... Why do I love the BSD and GPL licenses??) Now, just press space repeatedly for quick scrolling, and type yes. You now have two files:

[root]$ ls
jdk-*-linux-i586.rpm  
jdk-*-linux-i586-rpm.bin

Check the installation by printing the product version:

[root]$ /usr/java/jdk1.5.0/bin/java -version
java version "1.5.0"
Java(TM) 2 Runtime Environment, Standard Edition (build 1.5.0-b64)
Java HotSpot(TM) Client VM (build 1.5.0-b64, mixed mode, sharing)

Self-extracting file installation

This part of the tutorial has not been updated for a while...

Note: If your Linux has not RPM installed, you should follow these instructions.

Download the self-extracting file called j2sdk-*-linux-i586.bin.

Open a terminal window, and type:

[user]$ chmod +x j2sdk-*-linux-i586.bin

Log in as the super-user:

[root]# mkdir /usr/java
[root]# mv j2sdk-*-linux-i586.bin /usr/java/
[root]# cd /usr/java/
[root]# ./j2sdk-*-linux-i586.bin
[root]# rm j2sdk-*-linux-i586.bin

Check the installation by printing the product version:

[root]# /usr/java/j2sdk*/bin/java -version

java.sh file

This part of the tutorial describes how to put Java in your path. If you need to run Java from a terminal window without entering the complete path to the java and javac commands each time, you must complete this step.

Note: You may still run NetBeans IDE even without the path.

Create and edit the java.sh file in /etc/profile.d/ with a simple text editor like gedit or Pico so that java and javac commands works for all users:

Warning: Be careful when editing /etc/profile.d/java.sh. You may not be able to run Linux afterwards (for instance, if you forget to type $ in $PATH). In this case, use the Red Hat Linux CD-ROM with boot: linux rescue.

[root]# gedit /etc/profile.d/java.sh
export PATH=$PATH:/usr/java/jdk*/bin/

When you save the file, the file access permissions will look like:

ls -l
-rw-r--r--    1 root     root           44 feb  6 22:11 java.sh

You should now change the file access permission like this:

[root]# chmod +x java.sh
[root]# ls -l
-rwxr-xr-x    1 root     root           44 feb  6 22:11 java.sh

Concept: You may wonder how this would ever work after you log out and back in again, without an explicit command to load the java.sh script. It works because the file /etc/profile executes all scripts in the /etc/profile.d folder.

Note: No other environment variables (such as JDK_HOME, JAVA_HOME or CLASSPATH) are required to run the SDK. However, some applications may require their own environment variables. Check the installation instructions for those applications.

Note: Theoretically, you could edit /etc/profile instead of /etc/profile.d/java.sh, but the latter is easier to maintain. The export NPX_PLUGIN_PATH line is only needed for the Netscape browser Java plug-in. You should not change .bash_profile instead of /etc/profile.d/java.sh, because it will only affect one user.

Save the file and then exit from super-user. Update the NPX_PLUGIN_PATH and PATH environment variables by typing:

  [user]$ source /etc/profile.d/java.sh

Note: This should work because you changed file access permissions earlier. Alternatively you may log out and then in again.

You should check the path and installation from a terminal window:

[user]$ java -version
java version "*"
Java(TM) 2 Runtime Environment, Standard Edition (build *)
Java HotSpot(TM) Client VM (build *, mixed mode, sharing)

Your path and installation is OK, if java prints the product version. If nothing happens, see what your PATH environment variable is set to:

[user]$ echo $PATH

File System Preferences

If you try to run a Swing application with Java 1.4.1 or newer, you will get an error similar to this:

[user]$ java MySwingApp
21.feb.2003 20:22:34 java.util.prefs.FileSystemPreferences$3 run
WARNING: Could not create system preferences directory. System preferences are unusable.

Running a trusted Swing application once as root will create the preferences, and you will never see the message again:

[user]$ su
Password: 
[root]# java MySwingApp
21.feb.2003 20:32:47 java.util.prefs.FileSystemPreferences$3 run
INFO: Created system preferences directory in /etc/.java/.systemPrefs

Java Web Start

The J2SE installation also installs Java Web Start. You may start the Java Web Start from a terminal window:

[user]$ /usr/java/jdk*/jre/javaws/javaws

Create Java Web Start Launcher

  1. Right click the desktop
  2. Click New Launcher
  3. Type in the Name text field: Java Web Start
  4. Type in the Command text field: "/usr/java/jdk*/jre/javaws/javaws"
  5. Click Icon and select: /usr/java/jdk*/demo/jfc/Metalworks/HelpFiles/javalogo.gif

If you have created the launcher already and just need to edit it, just drag it into your text editor, or open the file: .gnome-desktop/Java Web Start.desktop

Note: Unfortunately, the original Java Web Start Launcher logo has been removed from /usr/java/jdk*/jre/javaws/

Java Plug-in installation

This part explains how to install Java plug-in for most new HTML browsers, including the Netscape 7.1 browser and the Mozilla 1.4 browser. If you have an older browser, you should read "Java Plug-in installation for older browsers".

Note: For new browsers based on gcc 3.2 one should explicitly choose the plug-in version compiled with gcc32 in the ns610-gcc32 folder. The plug-in in the ns610 folder won't function. The symbolic link created is placed in the folder similar to /usr/*/browser_name/plugins/

Warning: Note that you must create the symbolic link! It doesn't work just trying to copy libjavaplugin_oji.so to the right spot.

Installing for the Netscape 7.1 browser

Open a terminal window, login as the super-user, and make a symbolic link:

[root]# ln -sf /usr/java/j2sdk*/jre/plugin/i386/ns610-gcc32/libjavaplugin_oji.so /usr/local/netscape/plugins/

Note: This is a very long one line command! If something looks like return, it should be typed as space.

Installing for the Mozilla 1.4 browser

Open a terminal window, login as the super-user, and make a symbolic link:

[root]# ln -sf  /usr/java/jdk*/jre/plugin/i386/ns7-gcc29/libjavaplugin_oji.so /usr/lib/mozilla-1.4.2/plugins/

Note: This is a very long one line command! If something looks like return, it should be typed as space.

Make sure that the Java plug-in is enabled. Click Edit > Preferences... > Advanced > Enable Java.

Check the Mozilla installation by clicking: Help > About Plug-ins. Mozilla should show a message similar to: Java(TM) Plug-in *

Note: Remember to restart Mozilla before checking the Mozilla installation!

What now?

That's it!! Hopefully you now have Java installed on your Linux box, and you may wonder what to do next. Follow the link if you want to compile and run a Java program, or perhaps get started learning Java programming!
See: Sharing Java

Frequently used commands

Open a Terminal Window

To open a terminal window, click Main Menu > System Tools > Terminal.

Note: If you have already opened a terminal window, you don't have to open another one.

Log in as Super-User

To log in as the super-user, type:

[user]$ su
Password: <the super-user password>

Note: If you are already logged in as the super-user, you don't have to log in again.

Note: You may log out as super-user by typing Ctrl+D.

Search for Files

Click Main Menu > Search for Files...

Remove Folders

The tutorial does not explain how you should remove folders, because it is very easy to cause a lot of damage.

Warning: The rm -Rf command may delete your entire hard disk if you do anything wrong. You may feel safer by using a graphical file manager. Make backup of important files before you remove any folders.

Troubleshooting

Can't print the product version

Description: Java gives an error message when I type:

[user]$ java --version

Solution: The option --version contains a typo! You should write -version. Always read the error messages carefully. Usually, it's not too hard to find out what Java complains about:

Unrecognized option: --version
Could not create the Java virtual machine.

Can't unpack files

Description: The file j2sdk-*-linux-i586-rpm.bin does not unpack correctly.

Solution: You may have download problems. Check the file size with ls -l and compare with the file size written on the download page.

Can't run Java applications

Description: Walter 4 told me that a Java application will not run, because there are two or more versions of the package 'j2sdk' installed in your system, and that the application can't decide which version to use.

Solution: The problem could be that you have installed two versions of Java SDK. Try to uninstall the old package with the rpm -e command.

See: www.rpm.org homepage - RPM Package Manager

Can't run new Java version

Description: You may only run an old Java version, and not the new version you just installed.

Solution: The problem could be the jdkgcj package.

See: This tutorial how to deal with the problem.

Description: You may still only run an old Java version, and not the new version you just installed.

Solution: See answer above. If you need both versions, you should probably start Java by specifying the whole part, such as /usr/java/j2sdk*/bin/java. If you find a better solution, please send me an e-mail.

/usr/java/j2sdk*/bin is in the path twice

Description: /usr/java/j2sdk*/bin is in the path twice.

Solution: I've heard that "GNOME" or "X Window" or something runs /etc/profile even if it has been run already. If you have a better explanation or know how to get rid of the problem, please send me an e-mail.

File System Preferences Error

Description: If you try to run a Swing (GUI) application with Java 1.4.1 or newer, you will get an error.

Solution: The first time you run a Swing application, run it from super-user.

FUD Errors

Description: The network is the computer, and because Java is a network language it won't run on Linux because of firewall problems.

Solution: Don't panic! Try to overcome your personal Fear, Uncertainty, and Doubt (FUD), and the problem is going to magically disappear in a puff of smoke!! This works most of the time, because a whole lot of problems simply does not exist at all, or turns out to be much simpler problems when you just relax a little.

The Far Side of Java Installation

This chapter describes things that you would not normally do, but if you really want to do something unusual anyway, this is how to do it...!! Hey, what do I know??

/etc/profile

If you, for some reason, decided to edit /etc/profile instead of /etc/profile.d/java.sh, follow this procedure:

Warning: Be careful when changing /etc/profile. You may not be able to run Linux afterwards (for instance, if you forget to type $ in $PATH). In this case, use the Red Hat Linux CD-ROM with boot: linux rescue.

Edit profile with the gedit editor so that the Netscape browser Java plug-in and java and javac commands works for all users:

[root]# gedit /etc/profile
PATH="$PATH:/usr/java/j2sdk*/bin/"
export NPX_PLUGIN_PATH=/usr/java/j2sdk*/jre/plugin/i386/ns4/

Put the above lines in front of:

export PATH USER LOGNAME MAIL HOSTNAME HISTSIZE INPUTRC

The code should now look like:

PATH="$PATH:/usr/java/j2sdk*/bin/"
export NPX_PLUGIN_PATH=/usr/java/j2sdk*/jre/plugin/i386/ns4/
export PATH USER LOGNAME MAIL HOSTNAME HISTSIZE INPUTRC

Red Hat Linux 8.0 Note

Editing the profile under Red Hat 8.0 requires a different approach. If you are forced under torture to use Java with Red Hat Linux 8.0, this is how to do it:

pathmunge /usr/java/j2sdk*/bin after

Put the above line before:

pathmunge /usr/X11R6/bin after

The code should now look like:

pathmunge /usr/java/j2sdk*/bin after
pathmunge /usr/X11R6/bin after

Finishing touches:

export NPX_PLUGIN_PATH=/usr/java/j2sdk*/jre/plugin/i386/ns4/

Put the above lines in front of:

export PATH USER LOGNAME MAIL HOSTNAME HISTSIZE INPUTRC

The code should now look like:

export NPX_PLUGIN_PATH=/usr/java/j2sdk*/jre/plugin/i386/ns4/
export PATH USER LOGNAME MAIL HOSTNAME HISTSIZE INPUTRC

Java Plug-in installation for older browsers

This part of the tutorial describes how to install the Java plug-in for older browsers.

Installing for Netscape 4.x browsers

This is how to install the Java plug-in for older Netscape 4.x browsers. Open a terminal window, login as the super-user, and edit the java.sh file in the /etc/profile.d/ folder:

[root]# gedit /etc/profile.d/java.sh

The file should look similar to the two lines below:

export NPX_PLUGIN_PATH=/usr/java/j2sdk*/jre/plugin/i386/ns4/
export PATH=$PATH:/usr/java/j2sdk*/bin/

Warning: Be careful about typos when editing /etc/profile.d/java.sh. You may not be able to run Linux afterwards (for instance, if you forget to type $ in $PATH). In this case, use the Red Hat Linux CD-ROM with boot: linux rescue and fix the typo.

Make sure that the Java plug-in is enabled. Click Edit.Preferences... > Enable Java > Enable Java Plugin.

Installing for Mozilla 1.2.x browsers

This is how to install the Java plug-in for older Mozilla 1.2.x browsers. Open a terminal window, login as the super-user, and make a symbolic link:

[root]# ln -sf /usr/java/j2sdk*/jre/plugin/i386/ns610/libjavaplugin_oji.so /usr/lib/mozilla/plugins/

Note: This is a very long one line command! If something looks like return, it should be typed as space.

Note: You should explicitly choose the plug-in in the ns610 folder for older browsers, and not the plug-in in the ns610-gcc32 folder.

Note: The Mozilla folder/directory is named "mozilla-1.0.1" under Red Hat 8.0. However, it is called mozilla under Red Hat 7.2 and 9!

Make sure that the Java plug-in is enabled. Click Edit > Preferences... > Advanced > Enable Java.

Check the Mozilla installation by clicking: Help > About Plug-ins. Mozilla should show a message similar to: Java(TM) Plug-in *

Glossary

Alpha Release

An alpha release is an incomplete program that includes most major features. An alpha release is used for fixing bugs and bad features.

API (Application Programming Interface)

The Java API is a library of Java packages each containing related classes.

Beta Release

A beta release is a complete program, but not a stable or finished product.

JavaScript

Scripting language from Netscape, formerly known as LiveScript. JavaScript and Java are different languages. Netscape renamed LiveScript to JavaScript in order to confuse developers.

J2 (Java 2 Platform)

Sun Microsystems cunningly coined the 1.2.2 and later releases as the Java 2 Platform in order to confuse everyone. See: http://java.sun.com/products/archive/

J2SE with NetBeans IDE Cobundle

Also known as J2SE with Sun ONE Studio, Community Edition.

JDK (Java Development Kit)

Also known as SDK. Sun Microsystems cunningly renamed JDK to SDK in order to confuse everyone.

JRE (Java Runtime Environment)

The JRE is included in the SDK.

RC (Release Candidate)

A Release Candidate is very close to the launch version, and is meant to be a complete version in its final form. A Release Candidate is used for widespread testing, just in case there are any remaining bugs.

SDK (Software Development Kit)

Formerly known as JDK. The SDK contains development tools & APIs and the JRE.

SE (Standard Edition)

JRE or SDK

Recommended Links

References and Acknowledgments

  1. The Linux logo, created by Andreas Dilger, was stolen from http://www-mddsp.enel.ucalgary.ca/People/adilger/logo/
  2. The idea of creating the file /etc/profile.d/java.sh was found on several web pages using Google, for instance Ed Halley's Linux Roadmap, Installing Java.
  3. Lauri wrote the Red Hat Linux 8.0 note for me, and also made many useful suggestions.
  4. Walter had a solution to multiple versions of Java packages.
  5. Steve explained why JVM will not ever be a part of Red Hat Linux.
  6. Dennis suggested an entry for troubleshooting that should explain solutions to common problems, rather than just mention known problems.
  7. Igor explained how to link the Java plug-in properly with Mozilla 1.4.
  8. Tristan and Christian explained how to link the Java plug-in properly with Netscape 7.1.
  9. Luke explained how to give java.sh execution permissions for all users.

What's new?

Version 1.1.2, October 5. 2004

  • The tutorial is updated for java version "1.5.0"
  • Removed the "Testimonials" page, because it takes way to much space. Thank you all for great feedback!! Send more!!
  • Explained how to give java.sh execution permissions for all users.
  • Explained why you need the java.sh file.
  • Explained better why editing java.sh can be dangerous
  • Explained better what to do if OS do not recognize RPM.
  • Explained how to handle the java --version typo error.
  • Explained the File System Preferences Error
  • Explained the firewall problems
  • Explained FUD Errors
  • Explained a little better about environment variables such as JDK_HOME, JAVA_HOME or CLASSPATH
  • Explained that you must create the symlink, not just copy the libjavaplugin_oji.so.
  • Explained that the tutorial is a lot shorter than it looks like, most of the material is to keep trouble away.

Version 1.1.1, January 23. 2004

  • Changed fonts from Microsofts "Arial" to "Bitstream Vera Serif".
  • Updated "Java Plug-in installation" for Netscape 7.1.

Version 1.1.0, January 20. 2004

  • Renamed "Known Problems" to "Troubleshooting". The idea is to take a more active approach to problem solving.
  • Added: "Uninstalling the Software"
  • Added: "Java Web Start"
  • Added: "jdkgcj"
  • Added: "The Far Side of Java Installation"
  • Added: "What's new?"

Version 1.0.x, February 10. 2002

  • The tutorial should not be specific to Red Hat Linux only, so the name was changed from "Installing Java for Red Hat Linux HOWTO" to "Installing Java for Linux HOWTO".

Friday, June 03, 2005

Thursday, June 02, 2005

Classes

Classes are the blueprints that describes objects. See Object-oriented programming

You can write your own classes easily like this:

package animalfarm;

class Dog {
}

public class Main {
   public static void main(String[] args) {
   }
}

This is the code for the Dog class: class Dog { }. Uh, oh, the name of the package is borrowed from Orwell (1945). Let's write some more classes!

package animalfarm;

class Pig {   
}

class Dog {
}

class Chicken {
}

class Pigeon {   
}

class Sheep {   
}

public class Main {
   public static void main(String[] args) {
   }
}

That's pretty easy, right!

References

http://en.wiktionary.org/wiki/Category:Animal_sounds

Operators

Introduction

We need to be able to do something with the values. Operators is what you can do with the values.

The operators in Java are:

Operator =
'=' | '>' | '<' | '!' | '~' | '?' | ':' | '==' | '<=' | '>=' | '!=' | '&&' | '||' | '++' | '--' | '+' | '-' | '*' | '/' | '&' | '|' | '^' | '%' | '<<' | '>>' | '>>>' | '+=' | '-=' | '*=' | '/=' | '&=' | '|=' | '^=' | '%=' | '<<=' | '>>=' | '>>>=' ;

Program

package bloggingjava;

class Main {
    public static void main(String[] args) {
        System.out.println(6 * 9);
        System.out.println(42 % 9);
        System.out.println(true | false);
    }
}

Output

54
6
true

Friday, May 27, 2005

class body

This is a class body.

class MyClass {
}
ClassMemberDeclaration =
FieldDeclaration | MethodDeclaration | ClassDeclaration | InterfaceDeclaration | ';' ;

Class bodies are used to group class members, such as methods that belong together.

Objects

"Programmer: A red-eyed, mumbling mammal capable of conversing with inanimate objects."
(Anonymous)

An object is a class instance (JLS3 2005).

You can create your own objects from your own class like this:

package animalfarm;

class Dog {
}

public class Main {
    public static void main(String[] args) {
        new Dog();
    }
}

The statement that creates the object is new Dog();.

Well, actually, the object may get garbage collected almost before it is created, so we need a pointer for it.

package animalfarm;

class Dog {
}

public class Main {
    public static void main(String[] args) {
        Dog dog = new Dog();
    }
}

The statement Dog dog = new Dog(); creates the dog pointer and the Dog object. Then the memory location of the object is assigned to the pointer.

The cool thing about OOP is that you can create as many objects as you like from the class! What will happen if you print the objects after they are created?

package bloggingjava;

public class Main {
    public static void main(String[] args) {
        Dog dog1 = new Dog();
        Dog dog2 = new Dog();
        Dog dog3 = new Dog();
        
        System.out.println(dog1 == dog2);
        System.out.println(dog1 == dog3);
        System.out.println(dog2 == dog3);
    }
}
false
false
false

The program compares the references (or pointers) to the objects using the reference equality operator ==. Obviously, each reference points to an unique object, because each comparison is false.

toString

Program

public String toString() {
    return getClass().getName() + "@" + Integer.toHexString(hashCode());
}

Source: Object.java (Sun Microsystems 2006).

Applications

"Real Programmers don't write application programs, they program right down on the bare metal. Application programming is for feebs who can't do system programming."
(Vleck 1982).

Introduction

Here you will learn what an application is, and about the different parts of an application. Later you will learn how to write and save an application using a text editor, how to compile an application and how to run an application.

Program

Any Java application must follow this structure:

// declare package after this line

// import classes or packages after this line

class JavaApplication {
    public static void main(String[] args) {
        // enter code after this line
    }
}

An application that follows this structure is the HelloWorld application, a typical "first program" printed in most text books:

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

Output

This program is supposed to print "Hello World" to the screen, but does nothing much yet, because it has to be compiled and executed first.

Discussion

Now, you will get a quick tour of the code.

Also remember that Java is case-sensitive!

Types of Applications

Such Java applications are running in a terminal window in text mode. It is possible to extend this application to build much more sophisticated applications, such as GUI applications and applets, by importing parts of the Java library. Read about Swing for GUI applications (reference needed).

class

class HelloWorld {
}

This part of the code is called a class declaration, and contains the parts of the class called the class members which is actually the rest of the program code. Be aware that a program can have many classes.

Now, consider the HelloWorld application. Java programs seems impossible to apprehend at first sight. You should always do the simplest thing that works, right? Would it not be much simpler just to write:

println("Hello World!");

Why do we have to write all that other stuff? The main reason for the extra code in Java, is that Java forces us to use object-oriented programming (OOP). This program isn't much OOP-ish, but even so OOP dictates that all code should go inside classes.

main

The method main is where the Java interpreter will start the program execution. The Java Virtual Machine assumes that the class contains a method called main, where execution will begin, and that will take the program parameters called args.

public static void main(String[] args) {
}

It is a convention to write method main as public static void main(String[] args) {, but you could also write:

  public static void main(String args[]) {
  public static void main(String[] arguments) {
  static public void main(String[] args) {

Note: Many classes in a Java application may contain a main method. This means that a Java application may have more than one possible starting point.

public

Consider the code:
public class JavaApplication { // unusual
    public static void main(String[] args) {
        // enter code after this line
    }
}

You don't normally need to use access modifiers like public for the class containing the main method. However, Netbeans IDE 5.0 declare its Main classes as public. It is not necessary to declare the the class public. The Java environment executes the main method anyway.

static

static is used so that main can be called without first making an instance of the class. That is, main is a class method.

void

The keyword void simply means that the method main does not return anything.

String[] args

Consider the code:
    public static void main(String args[]) { // not so good

This code works, but you should write String[] args and not String args[], because it is easier to see that args is a String array.

println

System.out.println("Hello World!");

This is the statement that prints "Hello World!".

References

Constants

"The primary purpose of the DATA statement is to give names to constants; instead of referring to pi as 3.141592653589793 at every appearance, the variable PI can be given that value with a DATA statement and used instead of the longer form of the constant. This also simplifies modifying the program, should the value of pi change." (Wikipedia 2006)
FORTRAN manual for Xerox computers

Introduction

Constants are called final variables in Java. Variables that should never change value should be declared final Constants are usually declared public static final. PI is for example declared as public static final double PI = 3.14159265358979323846; (and as you may have observed, the value of PI did actually change since the FORTRAN days...)

Program

package bloggingjava;

class Main {
    public static void main(String[] args) {
        final int MONTHS;
        MONTHS = 12;
        // MONTHS = 13; // error, already assigned
        System.out.println("MONTHS: " + MONTHS);
    }
}

Output

MONTHS: 12

References

Static Factory Methods

Static factory methods is sometimes used instead of constructors (Bloch 2001).

Problem with constructors is that constructors do not have their own name, but same name as its class (Bloch 2001):

  • the name does not describe what the constructor returns (Bloch 2001).
  • must create a new object when invoked/called (Bloch 2001)
  • only one constructor with a given signature (Bloch 2001)
  • constructors can't return subclasses of class (Bloch 2001)

Definition: A static factory method is a public method that returns an instance of its class.

Naming Conventions

Bloch (2001) argues that adhering to standard naming conventions for static factory methods will make them readily distinguishable from other static methods, and says that the two names valueOf and getInstance are becoming common, the idea beeing that valueOf should return an instance that has the same value as its parameters and getInstance should return an instance described by its parameters.

However, it seems that both names are not much in use as of j2se 1.5.0. valueOf seems currently to be used mostly for type wrappers, and getInstance does not seem to be used that much. Perhaps a problem with standard naming conventions for static factory methods is that the name no longer really reflects what the method does. And after all, there already is a standard naming convention for constructors.

Examples of static factory methods

  • the public static Integer valueOf(int i) { method of class Integer
  • Conclusion

    * static factory methods have names (Bloch)
    * can return existing objects (Bloch)
    * can return subtypes (Bloch)
    * new is the standard way of creating objects (Bloch)
    * valueOf should return an instance with the same value as the parameters (Bloch)
    * getInstance should return an instance described by the parameters (Bloch)
    

    Thursday, May 19, 2005

    Explicit and Implicit Code

    Introduction

    There is basically two methods of writing program code. You could write all the code yourself explicitly, or you could let the compiler write some of the code for you implicitly.

    Discussion

    The words explicit and implicit are used extensively in most Java books and web pages. Obviously, it is important to know and understand the meaning of these words, so let's take a closer look at them.

    Implicit Code

    Introduction

    Wouldn't it be great if the compiler could write a lot of code for you automatically? Especially the boring, tedious stuff that always must be there, but that you would rather not write until absolutely necessary...

    Well, the compiler does just that, and often without the programmer even knowing. It's called implicit code, and is source code that is implied rather than directly expressed. The idea behind implicit code is that you do not have to do all the work yourself, because the compiler will write the code for you. Since the source code is implied, it does not actually show up in your program. But implicit code certainly end up as a part of the compiled code.

    Concept: Implicit code is source code that is implied rather than directly expressed.

    Program

    Consider the program:
    class Compute {
        public static void main(String[] args) {
            System.out.println(3 + 2 * 2);
        }
    }
    

    Output

    [user]$ javac Compute.java
    [user]$ java Compute
    7
    

    The application writes 7, not 10, because the compiler implicitly adds paranthesis around the operator with the highest precedence, 3 + (2 * 2).

    Discussion

    The compiler fills in the missing code implicitly for you, when needed, without actually changing the source code itself. Only the compiled code is affected. As a result, the source code look simpler, less cluttered and possibly you will also avoid a few bugs. On the other hand, you can always explicitly write the code yourself, if you want to.

    The code production is not totally random or uncontrollable. The compiler applies certain rules in order to discover implicit code when compiling source code. The rules will be discussed later at various places in the tutorial.

    Concept: Following certain rules, implicit code is added implicitly by the compiler.

    Note: There's a lot of implicit stuff going on in Java. The reason is that many programmers usually view implicit features as a convenience. However, the rules for implicit code must be clearly understood and always be remembered, actually making programming less comfortable or easy in many situations.

    Explicit Code

    Introduction

    Usually, you will write explicit code in order to avoid ambiguous code or simply because there is no implicit alternative.

    Concept: Explicit code is source code that must be expressed completely.

    Program

    Consider the program:
    class Compute {
        public static void main(String[] args) {
            System.out.println(3 + 2 * 2);
        }
    }
    

    Output

    7
    

    Discussion

    Imagine that the programmer thinks that it is unclear which operation, + or *, is performed first.

    class Compute {
        public static void main(String[] args) {
            System.out.println((3 + 2) * 2);
        }
    }
    

    Parenthesis has been explicitly added around 3 + 2 in order to avoid any ambiguity.

    Sunday, May 15, 2005

    Louden 1997

    Author Louden, Kenneth C.
    Year 1997
    Title Compiler Construction, Principles and Practice
    Place
    Publisher

    Saturday, May 14, 2005

    Cho 2004

    References

    Wednesday, May 11, 2005

    Memoization

    Introduction

    Instead of recomputing results for each function call, the results of function calls can be stored for later reuse. This technique is called memoization (Wikipedia 2007).

    Program

    class Fib {
        static long[] fibarray;
        
        public static void main(String[] args) {
            int n = Integer.parseInt(args[0]);
            
            fibarray = new long[n + 1];
            fibarray[1] = 1;
            fibarray[2] = 1;
            
            for (int i = 1; i <= n; i++) {
                System.out.print(memoizedFib(i) + " ");
            }
            System.out.println();
        }
        
        public static long memoizedFib(final int n) {
            return fibarray[n] == 0 ? fibarray[n] = memoizedFib(n - 1) + memoizedFib(n - 2) : fibarray[n];
        }
    }
    

    Output

    [user]$ javac Fib.java
    [user]$ java Fib 92
    1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946 17711 28657 46368 75025 121393 196418 317811 514229 832040 1346269 2178309 3524578 5702887 9227465 14930352 24157817 39088169 63245986 102334155 165580141 267914296 433494437 701408733 1134903170 1836311903 2971215073 4807526976 7778742049 12586269025 20365011074 32951280099 53316291173 86267571272 139583862445 225851433717 365435296162 591286729879 956722026041 1548008755920 2504730781961 4052739537881
    6557470319842 10610209857723 17167680177565 27777890035288 44945570212853 72723460248141 117669030460994 190392490709135 308061521170129 498454011879264 806515533049393 1304969544928657 2111485077978050 3416454622906707 5527939700884757 8944394323791464 14472334024676221 23416728348467685 37889062373143906 61305790721611591 99194853094755497 160500643816367088 259695496911122585 420196140727489673 679891637638612258 1100087778366101931 1779979416004714189 2880067194370816120
    4660046610375530309 7540113804746346429
    

    References

    Monday, May 09, 2005

    Barron 1977

    Author David William Barron
    Year 1977
    Title An Introduction to the Study of Programming Languages
    Place Cambridge
    Publisher Cambridge University Press

    Friday, May 06, 2005

    Cleaveland 1986

    (Cleaveland 1986).

    References

    • Cleaveland, J. Craig. (1986). An introduction to data types. London: Addison-Wesley.

    Wednesday, May 04, 2005

    Syntactic Salt

    Introduction

    Syntactic salt is a feature designed to make it harder to write bad code. An example of syntactic salt in Java is Generics. The need for adding a semicolon, ;, after each and every statement could be viewed as syntactic salt.

    Concept: Syntactic salt are constructs added to a language in order to make it harder for programmers to write bad source code.

    Resources

    Sunday, May 01, 2005

    Varargs

    Introduction

    Varargs are methods with variable number of arguments (Schubart 2004).

    Discussion

    The format method takes varargs: public static String format(String pattern, Object... arguments)

    import java.text.MessageFormat;
    
    class JavaApplication {
        public static void main(String[] args) {
            String pattern = "{0} weigh {1} kg.";
            String message = MessageFormat.format(pattern, "Polar bears", new Integer(800));
            System.out.println(message);
        }
    }
    
    [user]$ javac JavaApplication.java
    [user]$ java JavaApplication
    Polar bears weigh 800 kg.
    

    What happens is that the compiler write this code implicitly: String message = MessageFormat.format("{0} weigh {1} kg.", new Object[] {"Polar bears", new Integer(800)});

    Conclusion

    Varargs is a case of syntactic sugar. The compiler treats public static String format(String pattern, Object... arguments) like public static String format(String pattern, Object[] arguments)

    References

    Resources

    Saturday, April 23, 2005

    Halfon 2003

    Author Halfon, Amir
    Year 2003
    Title New Java Language Features in JDK 1.5
    Place
    Publisher Sun Microsystems
    Retrieved Saturday, April 23, 2005
    URL http://www.javasig.com/Archive/lectures/JavaSIG-Tiger.pdf

    Wednesday, April 20, 2005

    Parameters and Arguments

    Introduction

    A parameter is a variable named inside the parentheses of a method definition (Kernighan & Ritchie 1988).

    An argument is the value for a parameter used when calling the method (Kernighan & Ritchie 1988).

    Discussion

    formal argument == parameter
    actual argument == argument
    (Kernighan & Ritchie 1988).

    References

    • Kernighan, Brian W. & Dennis M. Ritchie. (1988). The C programming language. New Jersey: Prentice Hall.

    Tuesday, April 19, 2005

    JLS3 2005

    The Java Language Specification, Third Edition is now available in a pre-publication PDF release.

    You may find a clickable version of the grammar here: The Java JLS3 Grammar.

    ID JLS3
    Author Gosling, J., B. Joy, G. Steele & G. Bracha
    Year 2005
    Title The Java Language Specification, Third Edition
    Place Boston
    Publisher Addison-Wesley
    Retrieved March 4, 2006
    URL http://java.sun.com/docs/books/jls/

    Saturday, April 16, 2005

    Quote of the Day

    "If a program is useful, it must be changed."
    (Anonymous).

    Friday, April 15, 2005

    How to add Button Color

    Program

    Basic idea

    JButton colorButton = new JButton("Color Button");
    colorButton.setBackground(Color.red);
    colorButton.setForeground(Color.white);
    

    Complete program

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    
    public class SwingApplication extends JFrame {
        public static void main(String[] args) {
            new SwingApplication().createFrame();
        }
    
        void createFrame() {
            setTitle(getClass().getName());
            createContentPane();
    
            addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent e) {
                    System.exit(0);
                }
            });
    
            pack();
            setVisible(true);
        }
    
        void createContentPane() {
            JPanel jPanel = new JPanel();
    
            JButton grayButton = new JButton("Gray Button");
            JButton colorButton = new JButton("Color Button");
            colorButton.setBackground(Color.red);
            colorButton.setForeground(Color.white);
    
            jPanel.add(grayButton);
            jPanel.add(colorButton);
            getContentPane().add(jPanel);
        }
    }
    

    Output

    [user]$ javac SwingApplication.java
    [user]$ java SwingApplication
    

    Quote of the Day

    "Real Programmers don't eat quiche. They eat Twinkies. And Szechwan food. (Do not go to eat Szechwan food with a group of Real Programmers unless you are prepared to argue bitterly over the last spring roll.)"
    (Vleck 1982).

    References

    Thursday, April 14, 2005

    Iteration

    "Q: How do you keep a programmer in the shower all day? A: Give him a bottle of shampoo which says "lather, rinse, repeat.""

    Introduction

    Iteration is also known as loop or repetition. A statement or a block of statements are executed repeatedly as long as a specified condition is true.

    Infinite loop

    Program

    public class Loop {
        public static void main(String[] args) {
            for(; ; ) {
                System.out.println("Java is cool");
            }
        }
    }
    

    Output

    Java is cool
    Java is cool
    Java is cool
    Java is cool
    Java is cool
    ...
    

    Infinite counting

    Program

    public class Loop {
        public static void main(String[] args) {
            for(int i = 0; ; i++) {
                System.out.println(i);
            }
        }
    }
    

    Output

    0
    1
    2
    3
    ...
    

    Counting to "ten"

    Program

    This program counts 10 numbers, from 0 to 9.

    public class Loop {
        public static void main(String[] args) {
            for(int i = 0; i < 10; i++) {
                System.out.print(i + " ");
            }
        }
    }
    

    Output

    0 1 2 3 4 5 6 7 8 9 
    

    Resources