General Java Questions - I

Q: Is JavaScript the same as Java?
Answer: NO! An Amazingly large number of people, including many web designers, don't understand the difference between
Java and JavaScript. Briefly it can be summed up as follows:
Java was developed by Sun Microsystems. Java is a full-fledged object-oriented programming language. It can be used to
create standalone applications and applet. Applets are downloaded as separate files to your browser alongside an HTML
document, and provide an infinite variety of added functionality to the Web site you are visiting.

The displayed results of
applets can appear to be embedded in an HTML page (e.g., the scrolling banner message that is so common on Javaenhanced
sites), but the Java code arrives as a separate file.
JavaScript on the other hand was developed by Netscape, is a smaller and simpler scripting language that does not create
applets or standalone applications. In its most common form today, JavaScript resides inside HTML documents, and can
provide levels of interactivity far beyond typically flat HTML pages -- without the need for server-based CGI (Common Gateway
Interface) programs.
Some server software, such as Netscape's SuiteSpot, lets web application developers write CGI programs in a server-side
file:///C|/330_new/330_new/general_java-I.htm (1 of 16) [2003-07-22 22:07:52]
General Java Questions I
version of JavaScript. Both client-side and server-side JavaScript share the same core JavaScript language, but each side
deals with different kinds of objects. Client-side objects are predominantly the components of an HTML web page (e.g., forms,
text boxes, buttons). Server-side objects are those that facilitate the handling of requests that come from clients, as well as
connectivity to databases.

Q: Is Java open source as distributed by Sun, i.e., all the modules including JVMs?
If not, is anyone else doing an open source implementation?
Answer: Java is not open source project. Though you can get the full source code under a Sun license. does open source implementation.
I read there: "Kaffe is a cleanroom, open source implementation of a Java virtual machine and class libraries. It is also a fun
project that was started by Tim Wilkinson and was made successful by the contributions of numerous people from all over the
But Kaffe is not finished yet! You can help by developing new and missing functionality, porting Kaffe to new platforms, and
testing your Java applications under Kaffe.
Kaffe mostly complies with JDK 1.1, except for a few missing parts.
Parts of it are already JDK 1.2 (Java 2) compatible."
John - The GNU Compiler for the Javatm Programming Language

Q: I will be thankful if anyone tells me why JVM is called virtual machine.
Answer: JVM is called a virtual machine because there is no real hardware which interprets the byte code. If you have done
any assembly programming for any microprocessor/microcontroller you will able to understand this. A microprocessor has
builtin instruction set to interpret the assemly code. Similarly the JVM is similar to a microprocessor in the sense it has its own
instruction set but it implemented in software. That is why it is called a virtual machine!
file:///C|/330_new/330_new/general_java-I.htm (2 of 16) [2003-07-22 22:07:52]
General Java Questions I
Q: Do anyone know the difference between java and C#.
Answer: They are different languages. Java has been around for about five years. C# has not been publicly released yet. One
is written by Sun Microsystems, one my Microsoft. They are fairly similar languages with C# having a few extra bits added on
to it.
C# bytecodes can be compiled to native exe files just as Java bytecodes can be. But C# is expected to be more closely tied to
the Windows operating system and standard interfaces that are part and parcel of Windows. Writing a native compiler that
collects all these interfaces and combines them into a unified whole that can run on ANY operating system may require
compiling proprietary windows components which Microsoft will make sure is hard to do and against its licensing policies. So
you can expect to see native compilers that compile for Windows platforms but
not to other operating systems.

Q: I read PHP 4 times faster than JSP. Why then do we need JSP?
Answer: These tools fill somewhat different niches and seldom directly compete.
PHP is good for situations where your page can interact more or less directly with a database, without the need for complex
business logic. Its strength is that it can be used to build pages VERY quickly. And, as you note, they run very quickly as well.
The JSP/Servlet model is more geared toward distributed n-tier applications where there is at least logical, and possibly
physical, separation of model, view, and controller functions. It is more complex than PHP, but also more scalable, and wellwritten
Java apps may be a great deal more maintainable because of the separation of logical tiers.
They're both nice tools, and I use both, but I don't think either one is going to kill the other anytime soon.
file:///C|/330_new/330_new/general_java-I.htm (3 of 16) [2003-07-22 22:07:53]
General Java Questions I

