Where to find tutorials and documentation
Check www.netbeans.org for the most current documentation and recent articles. There are tutorials at www.netbeans.org, both for developing Java program with the Matisse GUI editor, and without, and for different versions of NetBeans.
Version Without the Matisse editor With Matisse
5.5 NetBeans IDE 5.5 Quick Start Guide www.netbeans.org/kb/55/quickstart-gui.html
The Matisse tutorials have good Flash animations showing how things were done. You can read the main page easily, but you'll need a reasonably fast Internet connection to download the animated Flash lessons.
Starting a new GUI project in NetBeans
My notes below overlap the (better) www.netbeans.org tutorial to some extent (see above).
Matisse is the name given to the GUI builder in NetBeans. It generates code from the WYSIWYG design. This is an excellent GUI editor, and with a little practice you can create attractive GUIs very quickly.
Tutorials. In addition to the notes below, you can learn how to use the Matisse editor the following places.
GUI Building in NetBeans IDE 5.5 is an excellent place to start, including a downloadable tutorial.
Building an SDI Application with NetBeans by Chuck Emerson-Henry is a nice example of using the GUI editor.
Building Java GUIs with Matisse: A Gentle Introduction by Dick Wall.
NetBeans IDE 5.5 GUI Builder Visual Feedback Legend Shows some of the feedback and controls when using Matisse. Worth taking a look at after you've tried it.
Starting a new GUI project (covered in the www.netbeans.org tutorial)
These instructions assume the project window is in the upper left, and the properties window is in the lower right of the screen. You might find them minimized with icons along left/right screen edges.
(Menu) File, New Project....
(Dialog) Take the default General and Java Application. Click Next.
(Dialog) Specify where you want it, and what to call the project directory. Unselect Create Main Class because you'll use the GUI class as the main class. Set as Main Project should be checked. Click Finish. This creates a project with the default package, but we'll create a project in the next step.
(Project pane, right click the project) Select New, JFrame Form...
(Dialog) Fill in the Class Name and Package fields. You can leave your program in the package, but it is highly recommended to create a named package. you can create multilevel packages by simply typing the the packages names separated by dots, eg. com.fredswartz.flograf . Click Finish.
You now have a working program with a functioning main program and (empty) window. Try running it. The code that NetBeans generated contains a main method, so it runs and does nothing. You'll have to confirm that this is the "main class" (where the main method you want to use is located) the first time you run it.
GUI editor - Toggle between Source and Design views
At the top left of the toolbar for GUI editor there are Source and Design buttons. Click on Source to see the generated code, and Design to work on the the window's appearance.
Design view. The default view is GUI design view, which shows approximately what the window will look like. You can select GUI components from the pallette at the top right, and click on the window to place them. You can drag and stretch them to get the right layout.
Source view. This shows the code that has been generated by NetBeans to build this GUI. The code with the blue background, called "guarded text", is uneditable. The sections in white can be edited to customize the code in several ways, but especially to add data binding code to connect it to your model/logic. The parts that are uneditable are:
The declarations of the components, which are placed at the end, which is a bit unusual. You can change the names of components in the design view properties pane.
The initComponents() method, which is called from the constructor. You can edit the constructor to add your own code as necessary (eg, to initialize your model class.
The headers and enclosing braces of "handlers" (methods called by listeners to handle the event. You must write the code for the body of the handlers to make them do what they need to do.
There are several things that you need to do to make this into a useful program.
Layout components. Use the GUI editor to layout your program. This is the most fun because you can create some good looking designs very quickly, in contrast to the normal layout struggles with the clumsy Java layout managers. With a little practice you can get things to work pretty well.
Edit component properties. You will want to edit some of the properties of components.
Right click component. Some of the very most common properties can be set by right clicking the component and selecting one of the options (eg, to change the text, the name of the corresponding variable, and create a listener).
Properties pane. There are a huge number of properties, but only a few are useful. The Properties panel puts them in several categories, and you will probably only need to use the first category, if any (Properties, Other Properties, Layout, and Accessibility).
Listeners and handlers. If you specify that a component should respond to an event (eg, ActionPerformed for a button), the GUI editor generates an anonymous, inner-class listener, which calls a method based on the name of the component. For example, if you have button in a variable called greetingButton, when you indicate that you want an action listener by right clicking the component and selecting Events > Action, it creates a listener that calls a handler method called greetingButtonActionPerformed(). Type code for the action you want inside this method.
Alternative - Properties pane. In the Properties window or popup there are three tabs at the top. The Events tab lets you specify which method should be called by the listener. Type in the method name and it will be created if necessary. Type your code in this method.
GUI editor - Structure of the generated source code
NetBeans automatically generates a lot of code for the GUI. Most of it can be ignored, and you only have to write the code in the event handlers, and initialize your "model" (logic) in the constructor.
Blue shaded areas are generated code that you can't edit.
Expand/collapse controls at are the beginning of each section. Just hit the "+" to expand, and the "-" to collapse the view.
No imports are used, so all library classes will be fully qualified (eg, javax.swing.JButton instead of just JButton as a human would write it).
Instance variables are declared at the end of the class, not near the beginning, as is the normal human style.
The constructor calls on the initComponents() method to do all the initialization. initComponents() is in the collapsed, uneditable area below the constructor.
The constructor itself is editable, so you can put your own initializations in it. Because you should separate your model/logic from the user interface, you may create an instance of your model in the constructor, and declare an instance variable at the end to hold it. The listener methods can then use that instance variable to interact with the model.
The initComponents() code is generated by NetBeans, and isn't necessarily a good model for writing code yourself. If you decide to look at it, you will see several unfamiliar things. For example, GroupLayout won't appear until Java 6. Button listeners are done as anonymous, inner-class listeners, ...
The main method is defined near the end, just above the instance variables, and contains what might be an unfamiliar way to display the window. This is equivalent to
YourGUIClass window = new YourGUIClass();
window.setVisible(true);
This runs the initialization code on the EventQueue thread because there are some (uncommon) situations where it makes a difference. Don't bother to change it, but when you write your own programs you can use the simpler code above. Or you can use the NetBeans main style. In any case, it's probably easiest to just collapse this code and never take another look at it.
GUI editor - Connecting components to code (listeners, handlers) - Data binding
To create a button you would put the button on the JFrame, or select it if it's already there, then right click the component and select Edit Text to put the right text on the button top. To add code to handle the actionEvent that is generated when a button is clicked, do the following.
Choose a good variable name. Right click the component and select Change Variable Name... to set the variable name to something meaningful.
Listener. Right click the component and select Event > Action > actionPerformed. This will generate a listener, and generate the top and bottom lines of a "handler" method that is called by the listener when the button is clicked.
Handler method. The name of this methods is the name of the JButton variable that you chose in a previous step, followed by "ActionPerformed", so choose a good name for the button. Write code to do what you want inside this method. Typically this code will have some interaction with the model and other components.
search topic
Tuesday, November 20, 2007
NetBeans GUI Projects
NetBeans IDE
Sections:
Introduction - Powerful, free, useful to students
Downloading NetBeans
Where to find tutorials and documentation
Starting a new project in NetBeans
Settings in NetBeans you might want to change
Packaging resources with your jar file.
Other features you might want to use
Introduction - Powerful, free, useful to students
NetBeans is a free, open-source, IDE which is available at www.netbeans.org. This is a reasonable choice, and liked by many programmers. It's similar to IntelliJ IDEA (expensive) or Eclipse (free), but it has some advantages: cheaper in the case of IntelliJ IDEA, a very good GUI form editor, and easy to install. Overall a very good choice, and my favorite.
Immediate error messages. One of the most useful features for students is the jagged red line under erroneous statements when there's a pause in the typing. NetBeans continuously compiles the program as you're typing it to alert you when there's an error. It's like the continuous spell checking of some word processors. I've gotten so used to this feature that I feel uneasy when I use an editor that doesn't do it.
Indentation and braces are serious problems for beginning students. Right clicking the source code and choosing Reformat Code reformats the entire file if nothing is selected, otherwise only the selected text. Placing the cursor beside a brace shows the matching brace.
Renaming is one of the most common operations, and NetBeans makes this easy -- even when renaming a variable like "a" because it parses the text and doesn't just use a simple textual match.
Downloading NetBeans
You must install the Java JDK before installing NetBeans. Go to java.sun.com and download J2SE 5.0 (or more recent version -- Java SE 6.0 beta 2 is quite satisfactory). Sometimes there is a link to a bundled version of the JDK and NetBeans, which, if available, can be used to install both at the same time. Otherwise install the JDK, then download and install NetBeans, which can be downloaded from www.netbeans.org.
Where to find tutorials and documentation
Check www.netbeans.org for the most current documentation and recent articles.
NetBeans tutorials (GUI and non-GUI) from www.netbeans.org. There are tutorials at www.netbeans.org, both for developing Java program with the Matisse GUI editor, and without. Version Without the Matisse editor With Matisse
5.5 NetBeans IDE 5.5 Quick Start Guide www.netbeans.org/kb/55/quickstart-gui.html
The Matisse tutorials have good Flash animations showing how things were done. You can read the main page easily, but you'll need a reasonably fast Internet connection to download the animated Flash lessons.
The Hello World with NetBeans 4.1 tutorial from faculty.ed.umuc.edu/~arnoldyl/ should work pretty well for version 5.5 too.
I've added a section below that also gives some help getting over thru the first dialog. If you have trouble with that first dialog box, it's not you; this is the original Dialog from the Black Lagoon.
Starting a new project in NetBeans
Creating a new project isn't hard, altho the second dialog box can be slightly confusing at first. If you have trouble creating a new project, create a few dummy projects just to get used to the quirks of this first step. Just create and throw them away. It only expect to throw away the first first several attempts at building your first project. I did. It's not so bad after you've done it a few times.
Click New Project in File menu or Welcome window.
Choose Category General, and Project Java Application (probably the defaults). Click Next.
The New Java Application dialog box can be surprisingly awkward to use, but it is asking from some simple information: the name of the project, the directory you want to put the project in, and the name of your "main" class, if there is one. It's made more confusing than necessary because NetBeans tries to help you by making very bad default choices for you, which causes more problems than solutions. If you try to fill in the text fields in an order that makes sense to you, you might be very surprised that the the fields interact with each other so that it overwrites what you typed earlier. Well intentioned but very, very annoying. After you use it a few times, it becomes easy.
Project Name. This is not only the name of the project, but it also used to create a directory/folder by that name, and after mangling the name, it becomes the default package name. This field starts with an unhelpful name like "JavaApplication5" - change it.
Just to test it, try typing something in upper case with spaces in it, for example "X Y" (without the quotes). You'll notice in the Project Folder text field that it plans to create a folder with that name. In addition, in the last, unnamed, text field there is the same text turned to lower case, without blanks, followed by ".Main". This lower case, deblanked version will be the package name.
Choosing a lower case no-blank name for the project name is probably the least confusing to start with. That way, the project, the folder, and the package all have the same name.
Oops! I've typed in "Problem1", but if I wasn't too lazy to redo the image, I'd change that to use a more meaningful name, and make it all lower case.
Choose a Project Location. This is the folder in which your project folder will be created. You can have many projects in this folder, so it would be best to create a folder that you will use for all projects for a class, perhaps something like "cmis141". You can either use the Browse button to find and/or create the folder, or type in a directory path. The Project Folder field below should now be automatically set for you using a combination of the Project Name and Project Location.
Set as Main Project. Check this box. This indicates that the project will contain a main method and can be run as an application. Even if you don't set it now, you can later. Don't be surprised if NetBeans asks you to set it again -- it's sometimes forgetful.
Create Main Class. Check this box. Clicking Finish creates a class from a standard template. It contains javadoc comments, an empty constructor, and a main method.
If you didn't check the Create Main Class box, you can create a Java source file and main method later. To edit template with your own initial text see below.
Package name and main class name are shown in the field after the Create Main Class check box.
Change Main class name. The class name is the part after the dot and defaults to the unhelpful "Main" name. Do not use this default name. Change the name to something more meaningful like "LeapYear" or "Sudoku". Remember that class names start with an upper case character. It's fairly easy to rename classes later in NetBeans using the Refactor > Rename... popup, so don't worry if you later decide on a better name. Getting class names right is important, and I often rename my classes.
The package name is the part before the dot. It will probably already have been set from the Project Name field, but you don't really have to use this default package name. You can change it to any legal package name, or even get rid of it entirely (and the dot) to make it a "default" package. I often use "com.fredswartz.whatever" to put my "whatever" package in a package hierarchy that uniquely identifies it as mine. Package names should be in lower case.
Anonymous / default package. You technically don't have to use packages, but Sun strongly recommends that you do because it may make it easier to access resources after you've deployed your program.
Finish. All project files will be created when you click this. The main class of your project should now be showing in the editor window. It's ready to run and you can just click the green arrow to test it at this point. Of course it doesn't do anything yet, but you can at least verify that it compiles and "runs".
The left panel now shows your project, and the right panel shows a source file. If necessary, in the project panel expand the project, then Source Packages, then the package, and now you can see all Java source files in your project.
Compiling and Running your programs in NetBeans
NetBeans allows a very quick code and test cycle. Change the source code and hit the right-facing green arrow in the toolbar to run it. This recompiles only the changed source files.
Clean and Build. The other option you should use is Clean and Build Main Project from the Build menu, or Clean and Build Project from the menu that drops down from a right click on the project. This action removes all object files and recompiles everything. This is important if you rename classes, change static final constants, need a new jar file, and probably in a few other cases. Always use this when you think you've finished a program -- it's better to have the surprises before turning it in to your instructor.
Double-clickable jar file. Build and Clean and Build create a double-clickable jar file in the "dist" directory in your project.
Settings in NetBeans you might want to change
Indentation style settings
To change editor settings.
Click the Tools > Options menu item.
In the icon display on the left, click Editor.
In the right panel, select the Indentation tab.
If it isn't already done, set the following:
Statement continuation Indent: 8
Number of Spaces per Indent: 4
Check Expand Tabs to Spaces.
If you like the Allman indentation style, check the Add New Line before Brace box.
Modifying the initial template for Java classes
When NetBeans creates one of several different types of initial files for you, it uses a template. Edit one or more of these templates so the files start with the text you want, eg, comments with your name, etc.
Select the Tools > Template Manager menu item. This displays a dialog box.
Expand the Java Classes tree folder in the dialog box. [Ignore all the other folders.]
Select Java Main Class or Java Class because these are what you will be using. Click the Open in Editor button at the bottom of the dialog box.
Edit the file to look like what you want your initial file to look like. I typically change the comments to my preferred style. The text contains predefined symbols, like __DATE__, which will be expanded as appropriate when the template is used.
Save it.
Changing to generic, type-safe, data structures. Deprecation warnings.
When compiling a program that uses non-generic data structures, it's possible to accidentally add an element of the wrong type. To alert you to places where this might be a problem, add
Right click on the project in the Projects panel at the left.
Select Properties at the bottom of the popup menu.
Click on Build > Compiling in the left panel.
To enable the most useful compiler warnings, in the Additional Compiler Options, put
-Xlint:all -Xlint:-serial
-Xlint:unchecked <[>Click OK. This turns on all warnings, but turns off warnings about not making your class serializable, which is really fine for most cases.
Also click Report Used of Deprecated APIs to be informed about obsolete library features you are using.
Turning runtime assertion checking on
Right click on the project icon in the Project panel at the left.
Select Properties at the bottom of the drop-down menu.
Click on the Run choice in the left panel.
In the VM Options text field at the right, enter "-ea" (without the quotes). "ea" stands for enable assertions. VM stands for Virtual Machine in this case, not virtual memory.
Packaging resources (eg images, data, ...) with your jar file
Q: How can you include resources (like images, sound, data, etc) so that your Java program doesn't need to use file paths, and so that you can package these resources in the jar file? And how do you access these resources from your program?
A: The Java class loader that loaded your program knows where the resources are. You can ask it to get other resources from the jar file. But first you have to build the jar file to include these resources. NetBeans does this automatically if you put a directory of your resources in the right place.
Adding your resources to the project.
Locate the src folder in your NetBeans project folder. This will have subfolder(s) in it that correspond to the package(s) in your program. The final package folder will have the source code (.java files) for your program.
Create a subfolder in the folder containing the .java files. Name this folder something like "resources" or "images" or whatever might be appropriate for your data.
Copy your data files into this folder. Keep a backup copy of the data -- if you put it in the wrong folder, NetBeans may delete it.
Build (or Clean and Build) your project. This will compile the code and copy the resources folder into the build/classes/your-packages folder of the NetBeans project. It will also be added to the jar file.
Reading resources from your Java program.
The following example shows how to read one line from the text file initial-board.sdk which is located in the resources directory. The main program is called Sudoku.
//... Reads one line of text from a file saved in jar file.
final String RESOURCE_LOCATION = "resources/initial-board.sdk";
InputStream instream = Sudoku.class.getResourceAsStream(RESOURCE_LOCATION);
Scanner in = new Scanner(instream);
String initial_board = in.nextLine();
in.close();
There are a few things to note about this code.
There are a couple of ways to get a Class object - either from the .class field if you specify the name of a class (as above), or by calling getClass() on an object.
A Class object has two methods for getting resources:
getResourceAsStream(name) which returns an InputStream that can be used with Scanner or any other way of reading. This is used in the example above.
getResource(name) which returns a URL. The URL is more general and can be used to get the InputStream. It can also be used directly in the IconImage(url) constructor, or various other ways to get images (getImage()) or sound (getAudioClip()).
Other features you might want to use
Importing packages into a project
To use other packages (eg, com.fredswartz.ezgui), NetBeans has to know where to find them. Here is the process.
Right click on the project in the Projects panel at the left.
Select Properties at the bottom of the popup menu.
Click on Libraries in the left panel.
On the right, click Add JAR/Folder....
Move around the file system to select the appropriate jar file, click Open, then OK.
Abbreviations
NetBeans Quick Tip #6 - Abbreviations in Editor
Misc
PMD - pmd.sourceforge.net - A wonderful plugin that analyzes your source program for bad programming practices. Highly recommended.
www.nbextras.org - Open source plugins for NetBeans.
Clearing Find results.
Q: When you search for text, all occurences will be highlighted, which is good, but how to do you get rid of the highlighting?
A: Use Find again, but with no text. Or use Alt-Shift-H.
Copyleft 2007 Fred SwartzMIT License
IDEs
Summary: There are many good, free, IDEs (Integrated Development Environments) that provide substantial advantages over the use of simple text editors for Java program development. The IDEs listed here are available for Windows altho many of them are also available for the Mac.
IDEs are the most efficient way to develop programs, but they are often not taught in text books. This gives the false impression that they aren't important. Why aren't they covered in most textbooks? There are too many choices, it takes some time to teach / learn to use one effectively, and instructors feel time spent learning one particular IDE is not central to learning programming. Another argument is that IDEs hide details that may be important to learn about. These are reasonable arguments, but the student often ends up without knowing how to use a good IDE.
Full-strength IDEs
A full-strength IDE provides extensive programming support for editing, project management, debugging, building GUI interfaces, etc. Surprisingly, most of these are now free.
Productivity. These offer far more than is required by the beginning Java programmer, and their extra complexity is a barrier to learning Java in the beginning. After your first programming course, however, they give a big boost to productivity.
Built on JDK. All of these require installing the Sun JDK ( free at java.sun.com) first.
NetBeans - www.netbeans.org
This free, open-source, IDE is a good choice. It does continuous compilation, which shows jagged red lines under erroneous statements as they are being entered. There is also brace matching, refactoring, reformatting, debugging, GUI form editing, and much more.
This is the IDE I use for my own work.
Eclipse - www.eclipse.org
The free Eclipse IDE is perhaps the most popular. "The Eclipse IDE can be a little daunting to the uninitiated" is a quote from John Montgomery who has some tutorials. See Using Eclipse for Java Programming. Highly recommended by many.
IntelliJ IDEA - www.jetbrains.com/idea
This is excellent, but expensive. It gets more favorable reviews than any other IDE, but certainly isn't worth the price for course work, not even at the $99 academic price.
The following full-strength IDEs are not the most popular, but may have features that make them best for your situation.
JDeveloper - www.oracle.com/technology/products/jdev/index.html
Oracle's JDeveloper is now available for free. It looked OK in my one quick test, and seemed very fast.
Borland CodeGear JBuilder - www.codegear.com
Borland produced some very good IDEs, but they've had a tough time competing with the free IDEs. They've spun off a separate company, CodeGear, for development tools, including JBuilder. CodeGear offers a free version of Turbo JBuilder. Their IDEs in the past have been very good (I've purchased several), and I hope this is still the case, but I haven't tried any of their recent products.
Half-strength IDEs
These are simpler to use for small projects, and typically don't have nearly as many features, eg, no graphical user interface editor.
DrJava - drjava.org
A simple, free development system. I especially like it's ability to indent the source program (select the code then hit tab). It's a single .jar file which can be run from a USB drive. This could be an important factor if you develop your programs and different machines (eg, in the student lab and at home). This is my first choice.
tIDE - snowmail.sn.funpic.de/tide/
This looks very nice, especially because it has the quality checking tools built in. Can be loaded with WebStart, or run from USB drive. However, running it is unobvious, and it isn't easy enough to recommend, yet.
JCreator - www.jcreator.com
Free LE and for pay Pro versions. I use it sometimes, and it's OK. Curiously, it's written in C++.
jGRASP - www.jgrasp.org
Many like it. The Control Structure Diagramming couild be nice, but it reformated my program in undesirable ways. Easy to install, but it rudely wants to be the default program for all kinds of files. Free. I'm not entirely enthusiastic about it, but it's popular.
BlueJ - www.bluej.org
BlueJ creates a nice development environment, which allows easy evaluation of isolated statements, inspection of classes, debugging, etc. My reaction to early versions was negative because it couldn't create "real" programs. That has changed, and hewer versions addressed most of my earlier reservations. My positive view is the result of only 30 minutes of testing, but it looked good. There is a textbook which is customized to use with it, which was very nice in many ways, but taught no GUI programming. It can also be used as a NetBeans or Eclipse plugin!
SyncJEdit - www.syncedit.com/software/jedit/
I haven't tried this, but it looks like it has some interesting features.
zBlueStudio - www.zbluesoftware.com/zbluestudio/index.cfm
Another interesting IDE that I haven't tried.
Others
There used to be many more, but keeping up with current Java releases caused many to drop out. But new good ones appear from time to time.
Editors that run javac
Some programming editors will compile Java by linking to Sun's JDK.
TextPad - www.textpad.com
[These comments apply to the 4.7.3 version which was available for the last 3 years, and can still be downloaded. My first trials of the new 5.0 version didn't go well.]
Good, but doesn't indent program. Has brace matching feature. You can buy it, but can also continue to use trial version with occasional nags. If the Java SDK is installed first, TextPad allows compilation of Java programs from the editor. Minimal, but a common choice because of the simplicity.
How should you choose an IDE?
My favorite happens to be NetBeans, but this doesn't mean it's best for you. Some factors that might be important are:
If you're already using a full-featured IDE, stick with it.
It's good to have a support infrastructure - use whatever your friends or coworkers are using.
Special features might be important to you. Each of the major IDEs has features that the others don't.
If you have no compelling reasons for another choice, I recommend NetBeans. It has nice features that make coding easier, and once you become familiar with its Graphical User Interface (GUI) editor, you can create GUI interfaces very quickly.
Copyleft 2007 Fred Swartz MIT License
Programming
Programming
Here are some tips on making programming student problems easier.
Start from an existing, running, program. If you can find a program that's vaguely similar in it's interface, even it it solves a completely different problem, it's much easier to start with that and modify it. These notes have a number of example programs that make good starting points.
The problem you might have is the number of basic structures that you haven't mastered yet (eg, the different between applets and applications, different object structures, ...). These will be big barriers when you are beginning.
Make incremental changes. This is one of the basic elements of Extreme Programming (a much hyped, but good Software Development Lifecycle methodology). Make a small change (a few lines), then compile and run the program.
Learn your editor or IDE well. You will spend most of your time with the editor -- learn it really well and you will be rewarded. Eg, to get it to indent your code, match braces, ... .
Indent your code. Good indentation is amazingly useful.
Copyleft 2003 Fred Swartz MIT License, Last update: 2002-12-15
Java Development Kit (JDK)
Java Notes
Java Development Kit (JDK)
The most popular Java compiler is Sun's Software Development Kit (JDK) (aka Software Development Kit (SDK)). It's free, and does a good job. The only problem is that the compiler is only a compiler - there is no editor and no graphical user interface. It is typically used in one of the following ways.
From the DOS command window with the javac command.
With a program editor (eg, TextPad) which has an interface to the compiler.
With an IDE (Integrated Development Environment). See IDEs.
Free Download
Download only the Java Standard Edition (SE) JDK from java.sun.com. There are three editions - get the "standard edition", not the Enterprise Edition (EE) or Micro Edition (ME).
Java SE - Java 2 Standard Edition - You want this.
Not Java ME - Java Micro Edition - This is for phones, PDAs, etc.
Not Java EE - Java Enterprise Edition - You don't want this unless you're doing Java client server programming, and even then, you probably don't need it.
Maybe the JRE - Java Runtime Environment - This is used to run Java programs, and altho it was installed automatically with the JDK in the past, it didn't install with JDK 6. You should probably install this. On Windows, look in C:\\Program Files\Java\ to see if there is a JRE for Java 6 (or later).
If you're a Macintosh user, it might already be installed on your system. Look at Java for Mac OS X.
Installation
Installing the JDK is easy (at least in Windows). Just follow the prompts.
CLASSPATH
If you're using commands from the DOS command window, you will probably have to set CLASSPATH. See CLASSPATH.
JVM runtime -enableassertions (-ea) option
Command Effect
java MyProg Assert statements are removed by class loader.
java -enableassertions MyProg Assert statements are executed.
java -ea MyProg Short form for allowing assertions.
It's also possible to enable/disable assertion checking at runtime for individual classes or for library routines, but that level of control is not useful for most purposes.
Copyleft 2007 Fred Swartz MIT License
Tools
You need software tools to build Java programs. Unless otherwise indicated, all tools mentioned here are freely available, and most of them are open-source.
Sun's Java Software Development Kit
Sun's SDK (formerly known as the JDK - Java Development Kit) is the most commonly used tool to compile and run Java programs. It's a good compiler, but it has a command line user interface. It is typically used with a text editor.
GCJ Compiler
This is an open-source Java compiler. It shouldn't be your first choice. Perhaps the greatest strength of Java is the extensive library. Unfortunately GCJ doesn't support all library classes, most notably the GUI classes. An interesting aspect of GCJ is that it compiles directly to machine code instead of to Java Byte Code. The only reason I include it here is to take part in the online Valladolid Programming Contest you will need to use this compiler.
Text Editors
Text editors are used to write the source programs. Some of them link directly to a compiler, but often you will run the compiler as a separate step to compile the source program.
IDEs - Integrated Development Environments
IDEs contain all the tools that you need to edit, compile, and test , manage projects, etc. An IDE is the high-productivity tool professionals use to produce programs.
Full-strength IDEs (eg NetBeans or Eclipse) are not usually the best choice for beginning students because learning the tool in addition to learning programming can be too much, and perhaps they hide some of the underlying issues of programming a little too much.
For the intermediate or advanced students it's extremely useful to use an IDE, especially because it can increase your programming productivity, and because it's a useful skill.
UML tools
The Wikipedia UML Tools page is the first place to look. I have a few notes below, but there are lots more UML tools.
UMLet - (www.umlet.com) = "UMLet is an open-source Java tool for UML diagrams with a light-weight, pop-up-free user interface: draw diagram sketches fast, export diagrams to eps, pdf, jpg, svg, and clipboard, share diagrams using Eclipse, and create custom graphical elements."
Violet UML tool - (www.horstmann.com/violet)
This is a nice simple program for doing class, sequence, and state diagrams. It's written by Cay Horstmann, one of the authors of the wonderful Core Java books, and author of Object-Oriented Design and Patterns. It's free and open source, and can be run from WebStart as well as downloaded.
This is a nice, simple program with the advantage that you can mess with the source if you really feel like it (only 300KB including the source!).
Visual Paradigm for UML - Community Edition (www.visual-paradigm.com)
The free Community Edition works pretty well. The only restriction that is bothersome is that the company name is printed over diagrams. It required registering, but I've never been hassled by email. After you download it, you will get email with a link to the key file, which you should put into the same directory as the installation file. When asked with you want to install, choose "Paradigm for UML", then "Community Edition".
ArgoUML (argouml.tigris.org/ - Can be run with WebStart! I find it a little awkward to use, but surely it must be easier after a little practice.
Poseidon for UML - Community Edition (gentleware.com/downloadcenter.0.html)
I haven't tried this newer version yet.
MagicDraw - Community Edition (http://www.magicdraw.com)
I've heard good things about it, but I found the interface very frustrating to use.
NetBeans UML Tool -- Will be in NetBeans 5.5.
Dia is a general diagramming tool, similar to Visio. Supports UML. Windows version: dia-installer.sourceforge.net/.
Jude Community Edition 3.0.3 (jude.change-vision.com/jude-web/index.html) Many operations caused an Exception. Unable to parse Java 5 code. Not ready for use yet.
Other development tools
As your programs move beyond simple student programs, additional tools will be needed. Some of there are included in IDEs, but many are used independently.
Code beautifiers are great for indenting your code correctly. I rarely use them because I'm compulsive about indentation from the beginning, but there are a lot of links at mindprod.com/jgloss/beautifier.html. I've used Arachnophilia, NetBeans, and Artistic Style at various times in the past, but am not sure which is currently the best choice.
Style and Correctness Checkers can be used to detect or eliminate problems in your programs.
Ant is the Java replacement for the traditional Unix make tool for automating the compilation process. At the simplest, one plain ant command recompiles all source files which have been changed since the last compilation. It can, however, automate all aspects of development.
javadoc creates documentation automatically from special comments in your Java programs. It comes with Sun's JDK.
JUnit (www.junit.org) is the single most important tool for running unit test cases. Other tools can be used for testing GUI interfaces.
Installers.
There are a number of options if you want to go beyond simply distributing a .jar file of your program. There are a number of installer generators that you can use. Naturally, there are some good commercial installers, but there are also a number of free installers.
With some installers you can bundle an appropriate version of the JRE (Java Runtime Environment), which will be installed if it's not already on the host machine.
See Open Source Installers Generators in Java (java-source.net/open-source/installer-generators)
PMD (pmd.sourceforge.net) - Checks code for errors. Can run standalone or as a plugin for NetBeans, Eclipse, .... I regularly use PMD. The following article inludes a lot of PMD information, not just advice on using it with Eclipse: Improving Code Quality with PMD and Eclipse.
My Favorite Java Books
My standard book questions
When I think about textbooks and other books, I usually ask myself some questions:
Would this be a book I would buy if I wanted to learn the subject on my own?
Can the book later be used as a reference?
What do the Amazon reviews say?
If it was used in a course, should I keep or throw it out?
Language
The following books aren't going to give the absolute beginner a simple enough start, but if you already know about variables, ifs and loops, or know another programming language and want to learn Java, these are good books.
Head First Java by Kathy Sierra and Bert Bates, O'Reilly
At first glance it looks like a book for dummies, but it isn't. It's funny and entertaining, has lots of diagrams, and is also a great Java book written by two smart Java people who helped to develop the Java Certification exam. This is a book which gives you the big picture. Amazon price $30 (a bargain)
Core Java volumes I+II by Cay Horstmann and Gary Cornell,
If you already know some Java or are a C++ programming converting to Java, this is a really good book, or set of books. Currently at the seventh edition, I've purchased at least three of the earlier editions. Amazon price: $31 for the first volume, $62 for both. Get the first and, if you like it, get the second. Useful both to learn from and later as a reference.
Java: How to Program by Deitel and Deitel, Pearson Prentice-Hall
I have mixed feelings about this, but it's better than most. It's crammed with tons of information about Java, and it is a good resource in many ways. However, the authors sometimes get obsessed with small features and completely lose sight of the big picture. This is also starting to show its age and hasn't been updated as well as it should have been. Amazon price $88 (seems a bit expensive).
Design
Object-Oriented Design & Patterns by Cay Horstmann
This is a good, brief, book that covers everything from Java's OO language features, with a healthy bit of OO design, and many of the common design patterns. This second edition incorporates Java 5 features.
It passes all the tests. Even the one bad review in Amazon was mostly just disagreement about terminology (eg, the first chapter should have been called a brief review, not a crash course; javadoc should have been a described as a implementation tool more than a design tool). I'm not sure about the negative multi-threading comment.
Favorite Java books from JavaLobby poll
I've extracted many of the books from this list, and kept those that I like too, or added warnings to others that might be a problem. I've also put them in categories.
Java language/usage
Core Java 2 (Volume I - Fundamentals, Volume II - Advanced Features) 7th Edition By Cay Horstmann and Gary Cornell.
Great books to learn Java from.
Java : How to Program (6th Edition) by Deitel and Deitel
Quite good if you don't get lost in the details.
Head First Java (2nd Edition) By Kathy Sierra and Bert Bates.
Probably the best book for understanding basic concepts, but it doesn't cover as much of the language as others. Excellent.
Java Examples In A Nutshell (3rd Edition) by David Flanagan.
I wish it was updated to Java 5.
Java Cookbook (2nd Edition) By Ian Darwin.
Lots of good examples with discussions.
Java In A Nutshell (5th Edition) by David Flanagan.
I definitely like the first part of this book. The bulk of the remainder is something you can get from the javadoc, but still nice to have on paper.
GUI Bloopers: Don'ts and Do's for Software Developers and Web Designers by Jeff Johnson.
If you're going to build a Graphical User Interface, you should have some idea about how to make it look "right". There is no Java code here, but a lot of good examples of good and bad GUI design.
Programmers Guide to Java Certification by Khalid Mughal and Rolf Rasmussen.
The earlier version I have was good. Much better than some of the certification books.
Thinking in Java (4th Edition) by Bruce Eckel.
If you're interested in delving into the details of everthing, this is a book for you, but probably not the right book to start your Java learning with tho. The first seven chapters are available for free online now, and maybe the rest will follow.
Java Puzzlers By Joshua Bloch; Neal Gafter. I've just glanced at it, and did learn a few things. Perhaps I should take another look.
Effective Java Programming Language Guide By Joshua Bloch. Good, but I think it's overrated. I read a lot of it in a bookstore, but didn't think it was worth buying.
General Programming Wisdom
Code Complete (2nd Edition) By Steve McConnell
The Pragmatic Programmer: From Journeyman to Master By Andrew Hunt; David Thomas
Design
Design Patterns: Elements of Reusable Object-Oriented Software By Erich Gamma; Richard Helm; Ralph Johnson; John Vlissides
Refactoring: Improving the Design of Existing Code By Martin Fowler; Kent Beck; John Brant; William Opdyke; Don Roberts
Head First Design Patterns By Elisabeth Freeman; Eric Freeman; Bert Bates; Kathy Sierra
Applying UML and Patterns By Craig Larman
Concurrent Programming in Java: Design Principles and Pattern (2nd Edition) By Doug Lea
Domain-Driven Design: Tackling Complexity in the Heart of Software By Eric Evans
Java Design Patterns: A Tutorial By James W. Cooper
Facts and Fallacies of Software Engineering By Robert L. Glass
Software Engineering
Agile Software Development: Principles, Patterns, and Practices By Robert C. Martin. [Also similar books by Alistair Cockburn, Craig Larman, and Jim Highsmith, as well as on specific methodologies such as Extreme Programming and SCRUM.]
The Mythical Man-Month: Essays on Software Engineering, 20th Anniversary Edition by Frederick P. Brooks
Peopleware by Tom Demarco; Timothy Lister
Rapid Development by Steve McConnell
Links to online resources
Java Quick Reference
More at www.javalobby.org/articles/5books/full.jsp
Copyleft 2007 Fred Swartz MIT License
Garbage Collection
Garbage collection is the process of automatically finding memory blacks that are no longer being used ("garbage"), and making them available again. In contrast to manual deallocation that is used by many languages, eg C and C++, Java automates this error-prone process.
Manual deallocation
The area of memory where blocks are dynamically allocated is called the heap. In many programming languages (eg, C++) the programmer generally has to keep track of allocations and deallocations. Manually managing the allocation and deallocation (freeing) of memory is not only difficult to code, it is also the source of a large number of extremely difficult to find bugs. It is estimated that a very large percentage, I've seen estimates as high as 50%, of the bugs in delivered, shrink-wrapped, software are related to memory allocation/deallocation errors. There are two common bugs.
Dangling references. When memory is deallocated, but not all pointers to it are removed, the pointers are called dangling references -- they point to memory that is no longer valid and which will be reallocated when there is a new memory request, but the pointers will be used as tho they still pointed to the original memory.
Memory leaks. When there is no longer a way to reach an allocated memory block, but it was never deallocated, this memory will sit there. If this error of not deleting the block occurs many times, eg, in a loop, the program may actually crash from running out of memory.
Automatic garbage collection
When there are no longer any references to a memory block (a Java object), that memory can be reclaimed (collected). Automatic garbage collection is the process of figuring out how to detect when an object in no longer referenced, and how to make that unused memory available for future allocations.
There are a number of garbage collection techniques (eg, reference counts and mark and sweep); Different versions of Java use different algorithms, but recent versions use generational garbage collection, which often proves to be quite efficient.
The reference below describes some of these techniques and provides further references.
What you can do to improve garbage collection performance
Garbage consists of objects that can't be referenced by anyone -- there are no static, instance, or local variables that references them either directly or indirectly.
Assign null to variables that you are no longer using. This will, if there are no other references, allow this memory to be recycled (garbage collected). Because local variables are deallocated when a method returns, they are less of a problem. Variables with the longest lifetime are static variables, you should be careful to assign null to any that are no longer used, especially if they reference large data structures.
Garbage Collection
Garbage collection is the process of automatically finding memory blacks that are no longer being used ("garbage"), and making them available again. In contrast to manual deallocation that is used by many languages, eg C and C++, Java automates this error-prone process.
Manual deallocation
The area of memory where blocks are dynamically allocated is called the heap. In many programming languages (eg, C++) the programmer generally has to keep track of allocations and deallocations. Manually managing the allocation and deallocation (freeing) of memory is not only difficult to code, it is also the source of a large number of extremely difficult to find bugs. It is estimated that a very large percentage, I've seen estimates as high as 50%, of the bugs in delivered, shrink-wrapped, software are related to memory allocation/deallocation errors. There are two common bugs.
Dangling references. When memory is deallocated, but not all pointers to it are removed, the pointers are called dangling references -- they point to memory that is no longer valid and which will be reallocated when there is a new memory request, but the pointers will be used as tho they still pointed to the original memory.
Memory leaks. When there is no longer a way to reach an allocated memory block, but it was never deallocated, this memory will sit there. If this error of not deleting the block occurs many times, eg, in a loop, the program may actually crash from running out of memory.
Automatic garbage collection
When there are no longer any references to a memory block (a Java object), that memory can be reclaimed (collected). Automatic garbage collection is the process of figuring out how to detect when an object in no longer referenced, and how to make that unused memory available for future allocations.
There are a number of garbage collection techniques (eg, reference counts and mark and sweep); Different versions of Java use different algorithms, but recent versions use generational garbage collection, which often proves to be quite efficient.
The reference below describes some of these techniques and provides further references.
What you can do to improve garbage collection performance
Garbage consists of objects that can't be referenced by anyone -- there are no static, instance, or local variables that references them either directly or indirectly.
Assign null to variables that you are no longer using. This will, if there are no other references, allow this memory to be recycled (garbage collected). Because local variables are deallocated when a method returns, they are less of a problem. Variables with the longest lifetime are static variables, you should be careful to assign null to any that are no longer used, especially if they reference large data structures.
Garbage Collection
Garbage collection is the process of automatically finding memory blacks that are no longer being used ("garbage"), and making them available again. In contrast to manual deallocation that is used by many languages, eg C and C++, Java automates this error-prone process.
Manual deallocation
The area of memory where blocks are dynamically allocated is called the heap. In many programming languages (eg, C++) the programmer generally has to keep track of allocations and deallocations. Manually managing the allocation and deallocation (freeing) of memory is not only difficult to code, it is also the source of a large number of extremely difficult to find bugs. It is estimated that a very large percentage, I've seen estimates as high as 50%, of the bugs in delivered, shrink-wrapped, software are related to memory allocation/deallocation errors. There are two common bugs.
Dangling references. When memory is deallocated, but not all pointers to it are removed, the pointers are called dangling references -- they point to memory that is no longer valid and which will be reallocated when there is a new memory request, but the pointers will be used as tho they still pointed to the original memory.
Memory leaks. When there is no longer a way to reach an allocated memory block, but it was never deallocated, this memory will sit there. If this error of not deleting the block occurs many times, eg, in a loop, the program may actually crash from running out of memory.
Automatic garbage collection
When there are no longer any references to a memory block (a Java object), that memory can be reclaimed (collected). Automatic garbage collection is the process of figuring out how to detect when an object in no longer referenced, and how to make that unused memory available for future allocations.
There are a number of garbage collection techniques (eg, reference counts and mark and sweep); Different versions of Java use different algorithms, but recent versions use generational garbage collection, which often proves to be quite efficient.
The reference below describes some of these techniques and provides further references.
What you can do to improve garbage collection performance
Garbage consists of objects that can't be referenced by anyone -- there are no static, instance, or local variables that references them either directly or indirectly.
Assign null to variables that you are no longer using. This will, if there are no other references, allow this memory to be recycled (garbage collected). Because local variables are deallocated when a method returns, they are less of a problem. Variables with the longest lifetime are static variables, you should be careful to assign null to any that are no longer used, especially if they reference large data structures.
Garbage Collection
Garbage collection is the process of automatically finding memory blacks that are no longer being used ("garbage"), and making them available again. In contrast to manual deallocation that is used by many languages, eg C and C++, Java automates this error-prone process.
Manual deallocation
The area of memory where blocks are dynamically allocated is called the heap. In many programming languages (eg, C++) the programmer generally has to keep track of allocations and deallocations. Manually managing the allocation and deallocation (freeing) of memory is not only difficult to code, it is also the source of a large number of extremely difficult to find bugs. It is estimated that a very large percentage, I've seen estimates as high as 50%, of the bugs in delivered, shrink-wrapped, software are related to memory allocation/deallocation errors. There are two common bugs.
Dangling references. When memory is deallocated, but not all pointers to it are removed, the pointers are called dangling references -- they point to memory that is no longer valid and which will be reallocated when there is a new memory request, but the pointers will be used as tho they still pointed to the original memory.
Memory leaks. When there is no longer a way to reach an allocated memory block, but it was never deallocated, this memory will sit there. If this error of not deleting the block occurs many times, eg, in a loop, the program may actually crash from running out of memory.
Automatic garbage collection
When there are no longer any references to a memory block (a Java object), that memory can be reclaimed (collected). Automatic garbage collection is the process of figuring out how to detect when an object in no longer referenced, and how to make that unused memory available for future allocations.
There are a number of garbage collection techniques (eg, reference counts and mark and sweep); Different versions of Java use different algorithms, but recent versions use generational garbage collection, which often proves to be quite efficient.
The reference below describes some of these techniques and provides further references.
What you can do to improve garbage collection performance
Garbage consists of objects that can't be referenced by anyone -- there are no static, instance, or local variables that references them either directly or indirectly.
Assign null to variables that you are no longer using. This will, if there are no other references, allow this memory to be recycled (garbage collected). Because local variables are deallocated when a method returns, they are less of a problem. Variables with the longest lifetime are static variables, you should be careful to assign null to any that are no longer used, especially if they reference large data structures.
NoSuchMethodError main
Do you get the following error message?
Exception in thread "main" java.lang.NoSuchMethodError: main
The following are common causes.
File/class name mismatch. Check the file and class names -- they much match exactly, even with upper and lower case. Windows doesn't care about file names that differ only in case, but Java does. If you have trouble renaming a file to fix the case, first rename it to something different, then rename to the correct case.
Mistyping the main header. Something is wrong with your declaration of main. It must be
public static void main(String[] args)
Variations in the parameter declaration are allowed, but the above is what everyone expects to see.
CLASSPATH is a less likely cause. See CLASSPATH.
Using other packages
Distributed as jar files. As extensive as Java's library is, there are sometimes other packages that you want to use. These are almost universally distributed as .jar files. You can access them if you import them.
Where to put predefined .jar files so that the compiler and JRE can find them
A .jar file is basically a .zip file plus a little extra information, the manifest. The jar file may contain one or more packages. Both the compiler and the JRE (Java Runtime Environment) must know where to look for these other jars that you've imported. There are several alternatives.
Modify the CLASSPATH variable to include the jar file
See CLASSPATH.
Tell the compiler or IDE where it is
The compiler (javac command) and JRE (java command) have parameters that specify where to find additional jar files.
Most IDEs have a way to specify where external jar files are located. See NetBeans.
Put the jar file in the JRE lib/ext directory
[Avoid - fragile] This directory is automatically searched by the compiler and runtime systems for needed packages. In my Windows installation of Java, the JRE is installed twice, once with the JDK and once so I put it in both. I don't know that both are actually used, but I didn't want to take any chances.
C:\Program Files\Java\jre1.6.0\lib\ext\
C:\Program Files\Java\jdk1.6.0\jre\lib\ext\
Packages - Defining
Packages - Defining
Package = directory. Multiple classes of larger programs are usually grouped together into a package. Packages correspond to directories in the file system, and may be nested just as directories are nested.
Reasons to use packages
Grouping related classes.
In large programs prevents name conflicts.
Allows effective use of default "package" visibility.
Creates a unique class name for distribution, Preferences, ...
Grouping related classes. If you are writing a normal one-programmer application, it will typically be in one package. The purpose of a package is to group all related classes together. If you are working on a program that is divided into separate sections that are worked on by others, each section might be in its own package. This prevents class name conflicts and reduces coupling by allowing package scope to be used effectively.
Library in package. If you're writing a library to use in various programming projects or by others, put it in its own package. Programs that use this library will be developed in their own packages. With its thousands of library classes, Java has grouped related library classes into packages, but usually you won't define more than one package.
Summary of how many packages you usually define
Normal programs = one package.
Library = one package.
Program + library = two packages.
Reasons for using packages
Limit the scope of class names.
To make package access more usable.
Package declarations
Each file may have a package declaration which precedes all non-comment code. The package name must be the same as the enclosing directory.
Default package. If a package declaration is omitted, all classes in that directory are said to belong to the "default" package.
Here are two files in the packagetest directory.
package packagetest;
class ClassA {
public static void main(String[] args) {
ClassB.greet();
}
}
and
package packagetest; // Same as in previous file.
class ClassB {
static void greet() {
System.out.println("Hi");
}
}
Note that these source files must be named ClassA.java and ClassB.java (case matters) and they must be in a directory named packagetest.
Compiling and running packages from a command line
To compile the above example, you must be outside the packagetest directory. To compile the classes:
javac packagetest/ClassB.java
javac packagetest/ClassA.java
To run the main program in ClassA.
java packagetest.ClassA
or
java packagetest/ClassA
In windows the "/" can be replaced by the "\" in the javac command, but not in the java command. Generally use a forward slash ("/") because it is used more commonly than the backslash in other places as well.
Copyleft 2006 Fred Swartz MIT License
Packages - Importing
Packages = directories. Multiple classes of larger programs are grouped together into a package. Packages correspond to directories in the file system, and may be nested just as directories are nested. Small, single-class, programs typically do not use packages, but a
Importing all classes from a package using *
Java libraries are organized in packages (directories). The most common way to get access to them is to use the import statement. For example,
import java.util.*;
. . .
ArrayList
gives your program access to the all (that's what the "*" means) classes in the package java.util. The source files for these classes are in a directory named util, which is in a directory named java.
Importing each class explicitly
If you need only one class from a package, eg ArrayList, you can write
import java.util.ArrayList;
. . .
ArrayList
You might think that importing all classes from a package is inefficient, but there is no noticeable difference in my experience. Consequently most programs use the ".*" style of import.
Using package qualifiers instead of imports
The import statement is not required. Class references can be made but explicit qualification with the "." operator. For example,
java.util.ArrayList
The fully qualified style is used in some textbooks, but is generally not used when programming, where the import style is almost universal.
However, there is one situation where qualification is necessary - when two classes have the same name, but are in different packages. For example, there is both java.util.Timer and java.swing.Timer. Because it's common to import all classes in both java.util and javax.swing, the name Timer is ambiguous and can't be used without qualification.
import java.util.*; // The java.util package contains a Timer class.
import javax.swing.*; // The javax.swing package also contains a Timer class.
. . .
Timer t; // AMBIGUOUS - compilation error
java.util.Timer t; // OK, you've told the compiler which one you want.
Packages within packages require additional imports
The import statement gives access to classes in a package, but not to packages in that package. For example,
import java.util.*;
does not give access to the classes of the package java.util.regex. To access classes in java.util and java.util.regex, import both.
import java.util.*;
import java.util.regex.*;
Java's import is not the same as C++'s #include
C++'s #include is commonly used to for library headers, but the mechanism which is used is fundamentally different. #include inserts the entire source file that is referenced into your C++ program. In contrast, the Java import statement only looks up the the identifiers and their declarations from the compiled class file (not the source files).
Another difference is that Java imports are non-transitive. If class A imports packagex and packagex imports packagey, class A does NOT get access to packagey. In C++, the imports are transitive, which can lead to some unexpected effects.
A minor difference is that Java's import is a statement and requires a semicolon, unlike C++.
Packages
Multiple classes of larger programs are usually grouped together into packages. See Packages - Defining for how and why to use packages
Each class should be defined in its own .java file
Put each of your classes in its own file. It's easy to do. Here are a couple of minor rules.
Make sure all classes (.java files) are in the same directory (folder).
You need separate import statements for each class.
You may have to compile a class that is referenced before the class that uses it. Whether you have to do this or not depends on which devopment system you're using.
When you run the program, you may have to have the class that contains main(. . .) be visible in your development system (depends on the development system.
There are some exceptions (inner classes), but this is the general rule that applies to almost all Java programming.
It's possible to put more than one class in a file and have everything work. I did this for a long time for small programs, but have given it up because it doesn't scale up as you create larger programs and use more better development tools. A common development tool, Ant, works best when each class is in its own source file.
Put all source files into a directory, one class per file
When you start a new project, create a new directory for the source files. The directory name should be lowercase letters, with no blanks or other punctuation. The directory is used as the package.
Setting CLASSPATH on Windows XP
The CLASSPATH variable can be set on Windows XP with the following steps.
Click the Start button in the lower left of the screen.
Select Control Panel from the pop-up menu.
Choose System from the submenu.
Click the Advanced tab.
Click the Environment Variables button near the bottom and you will see two lists of variables.
Look in the System variables list for a variable named CLASSPATH. If you find it, click Edit. If you don't find it, click New and enter CLASSPATH in the Variable name field.
The Variable value field is a list of file paths of directories or jar files. The first thing in this list should be the current directory, which is represented in windows just as it is in Unix, as a single period. If there's more than one thing in this list, separate items with a semicolon. For example, my CLASSPATH variable starts with these three items (there are a couple more, but this should be enough to give you the idea). The only part you need is the first "dot".
.;C:\classpath\com.fredswartz.ezgui.jar;c:\classpath\TableLayout.jar;
I put extra libraries that I want to be searched in a directory named classpath, but you can choose any name.
Problems? Setting the CLASSPATH environment variable can make life much more convenient, but it can also create huge problems when testing different versions of programs that are on your classpath.
IDE. Now that I do most of my development using NetBeans, where I can specify which jar files to include, I no longer modify my CLASSPATH variable.
CLASSPATH tells Java where to search for programs
Where to look? The Java runtime system needs to know where to find programs that you want to run and libraries that are needed. It knows where the predefined Java packages are, but if you are using additional packages, you must tell specify where they are located.
CLASSPATH. Specifying where to search for additional libraries in Windows is easily done by seeting the environment variable CLASSPATH, which Java uses to see where it should find Java programs and libraries.
Automatic? Some IDEs tell the Java runtime system where to search, and double-clickable Jar (Java Archive) files don't have this problem
When do you need it? If you compile "by hand" (typing javac and java in a command window), or sometimes with TextPad or other editors.