General Java Questions - II

Q: I know that Java file should have the same name as public class in the file..
But what are rules for files that have no public classes?
Answer: No rules are defined for such case! It is up to you how to name it. Please check my
// ****** file *******************
class G {
public static void main(String[] args) {
System.out.println("This is class G!");
class Z {
public static void main(String[] args) {
System.out.println("This is another class Z!");
class AB {}
class CD {}
class EF {}
After compilation you will get AB, CD, EF, G and Z classes.
You can run G and Z (they have main method), but not AB, CD, EF.
Try it:
java G
file:///C|/330_new/330_new/general_java-II.htm (1 of 10) [2003-07-22 22:07:54]

General Java Questions II
java Z
Q: I mainly use C++ but I have a program to write and java seems to be the right tool for
this job. That said my java skills are a bit rusty. I downloaded a free IDE and am ready to go but
I'm not a fan of putting my method implementations in the class definition.
Is there a way to separate the implementation from the class definition?
Like in c++ there are .h files and .cpp files.
Answer: You can use an interface and an implementation class, if you like.
The interface has just the method signatures; the class has their implementations. You can
then declare variables having the type of the interface, and assign objects of the
implementation class created with "new", or by a factory method.
Java is very different from C++ in that the interface of a class is defined by a compiled view of
that class, not by textual inclusion of source for a separate interface description. Therefore the
concept of splitting interface from implementation does have the same meaning in Java as in
In Java, you can separate the description of pure interfaces (or abstract classes) from concrete
classes that implement (or complete) them. This is a useful technique - compare
java.util.Collection and java.util.List to java.util.ArrayList and java.util.LinkedList.
Also, it is traditional to define the return type from factory methods and other such producers to
be pure interfaces to allow the factory or other class to decide which implementation to give
you - this is used extensively in and java.sql packages.
Phil Hanna (Author of JSP: The Complete Reference, Chuck
Q: Constructors are similar to methods... I know that they do not return any value. Could I
say that they have void type (no return type)?
Answer: Not. Constructors are not methods and they are different because they:
* always have the same name as the class name
* have no return type, even void!
* are not inherited and that's why (by the way) you can declare them final.

Q: Simple question: why constructor doesn't work in following example?
class Start {
public void Start() {
System.out.println("Konstruktor START");
file:///C|/330_new/330_new/general_java-II.htm (2 of 10) [2003-07-22 22:07:54]
General Java Questions II
public class Test {
public static void main(String[] args) {
Start s = new Start();
Answer: Because you have included the return-type 'void' in the method declaration, it
becomes a normal method, that just happens to have the same name as the class - so it won't
get used as a constructor. Remove the 'void' and it should work.
Vince Bowdren
P.S. by John: If you do not specifically define any constructors, the compiler inserts an invisible
zero parameter constructor "behind the scenes". Often this is of only theoretical importance,
but the important qualification is that you only get a default zero parameter constructor if you do
not create any of your own.
Your program used this zero parameter constructor and you saw nothing...
Q: If I declare an array of an objects, say Dogs, is that memory taken when I create the
array or when I create the objects in the aray when I declare this array:
Dog[] dog = new Dog[100];
or does it take the memory when I actually create the Dogs in the array eg:
for(int i = 0;i<dog.length;i++)dog[i] = new Dog();
Answer: The statement above is actually two-fold. It is the declaration and initialisation of the
array. Dog[] dog is the declaration, and all this does is declare a variable of type Dog[],
currently pointing to null.
You then initialise the array with new Dog[100], which will create 100 elements in the array, all
of them referencing null.
It is important to realise that the elements of an array are not actually objects, they only
reference objects which exist elsewhere in memory. When you actually create the Dog objects
with new Dog(), these objects are created somewhere in memory and the elements in the array
now point to these objects.
Pedant point:
Nothing ever points to null. It is a constant that represents the value of a reference variable that
is not a pointer to some object new Dog[100] creates an array of 100 null Dog references.
Q: Hi there, does anybody know a good source of design patterns written in Java?
Answer: A pretty good (free to download) book.
file:///C|/330_new/330_new/general_java-II.htm (3 of 10) [2003-07-22 22:07:54]
General Java Questions II
Q: Whats the difference between the two: System.err. and System.out? When should we
use System.err?
Answer 1: System.out leads the output to the standard output stream (normally mapped to your
console screen), System.err leads the output to the standard error stream (by default the
console, too). the standard output should be used for regular program output, the standard
error for errormessages. If you start your console program regularly both message types will
appear on your screen.
But you may redirect both streams to different destinations (e.g. files), e.g. if you want to create
an error log file where you don't want to be the regualr output in.
On an UNIX you may redirect the output as follows:
java yourprog.class >output.log 2>error.log
this causes your regular output (using System.out) to be stored in output.log and your error
messages (using System.err) to be stored in error.log
Answer 2: System.err is a "special" pipe that usually is directed to the standard consolle. You
can redirect the System.out with the normal pipe control (| or >), but System.err no. If you want
to put both the "normal" output and the "error" output to a file you must use the special redirect
This allow you to send normal messages into a file or in the /null black hole, but still receive the
error messages on the console.

Q: Does anyone know how could I get the size of an Enumeration object? The API for
Enumeration only contains getNext() and next().
Answer 1: You can't. Theoretically, some classes that implement Enumeration may also
provide some way to get a size, but you'd have to know about the more specific run-time type
and cast to it... and none of the standard java.util Collections classes nor Vector or such
provide these methods in their Enumeration implementations.
Answer 2:
you can make your own class like this:
import java.util.*;
public class MyEnumeration{
int size;
int index = 0;
Enumeration e;
public MyEnumeration(Vector v){
size = v.size();
file:///C|/330_new/330_new/general_java-II.htm (4 of 10) [2003-07-22 22:07:54]
General Java Questions II
e = v.elements();
index = 0;
public boolean hasMoreElements(){
return e.hasMoreElements();
public Object nextElement(){
return e.nextElement();
public int size(){
return size;
public int getIndex(){
return index;
by Nicolas Delbing and Victor Vishnyakov
Q: Ok, I know that one cannot put primitive types into a hashmap (only objects or
references to them) and I know how to deal with that (write some kind of wrapper class).
What I'm interested in is: 'Why is that?' Why can I not put a primitive type into a hashmap?
Something to do with this 'heap' thing… Right?
Answer: HashMap requires a key or a value to be assignment- compatible with
java.lang.Object (i.e. to be an object or an array). Primitive types aren't ones.
You can use wrappers like java.lang.Integer for this purpose. All container classes require
some basic operations to be defined for all of its contained objects in order for it to organize the
For example, a hashmap requires a hashing method hashCode(). A primitive type doesn't have
any methods associated with it.
The distinction between primitive types (int) and their wrapper classes (Integer) is made purely
for optimisation purposes. For example, we wouldn't want to have to instantiate actual objects
in an array instead of just allocating a block of memory for an array of integers.
Q: Most people asked why there is an error, but my question is why this is NOT an error
Please take a look:
file:///C|/330_new/330_new/general_java-II.htm (5 of 10) [2003-07-22 22:07:54]
General Java Questions II
r is a number and s is a character, why can I put them together to make a comparison without
compilation error? Could somebody tell me... thank you
double r = 34.5;
char s = 'c';
if (r > s) {
System.out.println("r > s");
} else {
System.out.println("r < s");
Answer 1: Yes, char is indeed a 16-bit value. However, the actual answer is in the Java
Language Specification, section 5.6.2, which is at the following URL:
In summary, the char is automagically promoted to a double. No explicit cast is necessary
since the language rules say that it gets "promoted" to a double.
by John O'Conner
Q: == and equals ()... These two still make me confuse a lot of time.
Can somebody give me some thumb rule or explain it to me?
Answer: When you use == with a primitive -int, double, char, ... you are checking that the
values are identical. But if you use == with an object, you are checking that the 2 objects are
stored at the same address. In other words the references pointing to the same object...
Method equals () is different.
It is the same as ==, if it isn't overriden by the object class.
Many classes override the method equals (). In this case this method will check that content of
the object is the same or not, not addresses.
Q: What is difference between Iterator and Enumeration?
First of all Java FAQ Team wish you !!!HAPPY NEW YEAR!!! and then
Answer: from
The object returned by the iterator method deserves special mention. It is an Iterator, which is
very similar to an Enumeration, but differs in two respects:
Iterator allows the caller to remove elements from the underlying collection during the iteration
with well-defined semantics.
Method names have been improved.
file:///C|/330_new/330_new/general_java-II.htm (6 of 10) [2003-07-22 22:07:54]
General Java Questions II
The first point is important: There was no safe way to remove elements from a collection while
traversing it with an Enumeration. The semantics of this operation were ill-defined, and differed
from implementation to implementation.
The Iterator interface is shown below:
public interface Iterator {
boolean hasNext();
Object next();
void remove(); // Optional
The hasNext method is identical in function to Enumeration.hasMoreElements, and the next
method is identical in function to Enumeration.nextElement. The remove method removes from
the underlying Collection the last element that was returned by next. The remove method may
be called only once per call to next, and throws an exception if this condition is violated. Note
that Iterator.remove is the only safe way to modify a collection during iteration; the behavior is
unspecified if the underlying collection is modified in any other way while the iteration is in
The following snippet shows you how to use an Iterator to filter a Collection, that is, to traverse
the collection, removing every element that does not satisfy some condition:
static void filter(Collection c) {
for (Iterator i = c.iterator(); i.hasNext(); )
if (!cond(
Two things should be kept in mind when looking at this simple piece of code:
The code is polymorphic: it works for any Collection that supports element removal, regardless
of implementation. That's how easy it is to write a polymorphic algorithm under the collections
It would have been impossible to write this using Enumeration instead of Iterator, because
there's no safe way to remove an element from a collection while traversing it with an
Q: I try to copy an object of my own using the clone() method from java.lang.Object, but this
is a protected method so I can't use it. Is there some other way to get my objective of
duplicating an arbitrary object?
Answer: If you want to clone your object, you need to make it cloneable. To achieve this, you
need to do two things:
1. implement the interface Cloneable
2. override the method clone(), so that it
a. becomes public
b. calls super.clone()
c. if necessary, clones any members, or
file:///C|/330_new/330_new/general_java-II.htm (7 of 10) [2003-07-22 22:07:54]
General Java Questions II
d. if a member can't be cloned, creates a new instance.
Simple example:
public MyClass implements Cloneable {
int someNumber;
String someString;
public Object clone() {
// primitives and Strings are no
// problem
return super.clone();
In this case the method clone() of the class MyClass returns a new instance of MyClass, where
all members have exactly the same value. That means, the object reference 'someString'
points to the same object. This is called a shallow copy. In many cases this is no problem.
Strings are immutable and you do not need a new copy. But if you need new copies of
members, you have to do it in the clone() method. Here is another simple example:
public class SomeMember implements Cloneable {
long someLong;
public Object clone() {
return super.clone();
public AnotherClass extends MyClass {
SomeMember someMember;
public Object clone() {
AnotherClass ac = (AnotherClass)(super.clone());
if (someMember != null) {
ac.someMember = (SomeMember)(someMember.clone());
return ac;
Note that the class AnotherClass, that extends MyClass, automatically becomes Cloneable,
because MyClass is Cloneable.
Also note, that super.clone() always returns an Object of the type of the actual object, although
the superclass doesn't know anything about that sub class. The reason is, that Object.clone() is
a native method, which just allocates new memory for the new object and copies the bytes to
that memory. Native code has it's own ways of finding out which type to return ;-)
file:///C|/330_new/330_new/general_java-II.htm (8 of 10) [2003-07-22 22:07:54]
General Java Questions II
Karl Schmidt
Q: I was just wondering about the usefulness of Interfaces...
I was just wondering about the usefulness of Interfaces. I was under the impression that
interfaces could be used to perform multiple inheritance. But an interface only declares a
method - in a very abstract way.
A class that implements an interface needs to define its own implementation of a certain
method. What is the use of having an interface when nothing is being gained...?
Answer: If two classes implements the same interface, you can get a reference to the interface
instead of the effective class without bother what class are you managing.
This is very useful in RMI (for example) or in any condition when you have to take an object
without knowing exactly his class, but only the interface that it implement.
For example:
public void recurseList( List l )
the generic List ensure that you can use every List for this method (ArrayList, AbstractList,
Vector...), so your calling method can be:
ArrayList l = new ArrayList(); or
Vector l = new Vector();
recurseList( l );
Without any problem.
by Davide Bianchi
Q: I got a problem with an array/vector...
I got a problem with an array/vector.
my class contains a member:
static Vector quad[][];
in my constructor I got:
Vector quad[][] = new Vector[row][col];
for (int i = 0; i < row; i++){
for (int j = 0; j < col; j++){
quad[i][j] = new Vector (0,1);
// row and col are int between (10..50) -- it's a big I know, but that
file:///C|/330_new/330_new/general_java-II.htm (9 of 10) [2003-07-22 22:07:54]
General Java Questions II
might not be the problem
My PROBLEM (and I don't know what to do, really), I can't access quad[x][y] outside of the
constructor!!!! Within the constructor I've got full access on quad[x][x]. Java (1.2) returns a
NullPointerException on any method except within the constructor!!!
What's my fault!???
Answer: I guess you shouldn't write Vector here:
Vector quad[][] = new Vector[row][col];
so, the correct variant may be:
quad[][] = new Vector[row][col];
I guess You just overridden your static variable with one defined in your constructor:
Vector quad[][].
Thus, you're initializing NOT your class-scope static variable but your constructor-scope quad.
It's not reachable outside the constructor. And as for static quad, it has never been initialized!
And a first reference to it causes NullPointerException. I guess. I hope I'm right :)