Q: My question is : is JSP as powerful as servlet?
I heard that JSP will eventually compile into servlet class file.
One thing can be done by servlet, can it be done by JSP too? In terms of http.
Answer: Everything a servlet does can be done in JSP and vice versa. Good programming practice (you will see some articles
over the last year in JavaPro) dictates to combine servlets and JSP in any significant web application.
JSP should be mainly HTML (or XML, or WML or whateverML) with little Java inside.
Servlets should be Java with few or not at all lines like this:
out.println( "<html>" );
out.printlb( "<body>" );
This creates a more or less clean separation between presentation (JSP) and business logic (servlet).
Java beans also have a role in this. I strongly recommend the JavaPro articles or whatever text on the MVC model you can
eugene aresteanu

Q: Doesn't Java have C's preprocessor functions? At least #define's? If not, the only way to define constants is with ‘final’?
So... no macros at all??
Isn't there, then, a separate "preprocessor" utility (at least), if I want to define things like
#define proc public void
or so?
Answer: The answer to that is either "No" or "No, thank God". Code gets read many, many more times than it gets written. You
should be constantly making things easy for the developers that have to maintain this after you've finished it (after all, it's
probably going to be you).
That's way Sun pushes its Java coding standards so hard.
Believe it or not, the only reason that I don't do much C++ work boils down to three things that C++ has that makes its code
hideous- the preprocessor, typedef, and operator overloading. All three of those are wholly unnecessary and mung C++ code
six ways to Sunday.
When C# was announced, I was excited because I'd heard its preprocessor was more restrictive. It is, in that it doesn't permit
macros. It still lets you do all sorts of whacky "conditional compiling" stuff, though, that makes code unreadable again.
file:///C|/330_new/330_new/general_java-I.htm (4 of 16) [2003-07-22 22:07:53]
General Java Questions I

Q: I can't manipulate inodes on my linux box ... in fact I can't even get real info about a file! Java is a bad hack and is for
kids who aren't sharp enough to do C++.
Answer: Think of Java in the same terms as COBOL and VB, and you've got the right idea. Start thinking of it as a replacement
for C++ and you're on the wrong track.
Don't expect this portable language to be a tool for low-level coding with hooks into the OS and hardware internals. It just
wasn't designed for that. It's an excellent *applications* language, not a *systems* language like C or assembler.
On the other hand, if any pesky Java programmers tell you that C++ is dead and that Java can do everything C++ does, and
more, you may howl with laugher and tell them to eat their JVM.
David Ehrens
Q: How do we exchange data between Java and JavaScript and vice-versa?
Answer: Public variable and methods of Java Applet are visible to a HTML document. So using JavaScript you can access the
public variables and public functions.
The syntax is:
var some_var = document.appletname.variable_name
With this you will get the value of the variable variable_name in your JavaScript variable some_var.
file:///C|/330_new/330_new/general_java-I.htm (5 of 16) [2003-07-22 22:07:53]
General Java Questions I

Q: Constructors and methods: are they the same?
I need a little help here...I have been teaching that constructors are not methods. This is for several reasons, but mainly
because JLS says "constructors are not members" and members are "classes, interfaces, fields, and methods."
So, now the rest of the staff is ganging up on me and making life a little nasty. They quote Deitel and Deitel, and Core Java
(which references "constructor methods") and who knows how many other books.
The one we are teaching in is loaded with so many errors that even though it calls constructors methods NOBODY will quote it
as an authority.
How can so many people call constructors methods if they aren't.
Okay. Are they or aren't they? I holding to the definition that they are not unless it is so common to call them that, that I will
have to change.
Answer: If you go by the JLS (Java Language Specification) and the Java API (and you should) , then no, constructors are not
methods. Consider that Class.getMethods() returns an array of Method instances and Class.getConstructors() returns an array
of Constructor instances, and Constructor and Method or not interchangeable (one is not derived from the other), but both
implement the Member interface. Seems to me that Java is going out of its way to differentiate them.
Besides, the mechanics of constructors are so different from the mechanics of methods, there seems to be no value to
considering one a member of the set of the other.
Now, as far as teaching the language goes:
+ return types
+ called by name
+ executed multiple times
+ super(...) or this(...) as first instructor (often implicit)
- everything else
I very much do not like trying to lump the two concepts together, especially in introductory courses. Conceptually they are very,
very different things.
A constructor is a unique element (even if there are several). It has the name of the class, its declaration is different, and it
doesn't have the same syntax as a method. It plays a unique role. You can call a method from a constructor, but you cannot
call a constructor from a method.
I say constructors are distinct from methods, and for students, blurring the distinction will lead to problems.
file:///C|/330_new/330_new/general_java-I.htm (6 of 16) [2003-07-22 22:07:53]
General Java Questions I
by Chuck McCorvey, Chris Wolfe,
-- Paul Lutus,

