Docstoc

Java Frequently Asked Questions and Answers

Document Sample
Java Frequently Asked Questions and Answers Powered By Docstoc
					 Java Frequently Asked Questions and Answers
                                     Tony Morris (c) 2003
                                     Build Number: 0070
                    Last Updated: Wed 09-06-2004 09:36:41.050 GMT+10:00


Back to questions


Question 1.
Where can I download the Sun Java Development Kit (SDK) / Java Runtime
Environment (JRE) ?

Answer.
At the time of this writing, the latest released version is 1.4.2.
This can be downloaded from http://java.sun.com/j2se/1.4.2/download.html




Question 2.
Do I want the Java Development Kit (SDK) or the Java Runtime Environment
(JRE) ?

Answer.
The SDK is the Software Development Kit. This will allow you to develop Java
software applications. The SDK includes the JRE as well as other tools that are
suitable for software development.
The JRE is the Java Runtime Environment. This will allow you to run Java
software applications, but does not include the tools to develop Java software
applications.
In conclusion, if you wish to develop and run Java applications, you want the
SDK.
If you wish to simply run Java applications, but not develop them, you want the
JRE.




Question 3.
How do I install the Java Development Kit ?

Answer.
This process is documented at http://java.sun.com/j2se/1.4.2/install.html




Question 4.
How do I set the PATH environment variable for the Java Development Kit ?
Answer.
The PATH environment variable is set that that it additionally contains the bin
directory of the installed SDK.
This process is outlined in the install documentation.

Question 5.
How do I set the CLASSPATH variable for the Java Development Kit ?




Answer.
Generally, you do not set the CLASSPATH environment variable for a standard
SDK or JRE installation. The CLASSPATH environment variable is set for other
reasons, usually the installation of third-party libraries. Some people (including
myself) argue that setting the CLASSPATH environment variable at all is bad
practice; it should be set dynamically at each build. This keeps the build machine
clean from potential "contamination" from libraries in the CLASSPATH. Setting
the CLASSPATH environment variable was required for installation of the SDK in
versions prior to 1.2. This "myth" has unfortunately carried over to later versions
of Java and confusion has resulted. A good rule of thumb is, "If you don't know
how to set the CLASSPATH (since you are relatively new to Java), don't set the
CLASSPATH at all". More information on the CLASSPATH environment variable
can be found at http://java.sun.com/j2se/1.4.2/docs/tooldocs/tools.html




Question 6.
What/Where is Java API Documentation ?

Answer.
API is an acronym for "Application Programming Interface." Therefore, the Java
API Documentation is a listing of all the possible uses of the current core Java
API. This includes packages, classes, methods, fields and more. Note that Java
API Documentation changes as the API changes for each incremental version of
the Java Development Kit. However, the API (generally) remains reverse
compatible and if API becomes outdated, it often becomes "deprecated." The
Java API Documentation is considered the "bible" of any Java programmer. An
example of the use of the API Documentation: the java.lang.String class has a
method called length() which returns an int value indicating the length of a
String. This can be confirmed by looking at the following part of the Java API
Documentation
http://java.sun.com/j2se/1.4.2/docs/api/java/lang/String.html#length(). The
Java API Documentation can be browsed online at
http://java.sun.com/j2se/1.4.2/docs/api/index.html or can be downloaded to be
viewed locally from the download page
http://java.sun.com/j2se/1.4.2/download.html
Question 7.
What does this mean "Exception in thread "main" java.lang.NullPointerException"
?

Answer.
Often called a NullPointerException or NPE, this is caused by dereferencing an
object reference to null. That is, you have an object reference and you are trying
to dereference it (usually by calling a method or accessing a field/member) while
the reference isn't referring to an object instance. The next line of the output will
give the location (file name and line number) of the violation. The following code
produces a NullPointerException:

        ...
        String s = null; // s is referring to null (no object instance)
        int len = s.length(); // dereferencing a reference to null -
will result in a java.lang.NullPointerException at this line
        ...

The following fixes the problem:

        ...
        String s = "blah"; // make sure that s is referring to an object
instance.
        int len = s.length(); // dereferencing a reference to a String
instance - ok.
        ...

For more information on null references:
http://java.sun.com/tutorial/java/data/objectcreation.html




Question 8.
What does this mean "Exception in Thread "main"
java.lang.NoClassDefFoundError <something> " ?


Answer.
This means that the Java Virtual Machine (JVM) cannot find the class that you
are referring to. The error is followed by the class name that the JVM was asked
to load. The directory that contains this class must be in your CLASSPATH
environment variable. If your CLASSPATH is not set to anything, then the class
must be located in the same directory from which the JVM is invoked (package
relative). The JVM is generally (but not always) invoked by executing the java
executable followed by the class name at a command line.

