How-To Guides for Programming in Java

With a few exceptions, you already know everything you need to in order to write any program there is. However, even when you have a good handle on each part of programming, putting them all together can seem a little overwhelming.

What follows is a few possible outlines of how to put the pieces together. These how-tos are not the only way to program, of course, and you will develop your own style with experience, but they can be a good fall-back when you get stuck.

How to Design a Program and Write Classes
How to Write a Method
How to Write a Loop: Top-Down or Bottom-Up
Imports, Filenames, and other Java Trivia
Confusing Error Messages

How to Design a Program and Write Classes

This discusses how to take an idea and from it create a set of classes and identify their methods. If you just want to write a single class, skip to Step 4.

If you

  1. Make sure you understand what the program is supposed to do.
  2. Identify what types you need. There's no magic here; just look at each bit you identified in step one and ask what types are involved. Don't worry too much about if Java knows about those types, just write down every type you see. Don't worry about having too many, either; it's easier to remove duplicates later than to realize we need types we don't have listed.
  3. Go through the list of types from the previous step. For each type, ask yourself if there's a built-in type that will work. A type will work if it can represent every value you want and you can do to it everything you need. In particular, consider
    1. Is it a char, int, double, boolean, or String?
    2. Is it a simple collection of values, all of the same type? If so,
      • An array works if you want a fixed-length list, the size of which can be determined before creating the array.
      • An ArrayList works if you want a variable-length list you can add to and remove from.
      • A HashMap stores pairs of values, like a phone book pairing names with telephone numbers.
    3. Is it something related to GUIs, graphics, telecommunication, or talking with other parts of the computer? If so, it likely already exists somewhere in the Java API, which you can browse online.
    4. If it's none of the above, note it down as a type-providing class you'll need to write.
  4. Write a testing class. Give it a name like SomethingTester (in a file SomethingTester.java) where Something is replaced by your program's name. Give it only one method: an empty public static void main(String[] args)
  5. For each of the type-providing classes you need to write,
    1. Ask yourself what these objects are made up of, what distinguishes one object from another; these are the attributes of the object. For each attribute,
      1. Ask what type it has and write a private attribute declaration for it. If it is some strange type, you may have to write the class for that type first….
      2. Write basic getThing() and setThing(ThingType thingValue) methods. Typically these should be public and contain little more than return this.thing or this.thing = thingValue, possibly with some if statements to check for illegal values.
    2. Write the gang of 3: toString, clone, and equals.
    3. Write any constructors that make sense to you. Usually these will just call a few this.setThing methods.
    4. Over in your SomethingTester class's main method, add some code that makes a few new ClassYouJustWrote(…) objects, calls a few of the get/set methods, and prints out the results. Don't move on until those printouts look the way you expected them to look.
  6. For each of the classes you've written,
    1. Inside the .java file, make a comment // methods I need to write:.
    2. Add to that comment a list of every behavior you can think of that objects of that type might need.
  7. Now work you way through the lists of methods to write found in each .java file and write them. Always test each method you write before writing the next one! Do that by adding code to the main method in SomethingTester that calls the method you wrote and prints the results.

How to Write a Method

Suppose you're writing a method inside class Foo (Why Foo? It's a traditional nonsense-name… see Wikipedia or RFC 3092).

  1. Make sure you can do the work the method is supposed to do, at least for small inputs.
  2. Unless you are certain no other class should be able to call this method, make it public.
  3. What information do you you need to know to run the method?
  4. What are the results of running this method? Does it It is unlikely (though possible) that the method has multiple results. It is nearly unheard-of to have a method without any results.
    If your method returns a value, the type of that value is the return type of the method. Otherwise, it's a void method.
  5. Now just write down each step you would take if you were evaluating this method without a computer. A few hints and reminders:

How to Write a Loop

Before you write a loop, make sure you need to write a loop. Loops do (nearly) the same thing many times in a row. There are two basic approaches to writing loops, either one of which should work:

Loops top-down

The top-down approach starts with the idea that there is a loop and fills it in from there.

  1. Ask yourself, If I were doing this as a human, what would I be repeating? Write down the answer (in English) between curly braces ({ and }).
  2. Ask yourself, How many times do I repeat it? If the answer is
  3. Translate the loop body into Java—using the variables you created in the for if you used a for loop.

Loops bottom-up

The bottom-up approach delays adding the loop until it is clear what it will look like.

  1. Without adding a loop, write the code the loop will execute its first iteration.
  2. Write the code the loop will execute its second iteration.
  3. Write the code the loop will execute its third iteration.
  4. Ask yourself, what changed between those three repetitions?
  5. Ask yourself, Is that it, or will something else change eventually? If something else'll change, you'll probably want to put the loop you just wrote inside another loop. Write out the first three ways this loop will appear and repeat the process outlined above.

Imports, Filenames, et cetera

Filenames
A public class SomeRandomClassName should start with a capital letter and must be in a file named SomeRandomClassName.java, with the same capitalization as the class name.
Imports
Does Order Matter?
Yes and no.
Order matters for:
import must come before class; the order of the parameters of a method and the statements inside a method is also significant.
Order doesn't matter for:
The methods, constructors, and attributes inside of a single class. Typically you put the attributes at the beginning of a class, followed by the constructors, then the other methods; some prefer the attributes at the end instead. Either way, this is just tradition, not essential.

Confusing Error Messages

As a reminder, the number of compiler errors java gives is more or less meaningless. Fix the first one, then recompile.

Some error messages ar every long. The top is usually more important than the bottom of such messages. The first line tells you what went wrong; the rest tells you where it went wrong.

Cannot Find Symbol
Most commonly, this is a spelling error or typo (not necessarily on the reported line; you might have declared the variable with a typo). The second line of the error message tells you what symbol it cannot find. If it's a class, check Imports above. If it's a method, it may be that the object you are calling the method on doesn't have that method (such as calling add on a HashMap).
Class, Interface, or Enum Expected
Too many }s before that line.
Illegal Start of Expression
Too many or too few } or ) before that line.
Reached End of File While Parsing
Too few }, usually one missing on the last line of the file.
StackOverflow
This means either uncontrolled recursion (a method is invoking itself forever) or (rarely) an infinite loop that adds to some ArrayList or HashMap. The error message should include a long list of the same filename:linenumber, which is the line that caused the problem.
Unreported Exception
The error message will have the form FileName.java:lineNumber: unreported exception package.name.SomeNewException; must be caught or declared to be thrown. Go to that file and that line of the file, scroll up to the method that encloses that line, and add throws SomeNewException between the ) that ends the argument list and the { that begins the body of the method. If there already is a throws line there, add your exception to the list, as throws OldException, SomeNewException.

Prepared by Luther Tychonievich for CS1112 at UVa, 15–19 April 2010