Java FAQs
This FAQ (Frequently Asked Questions) page is a compilation of the FAQs that I have written for my students and FAQ's taken from
http://metalab.unc.edu/javafaq/javafaq.html
If you have any FAQs you would like to contribute please email me.
Other links:
http://www.drye.com/java/faq.html - THE JFC SWING FAQ
What is the CLASSPATH?
How do I convert strings to numbers?
You can convert strings into numbers using the Integer, Float, Double and Long type wrapper classes as
indicated by the following code snippet:
class ConvertTest {public static void main (String args[]) {
String str;
str = "25";
int i = Integer.valueOf(str).intValue();
System.out.println(i);
long l = Long.valueOf(str).longValue();
System.out.println(l);
str = "25.6";
float f = Float.valueOf(str).floatValue();
System.out.println(f);
double d = Double.valueOf(str).doubleValue();
System.out.println(d);
}}
The Integer class also has methods to get the byte and short values: byteValue() and shortValue().
How do I format numbers?
Customizing Formats
lesson from Object and Data Basics in the Java
Tutorial describes the use of DecimalFormat class to format floating point
numbers.
Where can you find the source code for the
Java classes?
The source code for the standard Java Library can be found in a jar file
that comes with Sun's Java Development Kit (JDK). In the root directory for the
JDK, you will find src.jar.
How do I open a Jar file?
A Jar file has the same format as a zip file. However, WinZip(7.0) does
not open Jar files when you double click on the Jar file in the Window Explorer.
Instead, you must open WinZip and then either drop the Jar file on WinZip's
title bar or you need to use WinZip's File menu.
What are those extra classes with $ at the end of their names?
Many classes have inner classes. These are often created when a simple event
handler is needed. There is not need to create a full fledge class, so an inner
class that is only visible to the parent class can be created. These inner
classes however require a name for their class file. The Java compiler construct
a name for the inner class by appending $n (the 'n' is an index number) to
the name of the parent.
Can I locate the line that causes an exception when an applet runs in a browser?
The Java Console traps all uncaught exceptions. The Java Console displays the call stack with the line number of the code that generates the exception. As an example te following dump from the Java Console indicates that a NoClassDefFoundError exception was generated at line 57 of daisy.Susan.init():
java.lang.NoClassDefFoundError: daisy/Susan$1
at daisy.Susan.init(Susan.java:57)
at sun.applet.AppletPanel.run(AppletPanel.java:333)
at java.lang.Thread.run(Thread.java:479)
The Java Console also catches all the messages you see flying by on the status bar of the browser.
You can make the Java Console visible from Netscape by selecting Communicator/Tools/Java Console from the menu.
Why does the following code not give a compiler warning:
while(x < 9);
{
// do something
}
A cure for this problem is to change formatting styles so that the open brace is
at the end of the preceding line:
while (x < 9) {
// Do something
}
Now when your fingers auto-type that semicolon at the end of the line you get
a syntax error.
How do I copy multi-dimensional arrays?
Copying a one dimensional array is straight forwarded and can be done using System.arraycopy:
System.arraycopy( this.nVertices, 0, copy.nVertices, 0, nVertexCount );
Copying a two dimensional array is however more problematical because multi-dimensional arrays are represented as arrays of arrays. This is an issue when you are cloning an array. System.arraycopy() will give you a copy of the references to the embedded arrays. Instead you must do something like the following if you want to clone an array:
copy.nVertices = new double [nVertexCount][3];
for ( int i = 0; i < nVertexCount; i ++) {
copy.nVertices[i][0] = this.nVertices[i][0] ;
copy.nVertices[i][0] = this.nVertices[i][0];
copy.nVertices[i][0] = this.nVertices[i][0];
}
Can applets communicate with
other applets on a webpage?
Applets may communicate with other applets running in the same virtual machine. If the
applets are of the same class, they can communicate via shared static variables. If the applets are of different
classes, then each will need a reference to the same class with static variables. In any case the basic idea is to
pass the information back and forth through a static variable.
An applet can also get references to all other applets on the same page using the getApplets() method of
java.applet.AppletContext. Once you've got a reference to an applet, you can communicate with it by
using its public members.
What does it mean that a class or member is final?
A final class can no longer be subclassed. Mostly this is done for security reasons with basic classes like
String and Integer. It also allows the compiler to make some optimizations, and makes thread safety a little
easier to achieve.
Methods may be declared final as well. This means they may not be overridden in a subclass.
Fields can be declared final, too. However, this has a completely different meaning. A final field cannot be
changed after it's initialized, and it must include an initializer statement where it's declared. For example,
public final double c = 2.998;
It's also possible to make a static field final to get the effect of C++'s const statement or some uses of C's
#define, e.g.
public static final double c = 2.998;
What does it mean that a method or field is "static"?
Static variables and methods are instantiated only once per class. In other words they are class variables, not
instance variables. If you change the value of a static variable in a particular object, the value of that
variable changes for all instances of that class.
Static methods can be referenced with the name of the class rather than the name of a particular object of the
class (though that works too). That's how library methods like System.out.println() work. out is a static
field in the java.lang.System class.
What does it mean that a method or class is abstract?
An abstract class cannot be instantiated. Only its subclasses can be instantiated. You indicate that a class is
abstract with the abstract keyword like this:
public abstract class Container extends Component {
Abstract classes may contain abstract methods. A method declared abstract is not actually implemented in
the current class. It exists only to be overridden in subclasses. It has no body. For example,
public abstract float price();
Abstract methods may only be included in abstract classes. However, an abstract class is not required to have
any abstract methods, though most of them do. Each subclass of an abstract class must override the abstract methods of its superclasses or itself be declared
abstract.
Does Java have pointers?
No, Java does not have pointers Java does have references. A reference is an abstract identifier for an object. It is not a pointer. A reference
tags a particular object with a name in the Java Virtual Machine (VM) so that the programmer may refer to it. How
exactly the virtual machine implements references at the level of machine code is VM-dependent and
completely hidden from the programmer in any case. Most VMs including Sun's use handles, not pointers. A
handle is a pointer to a pointer. At the level of machine code in the CPU a reference is an address in memory
where the address of the object is stored. This way the objects can be moved around in memory and only the
master pointer needs to be updated rather than all references to the object. This is completely hidden from the
Java programmer, though. Only the implementer of the virtual machine needs to worry about it. Indeed, this is
not the only way references can be implemented. Microsoft's VM actually does use pointers rather than
handles. Other schemes are possible.
How do you make a linked list without pointers?
When dealing with short list one can use the Vector class in java.util. It can do anything a linked list can do and a little more and
saves you a lot of coding which, after all, is the point of OOP and the class library. However it is array based
so insertions or deletions from the middle of a Vector are not as efficient as with a true linked list.
With Java 1.2 there is now a LinkedList class
java.lang.Object
|
+--java.util.AbstractCollection
|
+--java.util.AbstractList
|
+--java.util.AbstractSequentialList
|
+--java.util.LinkedList
All of the operations perform as could be expected for a doubly-linked list. Operations
that index into the list will traverse the list from the beginning or the end, whichever is
closer to the specified index.
Does Java pass method arguments by value or by reference?
Java passes all arguments by value, not by reference. However this is one of the few places where the
distinction between an object and a reference to an object becomes important. Object and array variables in
Java are really references to the object or array. This can make it look like an object is passed by reference if
you only modify the fields of the object or array, but do not change the reference itself. For example, consider
this program:
import java.awt.Point;
class changePoint {
public static void main(String args[]) {
Point p1 = new Point(0, 0);
changePoint(p1);
System.out.println(p1);
}
static void changePoint(Point p) {
p.x = 38;
p.y = 97;
}
}
It prints:
java.awt.Point[x=38,y=97]
Therefore the point has been changed. However the reference, which is what was really passed, has not been
changed. To see that consider the following program.
import java.awt.Point;
class dontChangePoint {
public static void main(String args[]) {
Point p1 = new Point(0, 0);
dontChangePoint(p1);
System.out.println(p1);
}
static void dontChangePoint(Point p) {
p = new Point(38, 97);
}
}
It prints:
java.awt.Point[x=0,y=0]
What happened in this example was that a copy of the reference p1 was passed to the
dontChangePoint()method. A new Point object was then assigned to that copy. However this did not change the old reference in
the main method. In the previous example the reference p in the changePoint()
method and p1 in the main()
method both referred to the same object. In this example p
and p1 refer to different objects after the new
Point is assigned to p.