One common problem arises when executing a jar file (using the -jar switch),
which ignores all CLASSPATH settings, except for that specified in the Java
ARchive manifest file. This may be contrary to general intuition, but it makes
perfect sense when you think about it. This is outlined in The JAR File
Specification.

A common error is to append the .class file extension to the class name when
invoking the JVM; this will result in an error similar to the following:
Exception in thread "main" java.lang.NoClassDefFoundError: MyClass/class
Fix this problem by removing the .class file extension from your command.

Wrong
> java MyClass.class

Right
> java MyClass




Question 9.
What does this mean "non-static variable (or method) <something> cannot be
referenced from a static context" ?

Answer.
Well simply put, you are referencing something that is non-static from a static
context, which is not permitted. Elaborating on this concept in this document
may be misleading, so it is best to read the relevant tutorial on Understanding
Instance and Class Members.




Question 10.
What does this mean "variable <something> might not have been initialized" ?

Answer.
This is caused by using a variable that doesn't have a value. For example,
declaring an int without initializing it's value, then using it somehow (without a
value). Note that class data members are initialized implicitly. The following code
produces the compiler error:


        ...
        int x; // x doesn't have a value "hasn't been initialized";
        System.out.println("x = " + x); // attempting to use x before
giving it a value
        ...
To fix this problem, the value x must be given a value before using it:
        ...
        int x = 0; // x now has a value
        System.out.println("x = " + x); // using x with a value
        ...
Question 11.
What does this mean "unreported exception <something>; must be caught or
declared to be thrown" ?

Answer.
This is caused by a misunderstanding of the concepts of exception handling in
Java. Generally, Java has three types of errors that can occur, a runtime "Error",
a non-checked "Exception" or a checked "Exception." A runtime Error is usually
fatal and should not be handled at all in your code. A non-checked Exception is
recognizable because it is of type java.lang.RuntimeException (or a subclass)
and usually indicates a programming error, thus, it probably should not be
handled (of course, there are always exceptions (no pun intended) to this rule).
Checked Exceptions are usually recoverable and it is enforced by the compiler
that you (the developer) handle them, hence, the compile error when you don't.
For a better understanding of how to handle exceptions, see the following
tutorial:
http://java.sun.com/docs/books/tutorial/essential/exceptions/




Question 12.
What does this mean "Note: <something> uses or overrides a deprecated API.
Note: Recompile with -deprecation for details."?