Q: I the see method getClass() in java.lang.Object. Do we need it? I know all my classes.
Answer: Exactly. If you know - you do not need it. But if you do not know then it helps you. For example if you get some object
and would like to instantiate it:
Object createNewInstOf(Object obj) {
return obj.getClass().newInstance();
Q:I know that a default constructor is being defined from line 6 to 9 (see below). But I don't quite understand the syntax:
this(blah, blah). Surely I know that "this" refers to the current object. But what on earth does "this(blah, blah, blah)" mean?
Would you please help explain in what kind of situation we need to use this kind of statement?
1. public class ThreadPool implements Runnable
2. { private final int DEFAULT_MINIMUM_SIZE=5;
3. private final int DEFAULT_MAXIMUM_SIZE=10;
4. private final int DEFAULT_RELEASE_DELAY=10*1000;
5. ...
6. public ThreadPool()
9. }
10. ......
11. }
file:///C|/330_new/330_new/general_java-I.htm (7 of 16) [2003-07-22 22:07:53]
General Java Questions I
Answer: Whenever you encounter the :
this(blah, blah)
syntax, it means that another constructor should be called first:
public class MyClass{
this(2,2); / / here you make a call to the other constructor
MyClass(int a, int b){
The point herecan be, that even if the user doesn't know which parameters to pass to MyClass(int, int) , she gets a default
constructor which indirectly gives default parameters.
Important notes :
-calling this(...) is very similar to calling super(...) .
-indeed, this(..) may only be used inside a constructor, and may only be placed as the first instruction in a constructor (all like
super(...) ).
note that super(...) will call some constructor from the parent class.
file:///C|/330_new/330_new/general_java-I.htm (8 of 16) [2003-07-22 22:07:53]
General Java Questions I
Q: Simple question: why constructor doesn't work in following example?
class Start {
public void Start() {
System.out.println("Konstruktor START");
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: Why we can not declare constructor as final?
Answer: The keyword final when dealing with methods means the method cannot be overridden.
Because constructors are never inherited and so will never have the opportunity to be overridden, final would have no meaning
to a constructor.
file:///C|/330_new/330_new/general_java-I.htm (9 of 16) [2003-07-22 22:07:53]
General Java Questions I
Q: In Java, does exist a function like sprintf in C?
Answer: a free Java version of fprintf(), printf() and sprintf() - hb.format
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 array 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 initialization 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 initialize the array with new Dog[100], which will create 100 elements in the array, all of them referencing null.
It is important to realize 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.
file:///C|/330_new/330_new/general_java-I.htm (10 of 16) [2003-07-22 22:07:53]
General Java Questions I
Q: How do I return more than one value using the return command?
Answer: You could make a new object/class that contains these two values and
return it. For example:
Define an object like this:
class MyObj {
public int myInt;
public double myDouble;
Then, in your method create one of these, set the corresponding values,
and return it.
MyObj yourMethod() {
MyObj obj = new MyObj()
obj.myInt = 20;
obj.myDouble = 1.0003
return obj;
Q: How do I use object serialization for an object that has other objects as data member? Do both the class need to
implement serialize?
How about static data?
class A{
class B{
public A a;
Answer: Both the object and all the object references it contains need to belong to classes that implement Serializable.
Static and transient fields are not serialized. For more, see,
file:///C|/330_new/330_new/general_java-I.htm (11 of 16) [2003-07-22 22:07:53]
General Java Questions I
Q: I recently learned a bit about "inner classes" but this seems to be different...
I'm a bit new to Java programming so bear with me. My employer bought a package of java graphics library programs to support
some chart applets we want to create. We have the source code. I'm trying to create a jar file with all the files I need to run the
applet. When I currently run the applet, the browser java tool says that it can't find "TextComponent$1.class".
I recently learned a bit about "inner classes" but this seems to be different. The "" file does contain some
inner classes, but not a class called "1". I'm confused.
Is this an inner class? Or is it something else. Any help would be appreciated. Thanks...
Answer: The TextComponent$1.class is the first anonymous class defined in Since nested (inner) classes are compiled to their own
.class file, they needed unique names. The javac compiler is just creating a
unique file name for an anonymous nested class.
What is the essential difference between an abstract class and an interface? What dictates the choice of one over the other?
Answer: You can only extend one class (abstract or not) whereas you can always implement one or more interfaces. Interfaces
are Java's way to support multiple inheritance.
Q: Is there a way to provide values for a Vector in the source code, analogous to array initializers?
Answer: The Vector class constuctors take no arguments other than Collection (since JDK 1.2), which is abstract, and since a
Vector is a structure whose size can change dynamically, it's contents can only be initialaized through member methods.
Mike Lundy
Q: Is there a collection object like the hashmap or hashtable that stores values in an ordered path? Vector does this but i
need the key/value functionality. hashmaps do not guarantee the order of the objects.
Answer: Take a look at java.util.TreeMap.
Red-Black tree based implementation of the SortedMap interface. This class guarantees that the map will be in ascending key
order, sorted according to the natural order for the key's class (see Comparable), or by the comparator provided at creation time,
depending on which constructor is used.
file:///C|/330_new/330_new/general_java-I.htm (12 of 16) [2003-07-22 22:07:53]
General Java Questions I
Note that this implementation is not synchronized. If multiple threads access a map concurrently, and at least one of the threads
modifies the map structurally, it must be synchronized externally.
Q: Most people asked why there is an error, but my question is why this is NOT an error...
Please take a look:
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 2: 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: How can I find the first dimension length of the 2-dimenstions array? I have use the array[].length but it does not work, how
can I solve this problem?
Answer: Java doesn't really have "multidimensional arrays", only arrays of arrays. So try: array[0].length and you will get this
Q: I guess what I'm asking is "Is java.util.Hashtable thread safe?"
It's been a while since I've used hashtables for anything significant, but I seem to recall the get() and put() methods being
The JavaDocs don't reflect this. They simply say that the class Hashtable is synchronized. What can I assume? If several
threads access the hashtable at the same time (assuming they are not modifying the same entry), the operations will succeed,
right? I guess what I'm asking is "Is java.util.Hashtable thread safe?"
file:///C|/330_new/330_new/general_java-I.htm (13 of 16) [2003-07-22 22:07:53]
General Java Questions I
Answer: That is right! It is recommendable, if you have questions like these, always look at source for the API, it's freely
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
ArrayList l = new ArrayList(); or
Vector l = new Vector();
recurseList( l );
Without any problem.
by Davide Bianchi
file:///C|/330_new/330_new/general_java-I.htm (14 of 16) [2003-07-22 22:07:53]
General Java Questions I
Q: What is better to use: array or vector?
Just wondering as I am using Vectors to store large amounts of objects from 50 to 4000 and each one has to be "looked at"
every time paint is called...
Just wondering if it would be better to use an array, list etc?
Answer 1: Since the Vector method uses an array for storage but has extra steps involved in getting an element, use an array for
fastest access.
WBB Java Cert mock exams
Answer 2: arrays are faster, vectors are more dynamic.
This should be evident just looking at the amount of code you need to traverse one versus the other. It might also be beneficial to
write a linkedlist class and use that. That way you have a dynamic container which has potential to be faster than a vector
(though still not as fast as an array). The problem with arrays is that if you need more space than the current size, you have to
hardcode their copying into a bigger array.
Conversely, if you never (or rarely) use the entire array, its a waste of space and memory.
The following are benchmark test results of vector vs. array (ran on a 200-Mhz Pentium w/ 96 Mbytes of memory and
Windows95 ):
Allocating vector elements: 17910 milliseconds
Allocating array elements: 4220 milliseconds
Accessing Vector elements: 18130 milliseconds
Accessing array elements: 10110 milliseconds
One other reason for vectors being slower that I did not mention above is that vector methods are synchronized, which creates a
performance bottleneck.
Hope this helps
Q: Would anyone know the performance issues regarding Vector's?
I am actually talking about resource pooling. I have objects that wait in a queue. It is a vector that keeps growing, as the queue
gets bigger.
Do Vectors have much performance hit? Is there a better way to implement vectors to get the best out of them? Or am I better of
file:///C|/330_new/330_new/general_java-I.htm (15 of 16) [2003-07-22 22:07:53]
General Java Questions I
creating a fixed size array?
Answer 1:
If you just want a LIFO or LILO queue, you may be better off with
LinkedList than with Vector, as then you'll never have to wait for the contents to be copied.
Vectors perform pretty well, but if you know (even roughly) how big you're going to need it to be, specifying that in the constructor
call can help.
How sure are you that this will be a performance bottleneck? Premature optimisation is the root of all evil...
The Vector class is thread-safe. By that I mean that there is no way to corrupt the internal representation of the data by
accessing the vector from more than one thread. However, it is still possible, very easy in fact, to use a vector in a way that is not
thread safe.
Consider this code:
for (int i = 0; i < vector.size(); i++) {
It looks safe, but there's a subtle flaw...
(c)1999, 2000, 2001, 2002, 2003 All rights reserved worldwide.
This document can not be changed, either in whole or in part
without the express written permission of the publisher.
All questions please