您的位置:寻梦网首页编程乐园Java天地Core JavaJava Lecture Notes

INT4120 Frequently-asked questions

This is a summary of questions asked most frequently by students on this course last year. There are much more extensive Java FAQ's on the Web, and I suggest you refer to the Sunsite Java FAQ if you suspect your question is `frequently asked' and the answer is not in this list.

FAQs about the course in general

Q. Who prepared this course, and what are his qualifications and experience? A. This course was prepared by Kevin Boone, senior lecturer in computer science at Middlesex University, who has been programming professionally since 1989, and teaching prgramming since 1995. His programming experience includes work on a variety of systems, from heart pacemakers to power stations, both in the private and public sectors. He has a first-class honours degree and a PhD.

Q. I'm halfway through the course and I don't understand anything! What can I do?
A. Don't panic. Go back to a point where you did understand, and work forward again. In extreme cases you might have to go back to week one. Make sure you understand every single word of the course notes; if not, seek assistance. Make sure you do all the exercises; if you can't seek assistance.

Q. Are some people `natural programmers' and some not?
A. I think so; some people seem to take to programming very quickly, and others find it difficult to get started. It is impossible to predict who the `natural programmers' will be; people think that mathematicians will make good programmers, but I have not usually found this to be the case. Some of the best programmers I know are artists and musicians.

Q. What can I do if I'm not a `natural programmer'?
A. Work harder. Sorry, but life's like that. Any reasonably intelligent, hardworking person can learn to be a competent programmer, but some people have to work much harder at it than others. I have often needed to use a lot of mathematics in my research work, but I am not a `natural mathematician' so I find it more difficult than other people. No-one said that life was fair. The worst thing a student can do is to say `I'll never be any good at this; it's too difficult'. As soon as you say this, it becomes true. Remember: the harder it is, the harder you work.

FAQs about using the compiler and running programs

Q. Why do I get a message like `Bad command or filename' or `Invalid program name' when I type `javac program.java'?
A. Java is not installed, or not completely installed.

Q. Why does the java compiler say `invalid argument: program' when I try to compile 'program.java'?
A. Probably you are typing
javac program
when you should be typing
javac program.java
You must include the file extension `.java', or the compiler becomes confused.

Q. Why does the java compiler say `can't read: program.java' when I try to compile 'program.java'?
A. The java compiler can't find the file called `program.java'. Is it in the current directory (type `dir /p' to list the files in the directory)? Has Notepad accidentally saved the file with `.txt' on the end? (see below)

Q. Why does Notepad save my file as `program.java.txt' when I told it `program.java'? How can I stop it?
A. Notepad is trying to be helpful. It thinks that all the files it creates should have `.txt' on the end, and it will do this all the time unless you're careful. If you put the filename in double-quotes (") it will leave it alone. So in the `Save file...' dialog box enter "program.java" and not program.java If you always start Notepad from the command line, this problem will not affect you.

Q. I have written a Java applet that works perfectly well with the applet viewer, but noting happens when I look at it with a Web browser. Why?
A. The level of Java support provided by Web browsers is variable. The version of Java taught by this course is the one that was current at the time the course was developed. Web browser manufacturers are not able to release a new product every time the Java standard changes slightly. I'm afraid there's no straightforward solution to this problem; make sure you are using the most modern Web browser you can find. If you want to write applets that other people can view with a Web browser, then you have to support older browser versions. This means writing Java code that uses out-of-date operations. Expect to get lots of `deprecation' warnings.

FAQs about compiler error messages

Q. Why do I get the error message `Class string not found in type declaration'
A. Almost certainly you typed `string' when you meant `String'. The string data type is defined as a class in Java, and by convention all class names start with an upper-case letter.

Q. Why do I get the error message `can't find class XXX' when I try to run a program by typing `java XXX'?
A. Several possibilities. (1). You might be using the wrong class name. Don't forget that Java is case-sensitive: the class `MainClass' is different from the class `mainclass' or `mainclass'. Don't forget that you run a class, not a file. So if your main class is called `MainClass', don't type `java MainClass.java'. The correct usage is `java MainClass'. (2) The class file is not in the current directory, or in a directory that Java searches for classes. Use `dir /p' to look at the files in the current directory.

Q. Why do I get the error message `main must be public and static'.
A. Because the Java specification say that `main' must be `public' and `static'! The correct specification of the `main' operation, whatever it does in any program, is

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

Q. Why do I get the error message `class or interface declaration expected'?
A. All java instructions must be in operations, and all operations must be in classes. If you have a program like this:

class MainClass
    {
    /* ... various operations ... */
    }
int x = 2;

then the line `int x = 2' will generate that error message. This is because the only appropriate Java statements at this point are to define a new class (or a new interface). In practice this error message often occurs because you've missed out a closing brace ('}').

Q. Why to I get the error message `...uses a deprecated API...'?
A. Your program is using something (usually an operation) that the Java developers want to remove from the language. If you are programming professionally you should take this message seriously. It means that with later versions of Java your program may no longer work. The problem is that as Java has developed, different methods have been incorporated that do the same thing. The Java developers are trying to standardize so that there is only one operation for each purpose. Thus some operations will be removed from the language eventually.

Q. Why do I get the error message `can't make static reference to non-static variable'?
A. Usually because you are trying to change the value of an attribute in an operation that is static. This is not allowed. For example, this piece of Java:

class MainClass
    {
    int x;
    public static void main(String args[])
        {
        x = 0;
        }
    }

will get that error message. `main' can't change the value of `x' because main is static. Remember that a static operation is part of the class, not part of its objects. Only an object can have attributes with values.

Q. Is there an easy way to find missing braces and semicolons? I've spend a week trying to find a single missing brace!
A. Be very, very self-disciplined about program layout and indentation. Then you'll find you don't miss out braces. Semicolons come with practice. Bear in mind that the Java compiler will usually report a missing semicolon some on a line below the real error. So you should start searching backwards from where the compiler says the error is.

Q. You keep nagging about indentation, but why is it so important?
A. Good indentation will keep you sane (see question above). It is much easier to follow how a program works if the indentation is exactly right. My only rules are that the open brace and its corresponding closing brace should be the same distance from the left margins, and every time I introduce a new opening brace I indent it by one tab stop. If you ever see two opening or two closing braces at the same distance from the margin, e.g.,

    }
    }

you'll know you've made a mistake.

FAQs about object orientation

Q. What's the difference between a `class' and an `object'?
A. You can have many objects of the same class. For example, there are many books in a library. All individual books are instances (members) of class `Book'. A Java program uses the statement `class ....' to define a class, and (usually) `new ....' to create a new object of that class.

Q. What is a constructor for?
A. The constructor is an operation that is called automatically when an object is created. The program does not have to instruct it to do this, it is automatic. A common use of a contructor is to initialize the values of a class's attributes.

Q. What is a `destructor' for?
A. The destructor is called whenever an object is deleted. Its usual purpose is to reverse whatever the constructor did, if it needs to be reversed. In practice, destructors are not that important in Java (compared to C++) for example, because Java has `garbage collection' (see `what is garbage collection?')