Answer.
Taken directly from the Sun Microsystems' web site
(http://java.sun.com/docs/books/tutorial/post1.0/converting/deprecation.html)

You might have heard of the term "self-deprecating humor." It describes humor
that minimizes one's own importance.
Similarly, when a class or method is deprecated, it means that the class or
method is no longer considered important. It is so unimportant, in fact, that it
should no longer be used at all, as it might well cease to exist in the future.

The need for deprecation comes about because as a class evolves, its API
changes. Methods are renamed for consistency. New and better methods are
added. Attributes change. But making such changes introduces a problem: You
need to keep the old API around until people make the transition to the new one,
but you don't want developers to continue programming to the old API.

The ability to mark a class or method as "deprecated" solves the problem.
Existing classes that use the old API continue to work, but the compiler can issue
a warning when it finds references to deprecated items. Meanwhile, API
documentation can warn the user against using the deprecated item and tell the
user how to avoid doing so. To mark API as deprecated, the implementer of the
API uses a special tag in doc comments: @deprecated.
--------------------------------------------------------------------------------
Note: "Deprecated" and "depreciated" are not the same. "Depreciated" is a
financial term that means "lowered value." Although the meanings are similar,
classes and methods are deprecated, not depreciated.
--------------------------------------------------------------------------------

The following document describes how to overcome this compiler warning:
http://java.sun.com/docs/books/tutorial/post1.0/converting/converting.html




Question 13.
How do I generate a random number between x and y ?

Answer.
The java.lang.Math class provides a method called random() that returns a
double value that is "greater than or equal to 0.0 and less than 1.0." Therefore,
using some simple mathematics, you can generate a value between any range
with the following piece of code:

         double num = Math.random() * (y - x) + x;

This will generate a random number between x (inclusive) and y (exclusive).

Question 14.
What are access modifiers (public, protected, private, default) ?




Answer.
In the Java programming language, there are four different types of access
modifier. An access modifier is applied to classes, class data members and class
methods. These access modifiers describe what type of scope or visibility they
have. All classes, class data members and class methods have some type of
access level (even if one isn't specified).

These access modifiers are :
public
protected
package-protected (also called default)
private

To specify a class, data member or method as having access scope of type
default is to not explicitly declare any access modifier at all.
A description of the access modifiers follows, in order of least restrictive to most
restrictive:
public
A public class, data member, constructor or method has scope to all other
classes. All classes can see each others' public classes, data members,
constructors and methods.

protected
A protected class, data member, constructor or method has scope to itself, it's
subclasses and classes within the same package. A class can see the protected
classes, data members, constructors and methods of its' superclass and classes
within the same package. Top level classes cannot be declared as protected.

package-protected (or default)
A package-protected class, data member or method has no access modifier
explicitly specified. A class, data member or method which is declared as
package-protected has scope only within its' package. Classes that are declared
to be in the same package can see each others' package-protected classes, data
members and methods. Classes that are declared with package-protected access
scope are available to classes within the same package. The package-protected
access modifier is also referred to as default scope or package-friendly.

private
A private data member or method has scope only within itself. A class can see
only its' own private clases, members, constructors and methods. Top level
classes cannot be declared private.

For further information:
http://java.sun.com/tutorial/java/javaOO/accesscontrol.html




Question 15.
What is "inheritance", "polymorphism (run-time binding)", "an interface" ?

Answer.
These concepts are not trival. A good understanding of these (and other)
concepts is essential to make good use of the Java programming language. The
following online tutorial is a good place to start to understanding these important
concepts:
http://java.sun.com/docs/books/tutorial/java/concepts/




Question 16.
What is method overloading ?

Answer.
Method overloading is distinct from method overriding - they are two separate
concepts. Method overloading is where a class provides a method which has the
same name but different type and/or order of parameters. Method overloading is
generally used where a class can perform the same operation on more than one
type of data. Note that a class cannot contain two methods with the same
"signature." A method signature is defined by it's name and type/order of it's
parameters. The method return type and modifiers have no effect on the method
signature. The following is an example of method overloading:

        class AddNumbers
        {
          public double add(double a, double b)
          {
                return a + b;
          }

          public int add(int a, int b)
          {
                return a + b;
          }

          /*
          public long add(int a, int b) // illegal, a method with the
same signature already exists
          {
                return a + b;
          }
          */
        }

For further information:
http://java.sun.com/tutorial/java/javaOO/methoddecl.html




Question 17.
What is method overriding ?

Answer.
Method overriding is distinct from method overloading - they are two separate
concepts. Method overriding is where a class provides a method with the same
signature as a method that is declared in it's superclass. The subclass' method
does not inherit the functionality of it's superclass' method unless it is done
expicitly using the "super" keyword. The following code demonstrates method
overriding:

        class Superclass
        {
                void method1()
                {
                        System.out.println("Superclass.method1()");
                }

                 void method2()
                 {
                         System.out.println("Superclass.method2()");
                 }
        }

        class Subclass extends Superclass
        {
                // Overrides method1() and loses the functionality of
the superclass method1()
                void method1()
                {
                        System.out.println("Subclass.method1()");
                }

               // Overrides method2() and explicitly calls the
functionality of the superclass method2()
               void method2()
               {
                       super.method2();

                         System.out.println("Subclass.method2()");
                 }
        }

For further information
http://java.sun.com/tutorial/java/javaOO/override.html




Question 18.
Can static methods be overridden ?

Answer.
No. A static method of a subclass that has the same signature as a static method
of a superclass does not actually override it. The subclass method cannot call on
the superclass methods functionality with the "super" keyword..

For further information:
http://java.sun.com/tutorial/java/javaOO/override.html




Question 19.
Can private methods be overridden ?

Answer.
No. A private method of a subclass that has the same signature as a private
method of a superclass does not actually override it. This is because the two
methods work independantly of each other due to their access scope. The private
subclass method cannot call on the private superclass method with the "super"
keyword since this is a violation of the private access scope.
Question 20.
What does "immutable" mean ?

Answer.
The term immutable simply means unchangeable. Immutable objects do not
change once their constructor has executed. You may already know that the
java.lang.String class is immutable, despite the appearance that it is not, due to
its convenient concatenation operator. You may also know that if you need to
write code that constructs a single String object over a number of separate
statements, it is more efficient to use the java.lang.StringBuffer object.

Immutability is implemented as a design pattern that the programmer builds into
the class. There are some general characteristics that are usually found in all
intentionally immutable objects. These rules follow:

- A class is instantiated and all of its properties are set through the
constructor(s). When the arguments are passed at creation, it eliminates any
need for setter methods on the class that might be called later.
- The class is declared final. This prevents another developer from extending
your class and implementing code that supports mutability.
- The properties of the class are private. This prevents other objects from
modifying the attributes directly, and adds another layer of protection from
subclassed code over making the class final (with one very exceptional rule).
- Other than the constructor(s), there is no code in the class that changes the
properties of the object. Any methods or events for the class must treat the
private attributes as read-only. In this way, the final state of the object is
determined when it is constructed, and no opportunity exists to change it for its
lifetime.
- If methods are implemented that perform operations on the data abstracted by
the class, the result of those operations are another instance of the class
containing the modified data.
- If the class is sufficiently general purpose in scope, it may be packaged with a
companion object that is mutable. This is the case with the String and
StringBuffer classes.




Question 21.
Does Java pass parameters by reference, by value, both or neither ?

Answer.
Java pass all parameters strictly by value. This may be contrary to advice that
you receive from both (claimed) experienced and inexperienced people. I can
assure you that they need a walloping; Java is purely pass by value. To clarify,
there is some deeper understanding that is essential. This understanding is not
trivial or useless but it is necessary to understanding how to use the Java
Programming Language effectively.
Java has two basic data types; primitive values and object references. Java does
not permit direct access to objects (as in .NET), but allows the developer to
declare a reference to an object type. There are 8 primitive data types (long, int,
short, char, byte, boolean, float and double). Consider the following piece of
code:

        ...
        Object o = new Object(); // declares an object reference called
'o' that refers to an object of type java.lang.Object
        String s = "blah"; // declares an object reference called 's'
that refers to an object of type java.lang.String (a literal String)
        int x; // declares a primitive type called 'x' of type int
        ...

In memory, the above code looks like this:




Now calling a method and passing these three parameters (by value) with the
following code:

        ...
        method(o, s, x);
        ...

        void method(Object o2, String s2, int x2)
        {
                // What does memory look like now ?
        }
The model in memory now looks like this:
The "greyed out" areas represent variables that method2 does not have access
to. Notice that method2 can still "see" the object instances, but not the original
caller's object references. Therefore, if an object instance is altered through one
of method2's object references, the change to the instance will be reflected in
the original caller's object references. This will give the false impression that the
object was passed by reference. In fact, the object reference was passed by
value. If method2 had changed the value of the references, the change would
not have been reflected to the caller in any way. The primitive data type was
passed by value and the effect was not seen at all in the original caller. To
reiterate, understanding this concept is not trivial or academic. It is fundamental
to the use of the Java Programming Language. Java is strictly pass by value.




Question 22.
Can Java applications leak memory ?

Answer.
Yes. Consider the following code:

         import java.util.*;


         public class Stack
         {
                 private Object[] elements;
                 private int size = 0;
                 public boolean leak = false;

                  public Stack(int initialCapacity)
                  {
                          elements = new Object[initialCapacity];
                  }

                  public void push(Object e)
                {
                         ensureCapacity();
                         elements[size++] = e;
                }

                public Object pop()
                {
                        if(size == 0)
                        {
                                throw new EmptyStackException();
                        }

                         if(leak)
                         {
                                 return elements[--size];
                         }
                         else
                         {
                                 Object result = elements[--size];
                                 elements[size] = null;
                                 return result;
                         }
                }

                private void ensureCapacity()
                {
                        if(elements.length == size)
                        {
                                Object[] oldElements = elements;
                                elements = new Object[2 * elements.length
+ 1];
                                 System.arraycopy(oldElements, 0,
elements, 0, size);
                         }
                }
        }
The following code is likely to cause a java.lang.OutOfMemoryError caused by a
memory leak in the Stack class:
        class Foo
        {
                private int[] vals = new int[10000];
        }

        class Bar
        {
                public static void main(String[] args)
                {
                        final int size = 1600;
                        Stack s = new Stack(size);
                        s.leak = true;

                         for(int i = 0; i < size; i++)
                         {
                                 s.push(new Foo());
                         }
                         for(int i = 0; i < size; i++)
                         {
                                 s.pop();
                         }

                         System.out.println("Pushed and popped " + size +
" objects");

                         for(int i = 0; i < size; i++)
                         {
                                 s.push(new Foo());
                         }

                         for(int i = 0; i < size; i++)
                         {
                                 s.pop();
                         }
                 }
        }




Question 23.
Can I invoke the garbage collector ?

Answer.
No. Both the java.lang.System and java.lang.Runtime classes provides a gc()
method that "suggests that the Java Virtual Machine expend effort toward
recycling unused objects in order to make the memory they currently occupy
available for quick reuse." It is not guaranteed when or if the garbage collector
will run by making this call. The common misconception that this method invokes
the garbage collector is a source of many subtle errors in Java applications.




Question 24.
Can I convert my Java application into a Windows executable (.exe) ?

Answer.
What you want to do is possible, but it is not recommended. Java is designed to
be a platform independent language. Compiling a Java application into a
platform-specific executable defeats Java's design intent. Also, using native
compilers does not offer the significant performance improvements over the Java
Runtime Environment with JIT (Just-In-Time) enabled. If you want do distribute
your Java application, distribute it with Sun's Java Runtime Environment.
Question 25.
What is a "Singleton" class ?

Answer.
A singleton class is a class where there only exists at most, one instance during
runtime. This can be enforced by giving all constructors private access and
providing a public static method that returns the only existing instance. The
following is an example of a Singleton class BUT only if a single thread accesses
the instance. Achieving thread-safe access to singleton classes is a very
interesting topic, but is beyond the scope of this document.

         class SingletonExample
         {
                  private static SingletonExample instance;




                  private SingletonExample()
                  {




                  }


                  public static SingletonExample getInstance()
                  {
                            if(instance == null)
                            {
                                       instance = new SingletonExample();
                            }


                            return instance;
                  }
         }




Question 26.
How do I convert a .class file back to a .java source file ?

Answer.
Converting a compiled Java class file to its original source may be a violation of
the licence to use the software. Typically, there is seldom a legitimate reason for
doing such a thing. It is important to realise the unethical nature of violating the
terms of use of code that does not belong to you before performing this
operation.

In order to "decompile" a Java class file to a Java source file, you will require the
use of a Java decompiler. Some searching around on a web search engine for a
"Java decompiler" will likely yield the desired results.




Question 27.
How do I clear the console screen ?

Answer.
You can't without making a native call using JNI or executing a system
command, and, in both cases, losing platform independance. You can "kind of"
clear the screen by printing a series of new lines.

         ...
         for(int i = 0; i < 100; i++)
         {
                 System.out.println();
         }
         ...

The reason for this is that Java doesn't assume that it's operating environment
has a console screen. You don't have a screen for servlets, EJB and various other
environments, so it makes sense not to assume the existance of one. Generally,
clearing a console screen means one of the following:
- You are a university student trying to "pretty up" your assignment, in which
case, it's not worth writing bad code in order to do something that Java was not
designed to do.
- You are using a command line interface where you should be using a
windowing interface (such as swing) if you want to perform operations such as
clearing a screen.
- You have too much time on your hands (Go and read a good book on Java,
instead of writing poor code).




Question 28.
How do I create a String that represents a double (or float) value with only 2
decimal places ?

Answer.
By using the java.text.DecimalFormat class. The following is an example:

         double d = 12345.678;
         DecimalFormat df = new DecimalFormat();
        df.setMinimumFractionDigits(2);
        df.setMaximumFractionDigits(2);
        String formatted = df.format(d); // "12345.68"

Alternatively:

        double d = 12345.678;
        DecimalFormat df = new DecimalFormat("#.00");
        String formatted = df.format(d); // "12345.68"

Question 29.
Does Java support multiple inheritance ?

Answer.
No. Classes may inherit from one and only one (not zero, implicitly or explicitly)
class and may implement zero or many interfaces. Interfaces may inherit from
zero or more interfaces - this is not (and is not even close to) multiple
inheritance. The only exception to this rule is java.lang.Object which does not
have a superclass.

For further information:
http://java.sun.com/tutorial/java/javaOO/subclasses.html
http://java.sun.com/tutorial/java/interpack/interfaces.html




Question 30.
How do I make a javax.swing.JTextArea scroll to the end ?

Answer.
First, the JTextArea must be within a javax.swing.JScrollPane. Then set the caret
position of the JTextArea to be at the end. Assuming the JTextArea has a
reference called 'ta':

ta.setCaretPosition(ta.getText().length() - 1);




Question 31.
Can I execute an external command ?

Answer
Yes you can. Be aware of the consequences of doing such a thing. Your
application then becomes dependant on the platform which the external
command runs on. It may (or may not) be worthwhile allowing the user of your
application to configure the external command, since it changes under so many
different operating environments.
You can achieve this by calling one of the exec methods of the java.lang.Runtime
class, which will fork a process from the JVM. A handle to this process is returned
from the method as a java.lang.Process.




Question 32.
Can I reference the subclass from a superclass ?

Answer
No. Wanting to do such a thing generally indicates a design flaw. It is not
possible to explain where the design flaw is, since this question is too general.
Therefore, I will propose some questions that will hopefully assist you to
understand why this a design flaw. Firstly, what is "the" subclass ? A superclass
can have more than one (or even none) subclasses - this rules out the concept of
"the" subclass. A subclass is dependant on its superclass, and this dependancy is
unidirectional - a superclass cannot have a dependancy on a subclass (unless of
course, it is some other relationship besides inheritance, but that is beside the
point). How can a developer design a superclass that knows about ALL of its
subclasses ? Deriving from a class provides you with the same functionality as
the superclass - how does the superclass know about the subclass, since it is
added at a later date (due to the unidirectional dependancy) ? Perhaps what it is
in the subclass actually belongs in the superclass ? Perhaps you need to use the
Template Method Design Pattern ? This is clearly speculation and a more
concrete solution can only be arrived at with some more thought on your behalf.

Question 33.
Is it possible to prevent a thread of execution from executing for a specified
period of time ?

Answer
It is only possible to prevent the current thread from executing for a specified
period of time, but not any arbitrary thread. This is achieved by putting the
thread into a "sleep" state. It is important to realise the after the specified period
of time, the thread enters the "ready for execution" state, NOT the "execution"
state. The time at which the thread enters the "execution" state after sleeping
(and then entering "ready" state) is completely indeterminate and is the
responsibility of the thread scheduler. It can be said that "sleeping a thread
prevents the current thread of execution from executing for AT LEAST the
specified period of time". Therefore, causing a thread to sleep should not be
relied upon as an accurate timer, as accuracy is not guaranteed, and in practice,
it seldoms occurs.

The java.lang.Thread class exposes two static sleep methods:
java.lang.Thread#sleep(long)
java.lang.Thread#sleep(long, int)
Considering the lack of accuracy when putting a thread into the sleep state,
there doesn't seem to be a good reason why anyone would want to call the
method that takes the number of nanoseconds as an argument.




Question 34.
Why shouldn't an Integrated Development Environment (IDE) be used for
learning Java ?

Answer
It is an unfortunate fact that those who have a fundamental understanding of
Java know the answer to this question, while those who are still learning, often
choose to ignore it. An IDE hides the details of the inner workings of Java, and at
times, the user is abstracted away so much, that when a problem is
encountered, the user consults the IDE for resolution, rather than understanding
that "underneath" the abstractions given by the IDE, the problem is lurking.

For example, a user who has an understanding of Java and is using an IDE might
perform the following actions:

 Encounter a java.lang.NoClassDefFoundError
 Recognise the message as a type of Throwable and consult the API documentation for
that type
 Recognise the error made after determining the meaning of that error type
 Fix the error
 Continue development

In contrast, a user who is learning Java, and is using an IDE might perform the
following actions:

 Encounter a java.lang.NoClassDefFoundError
 Being unable to determine what this message means, consults the help for the IDE,
which clearly, won't reveal any clues
 Consult a newsgroup or some internet group for assistance, where any explanation that
is given, is well beyond the understanding of the user
 Search for the error message on the internet, which reveals ad hoc advice that is
unrelated to the actual problem (instead of the more likely, IDE setting)
 Continues searching for answers to what is generally a trivial problem, which takes
several hours, while the competent user resolved the issue in less than one minute.

This example is one of the many thousands of possibilities that an IDE can
present to a user who is well out of their depth of understanding. Some people
have a hard time recognising their shortcomings, swallowing their pride, and
learning with the appropriate material and tools. The best way to learn Java is
with a text editor (even Notepad or vim will do!) and the Java 2 SDK. As a
university teacher, I see this mistake all too often. Some of the excuses I hear
are outrageous:

 I don't have time to learn Java properly
... but you have time to fix the infinite number of possible problems that are well beyond the scope of
your understanding ?


 But it hasn't given me any problems (yet)
Oh it will. Like I said, I've seen it far too many times. If it doesn't, it is purely coincidental (video tape
it - it's a rarity!).


 The IDE makes it easier for me
The IDE is doing things that you don't understand and as soon as something "breaks", you will be in
big trouble.


 The IDE writes my code for me, so that I don't have to

The IDE is writing code for you that you don't understand. What happens when the IDE isn't capable
of producing the code exactly as you want ? Are you capable of editing it ?



Learning the intricacies of Java is very important for anyone who intends on
developing seriously. This may be contrary to the belief of the untrained user,
and I can certainly see why. It is difficult to accept that the tools that you are
using are actually a hindrance, while they are disguising themselves as helpful
tools. This opinion is not just my own, but that of several very competent
developers who have all learnt The Hard Way But The Right Way.




Question 35.
When should I use java.util.Vector/java.util.Hashtable ?

Answer

The classes java.util.Vector and java.util.Hashtable are remnants of JDK 1.1 that
have been kept in the core API to maintain reverse compatibility with older code.
These classes were "retrofitted" in JDK 1.2 to fit into the new Java Collections
Framework. Newer classes/interfaces were introduced in JDK 1.2 that achieve
the same function as Vector and Hashtable, and do not have to maintain any
backward compatibility. Lessons that were learnt from previous versions of the
JDK could be applied to these new classes without fear of breaking earlier code.
The same functionality of Vector can be achieved by using java.util.ArrayList and
the functionality of Hashtable can be achieved by using java.util.HashMap (there
is a minor difference in that HashMap permits nulls). If you require thread safety
on these types, you can use java.util.Collections to synchronize them, since
Vector and Hashtable are already thread-safe, and often times, unnecessarily.

In general, you only need to use a Vector or Hashtable if you are supporting Java
Runtime Environment versions that are older than 1.2. More often that not, the
newer classes/interfaces should be used in order to take advantage of
performance and maintenance benefits if this is not the case.

If you insist on using a Vector or Hashtable for some unforeseen reason, you
should always use (at least) a java.util.Map reference to refer to a Hashtable
and/or (at least) a java.util.List reference to refer to a Vector. This same
guideline applies to using HashMap and ArrayList. The reasoning for this, and
many other good practices for the Java Collections Framework are detailed in the
tutorial.

Javaworld Article: http://www.javaworld.com/javaworld/javaqa/2001-06/03-qa-
0622-vector.html




Question 36.
Can I increase efficiency by using less import statements ?

Answer

First the term "efficiency" must be defined.

The quantity and type (wildcard or fully qualified) of import statements does not
affect runtime performance of an application, so in terms of "efficiency of
runtime performance", the answer is "no".

The quantity and type of import statements does affect compile-time
performance - that is, less import statements generally means your application
will compile faster; also, using fully qualified import statements rather than
wildcard import statements generally means your application will compile faster.
If the term "efficiency" is defined as the "efficiency of the compiler to compile my
application", the answer is "yes".

Source code becomes more maintainable when full qualified imports are used,
and unused imports are absent. If the term "efficiency" is defined as the
"efficiency of a code maintainer to read and maintain the code", the answer is
"yes".




Question 37.
Can I start my java.lang.Thread more than once ?

Answer

No. A thread that has been run and completed (by finishing the run() method)
cannot be restarted. Attempting to restart a thread that has completed execution
(or is already running) results in a java.lang.IllegalStateException. However, you
can create and start more than one thread with an instance of
java.lang.Runnable (which defines what the thread does during execution in its
run() method).

Fore more information:
http://java.sun.com/docs/books/tutorial/essential/threads/index.html




Question 38.
What's the difference between javaw.exe and java.exe ?

Answer

Both of these executables start up a JVM, however, only javaw.exe is available
on the Microsoft Windows platform. The javaw.exe executable allows the user to
start the JVM without the need for a command console from which to launch it
from. This is useful for applications that do not require the user to view the
command console on the Microsoft Windows platform, such as graphical
applications.




Question 39.
How do I exit my application ?

Answer

Some developers will immediately jump at this question claiming "System.exit"
is the answer. However, naively calling this method can cause potential
problems, albeit the fact that it occurs often. System.exit(int) forces a JVM
shutdown and returns with the exit code given as the parameter. It is important
to realise that it is not just your application that will cease running, but any other
applications running within the JVM, and the JVM itself. This may cause
undesirable results, leaving data which is external to your application (or any
other application under the JVM) in an inconsistent state.

Seldom in an application is there a need to forcefully shutdown the JVM. A well
designed application will have taken into consideration issues regarding flow
control, and application logic will be implemented such that the application exits
cleanly (usually by exiting the main method) when it is time to do so. It is
important to ensure that all non-daemon threads that your application creates
are no longer executing when a clean exit is intended. Also, consider that an
application that has more than one exit point is difficult to maintain.




Question 40.
Why is my GUI application broken if I set the layout to null ?
Answer

Quite often, developers of Swing applications will set the layout of a
java.awt.Container to null, in order to avoid the complexities involved is using
Layout Managers. This approach is fraught with many pitfalls that the developer
may not be aware of. For instance, the application may not run correctly on a
system with:

 different installed fonts to the development system.
 different screen resolution to the development system.
 different locale settings to the development system.

Setting a layout to null is generally considered poor form, and applications that
violate this rule should be considered defective, since it is not guaranteed to run
on any system correctly, except for the system on which it was developed.

For more information:
http://java.sun.com/docs/books/tutorial/uiswing/layout/index.html

Question 41.
Why shouldn't I use floating-point types for representing monetary values (or
any value that demands accuracy) ?

Answer

Java floating-point types (float and double) are represented in IEEE 754 (Institute
of Electrical and Electronics Engineers) format as per Java Language
Specification 4.2.3. IEEE 754 format for floating-point types is a detailed
specification, suffice to say that a floating-point type is "an inexact
representation of an ideal real number" and operations performed on them are
inexact. You can witness these inaccuracies by performing an operation as
simple as System.out.println(2.4 * 1.111111); You will immediately notice that the
output is not the otherwise expected 2.6666664. This is due to the internal
representation of the floating-point type.

The correct approach for storing monetary values would be to use an integral
type (such as int, or long) that represents the number of cents guaranteeing
accuracy. Storing other data where accuracy is required should also use some
approach that involves integral types, and not floating-point types.

If you happen to encounter an application where monetary values have been
represented using an IEEE 754 floating-point type, please contact me such that I
can arrange for the "missing bits" of money to be deposited into my bank
account.

For more information on IEEE 754: http://grouper.ieee.org/groups/754/meeting-
materials/2001-10-18-langdesign.pdf
Question 42.
What's the difference between Java and J++ and J# and Javascript ?

Answer

First and foremost, these four technologies are distinct. That it to say "Java is
not J++ is not J# is not Javascript".

Java is a programming language designed by Sun Microsystems and it is this
language that this web page is dedicated to.

J++ is (was) a programming language designed my Microsoft Corporation to
compete against Java. It consists of a very similar syntax and API specification to
Java, however, it is not compliant with the specifications for Java set out by Sun
Microsystems, and this fact was the basis for a successful lawsuit filed by Sun
Microsystems Inc. against Microsoft Corporation in 2001.

J# is the successor to J++ developed by Microsoft as part of their .NET initiative
and again, is not compliant with the specifications for Java set out by Sun
Microsystems.

Javascript is a scripted loosely-typed (Java is strongly-typed) language
developed by Netscape, which unfortunately inherited a similar name to Java
that now results in confusion. Javascript is the language interpreted by web
browsers to perform certain browser-specific behaviour along with HTML. It has
no relationship to the Java 2 Programming Language, except for a similar name.




Question 43.
How do I access an outer class member/method from an inner class ?

Answer

<OuterClassName>.this.<member/methodname>

Here is an example:

         public class Outer
         {
                   private int x;




                   public class Inner
                   {
                              void method()
                           {
                                    Outer.this.x = 42;
                           }
                  }
         }




Question 44.
What is the newline character ?

Answer

A lot of misinformed developers will quickly reply to this question with an answer
of '\n'. The correct answer is that there isn't one. If you consult a Unicode table
(how Java characters are represented), you'll find that there is no character
designated as the line terminator. So where did '\n' come from ? The End Of Line
(EOL) terminating character on UNIX platforms is the Line Feed character '\n'
(0x000A). This does NOT apply to all platforms. For example, the Microsoft
Windows platform uses two characters, Carriage Return and Line Feed to
represent an EOL terminator "\r\n" (0x000D 0x000A); the Macintosh platform
uses the Carriage Return to represent the EOL terminator "\r" (0x000D). Other
platforms may use other character sequences to represent an EOL terminator.
When you see code that is written in a fashion similar to this:

         System.out.print("hello world\n");

it is important to realize that you are seeing the string "hello world" followed by
the Line Feed character, NOT an EOL terminator as some would suggest. If this
code was executed on a UNIX platform, you'd have that character expressed as
an EOL terminator (UNIX platform-specific behaviour), but this is not the same
as writing an EOL terminator in Java. Some Microsoft Windows applications take
into account that a lot of developers erroneously insist on using '\n' as an EOL
terminator and act accordingly (so that you won't see the consequences). So
what if you wanted an EOL terminator in a Java environment ? Since Java is
platform-independant, there needs to be a way of representing the EOL
terminator on all the different platforms. You can obtain the EOL terminator by
accessing the System property called "line.separator". Alternatively, when you
write to streams, you can use a java.io.BufferedWriter to write a new line or a
java.io.PrintStream to println. Doing this will take care of writing out the correct,
and often intended, EOL terminator (by accessing the line.separator System
property internally). In the code sample above, if the intention is to print "hello
world" followed by an EOL terminator (instead of a Line Feed character as it does
now), you can simply use the println method, since System.out is a PrintStream.
To reiterate in conclusion, the following statement is NOT equivalent to the
statement given above.
         System.out.println("hello world");




Question 45.
How do I use a multi-dimensional array ?

Answer

A common misconception is that Java supports the use of multi-dimensional
arrays. In fact, Java supports arrays whose elements may be of any type,
including arrays. That is, an array of arrays and an array of arrays of arrays is
quite possible, while a "2D array" and a "3D array" is not. This distinction is
important in coming to terms with the Java programming language, and is not
purely academic as some might suggest. Consider the following code:

         // An array that holds String arrays - NOT a 2D String array.
         String[][] array;

         // Iterate the "outer" array
         for(int i = 0; i < array.length; i++)
         {
                 // Get an element of the "outer" array.
                 String[] element = array[i];

                  // Iterate the "inner" array.
                  // Length is not constant for all elements.
                  for(int j = 0; j < element.length; j++)
                  {
                          // Get an element of an "inner" array.
                          String s = element[j];
                  }
         }

It is important to realise, that in the above code sample, there is no "2
dimensional" array. There is an array whose elements are String arrays. A
language such as COBOL supports true multi-dimensional arrays (known as
"tables"). To understand this distinction is important to use arrays effectively in
Java (and COBOL too!).

For more information:
http://java.sun.com/docs/books/tutorial/java/data/arrays.html




Question A.
Who is the author of this document ?

Answer.
My name is Tony Morris. I live on the Gold Coast in the state of Queensland,
Australia. I have a Bachelor of Information Technology which I achieved at
Griffith University, Gold Coast. I have also attained Sun Certified Programmer for
the Java 2 Platform (310-035) and Sun Certified Developer for the Java 2
Platform (310-027). I currently work full-time for IBM Corporation as a Software
Engineer specializing in security software development. I am a part-time teacher
for the School of Information Technology at Griffith University, where I teach a
range of topics, including Java programming.

See my Curriculum Vitaé here

Question B.
I believe there is something that is incorrect, needs improving or I have
something to add to this document, who do I contact ?

Answer.
Email the author.

Back to questions

				
DOCUMENT INFO