Q. What is `UML'?
`Unified modelling language'. This is the new international standard for showing classes and their relationships on a diagram. Of course an programmer is free to use any symbols he or she likes, if it makes the programming easier and of higher quality. But using the standard symbols makes it much easier to communicate with other designers and programmers. UML was originated at Rational Systems, and more information can be found on the company's Web site: www.rational.com.

Miscellaneous FAQs

Q. What is the difference between an `operation', a `member function' and a `method'?
A. Nothing. They mean the same thing. Specialists in object-oriented design tend to use the term `operation'. Programmers tend to use `method'. `Member function' is now rarely used. Remember that they all mean the same thing: something that a class does.

Q. What is the difference between an `attribute' and a `member variable'?
A. Nothing

Q. What is the difference between an `attribute' and a `variable'?
A. All attributes are variables, but not all variables are attributes. An attribute is available to all operations in a class, but a variable is only available to the section of program that defines it. For example, in this piece of Java:

class MainClass
    {
    int x;
    void anOperation()
        {
        int y;
        }
    }

`x' is an attribute; it is created when the object is created, and exists until the object is deleted. Any operation in the class can change its value. `y' is a (local) variable. It is created at the start of `anOperation' and is deleted at the end of `anOperation'. Consequently it is not available to other operations (unless its value is told to them explicitly).

Q. What is `garbage collection'?
A. The process of `cleaning up' unwanted objects. Every time a program creates a new object it uses some of the computer's memory. The computer only has a limited amount of memory. In some programming langauges (notably C++) the programmer must keep track of the objects created, and remove them when they are no longer necessary. Java does this automatically: this is garbage collection. Normally garbage collection is automatic, and the programmer does not have to initiate it. Garbage collection will always happen when the program finishes anyway.

Q. What sort of programs can be written in Java?
A. Any sort of program, except (1) programs that must run very fast (e.g., controlling a guided missile or (2) programs that interact with unusual computer hardware (e.g., there is at present no way to write a Java program that can interact with a Teletext decoder or a CD writer. In fact both these sorts of programs can be done in Java with a little bit of C or C++ to assist. Java has been used to write Web browsers, Word processors, expert systems and many other things.

Q. Why does my program consist only of an empty Window, when I am doing `new' and `add' to put other user interace elements into it?
A. I have noticed this behaviour when a class's constructor does not use `super' to call the constructor of its superclass. For example, if I define a new class of type `Frame', then the constructor of this new class must call the constructor of frame. Specifically, this is where the layout manager is initialized, and it is the layout manager that positions objects in a window. The correct place to call `super' is shown in this code fragment:

class MainWindow extends Frame
    {
    MainWindow() // Constructor for MainWindow class
        {
        super("Title of window goes here");
        /* ...other instructions... */
        }
    }