From: elharo@sunsite.unc.edu Newsgroups: comp.lang.java,alt.www.hotjava,alt.answers,comp.answers,news.answers Organization: Cafe Au Lait Followup-To: Poster Subject: comp.lang.java FAQ Archive-name: computer-lang/java-faq/part1 Posting-Frequency: weekly Last-modified: 1996/1/26 Version: 0.9.7 URL: http://sunsite.unc.edu/javafaq/javafaq.html
If you're reading the text version via Usenet, I do apologize that parts of it may be less intelligible than possible in HTML. Please refer to the HTML version at http://sunsite.unc.edu/javafaq/javafaq.html.
for loops have the same syntax in all four languages);
but it is not based on any of those languages, nor have efforts
been made to make it compatible with them.Java is sometimes referred to as C++ ++ --. The language was originally created because C++ proved inadequate for certain tasks. Since the designers were not burdened with compatibility with existing languages, they were able to learn from the experience and mistakes of previous object-oriented languages. They added a few things C++ doesn't have like garbage collection and multithreading; and they threw away C++ features that had proven to be better in theory than in practice like multiple inheritance and operator overloading. (There's still argument over whether they made the right choices. I tend to think they were correct to throw out operator overloading and possibly incorrect to throw out multiple inheritance. For now let's just say that neither choice is likely to be reviewed soon.)
Even more importantly Java was designed from the ground up to allow for secure execution of code across a network, even when the source of that code was untrusted and possibly malicious. This required the elimination of more features of C and C++. Most notably there are no pointers in Java. Java programs cannot (at least in theory) access arbitrary addresses in memory.
Furthermore Java was designed not only to be cross-platform in source form like C, but also in compiled binary form. Since this is frankly impossible across processor architectures, Java is compiled to an intermediate byte-code which is interpreted on the fly by the Java interpreter. Thus to port Java programs to a new platform all that is really needed is to port the interpreter.
Finally Java was designed to make it a lot easier to write bugfree code. Shipping C code has, on average, one bug per 55 lines of code. About half of these bugs are related to memory allocation and deallocation. Thus Java has a number of features to make bugs less common:
In 1989 Joy sold his Sun stock, invested heavily in Microsoft and moved out of mainstream Sun to Aspen, Colorado. By the early 90's Bill was getting tired of huge programs. He decided that he wanted to be able to write a 10,000 line program that made a difference. In late 1990 Bill wrote a paper called Further which outlined his pitch to Sun engineers that they should produce an object environment based on C++. Today Joy freely admits that C++ was too complicated and wasn't up to the job.
Around this time James Gosling (of emacs fame) had been working for several months on an SGML editor called "Imagination" using C++. The Oak language (now Java) grew out of Gosling's frustration with C++ on his "Imagination" project.
Patrick Naughton, then of Sun, now vice-president of technology at StarWave,
started the Green Project on December 5th, 1990.
Naughton defined the project as an effort to "do fewer things better".
That December he
recruited Gosling and Mike Sheridan to help start the project.
Joy showed
them his Further paper, and
work began on graphics and user
interface issues for several months in C.
In April of 1991 the Green Project (Naughton, Gosling and Sheridan)
settled on smart consumer electronics as the delivery platform,
and Gosling started working in earnest on Oak.
Gosling wrote the original
compiler in C; and Naughton, Gosling and Sheridan
wrote the runtime-interpreter, also in C. (The Green project
never wrote a single line of C++.) Oak was running its
first programs in August of 1991. Joy got his first demos of the system that winter, when
Gosling and Naugton went skiing at Joy's place in Aspen.
However the smart consumer electronics/remote control market didn't materialize so
in early 1993 the Green project
was redirected to focus on the settop box market. This market also proved to be more hype than
reality. However in 1994 it was realized that
the requirements for smart consumer electronics and settop box software (small, platform independent secure reliable code) were the same requirements for the nascent web.
For a third time the project was redirected, this time at the web.
Information in this section is primarily based on the first hand accounts
of Bill Joy and Patrick Naughton (which don't always agree). No doubt other
people have still different memories of what occurred. If you've got any more first hand information about what went on in the Green project I'd like to hear from you.
At the lowest level the
advantage of Java to the web is that it provides a secure, cross-platform
way for code to be executed. At a somewhat higher level Java adds several features to
existing web sites:
An IRIX port has mostly been completed by
A Linux port is rumored to have been mostly completed. See
http://java.blackdown.org/java-linux.html.
Sun is porting Java to MacOS 7.5, but it is unclear when this port will ship.
The latest rumors
say January, 1996. I suspect that's optimistic.
Natural Intelligence is working on Roaster,
a Java applet development environment which they claim will ship at MacWorld, San Francisco
in January.
Metrowerks has promised to
include Java applet support
in Code Warrior 9, due to be released in May, 1996.
IBM is porting Java to OS/2. See http://www.hursley.ibm.com/forums/java/Java_OS2.html
. IBM is also rumored to be porting Java to Windows 3.1. However, the
lack of threading in Windows 3.x makes
such a port extremely difficult.
The OSF is porting Java to Unixware,
HP/UX, Sony NEWS and Digital Unix.
The alpha 3 HP/UX (9.0 and 10.0) and Unixware 2.0 ports are available. See http://www.gr.osf.org:8001/projects/web/java/.
Various unsupported ports for Solaris x86 are available at
ftp://ftp.xm.com/pub/.
These ports don't contain the demo files or documentation.
You'll need to get those from the Sparc version.
Other ports are underway for Nextstep, SunOS 4.1,
the Amiga
and possibly other platforms.
In the past new versions of Java have
most often been made available first
for Solaris. If you have to have the latest
version as soon as it's released, or if you're developing "Bet your company"
applications with Java you should probably be running Solaris on a SparcStation.
Otherwise, if you just want to learn the language, you can get away with
an Intel based Windows 95 or NT machine with a lot of RAM.
This site has grown quite busy and is mirrored in several other places including
To subscribe to any or all of these lists send the word "subscribe"
in the BODY of a mail message to
listname-request@java.sun.com, where listname the mailing list
you want to subscribe to.
HyperMail archives
of these lists through sometime in late summer are also available.
When you send email to these lists never, never cross-post.
If you can't decide where your message properly belongs flip a coin. Please
don't send it to
every single list.
There is also a mailing list daling with
Java, Kerberos and DCE at java-kerberos@lists.stanford.edu.
To subscribe send email to majordomo@lists.stanford.edu with
the words "subscribe java-kerberos" in the BODY of your
mail message.
Presenting Java
is very heavy on the philosophy and purpose of Java and very light on
practical information. It certainly doesn't have very much information to help
you learn to program in Java. It may be a useful book to give your bosses
to explain why they should drop $10,000 on a Solaris box so you can play with Java.
According to
It's written for people with some experience in *a* programming language --
not real super-experts or rank beginners, but somewhere in the middle.
And, unlike many other Java books that will be published real soon now,
it will be up to date with the beta JDK (and will be up to date for
Netscape 2.0 and whatever other releases come out between now and then).
Based on the alpha2 and alpha3
releases.
For people who want to use applets but not necessarily program them.
I haven't seen this book myself yet, but the consensus of the net is that
this may well be the best book currently available on Java.
March 1996
For experienced programmers, from the fundamentals to advanced tips and tricks of the experts,
this book provides coverage of all Java
features and syntax as well as Visual Basic and C/C++ tips that compare
and contrast features of Java to those languages.
This book is a guide for programming in Java, from
learning the basics, to advanced features, and an API reference.
It includes a CDROM containing all the sample code from the book.
The Waite Group is also working on several other
Java books, but. I have no further information
about those books yet.
Que Books and O'Reilly are also rumored to have several Java books in development,
but I have no information about them at this time.
To add to or correct this list please send complete details to me at elharo@sunsite.unc.edu. If you'd really like to be helpful look at the HTML source of this document and send the corrections to me as a
completely formatted listing. All extraneous hype will be removed.
Sun Educational Services offers a 3-day hands-on course, SL-230
Basic Java Programming. In November they will also offer a 2-day Advanced Java
Programming, SL-270. Call 1-800-422-8020 for dates, times and locations.
These courses fill up very fast so register early.
Basic Java Programming is a three-day course
that introduces the Java language and Java
applets. It covers :
Advanced Java Programming is a two-day course
designed to cover the Java language in greater detail. This is a
project course, where you will design your own "point-of-sale"
application. This course covers:
This course is an intensive one-day examination of:
Call 800-433-4224 or
email sunsoft@tbsmkt.com
for dates and locations.
Here are the detailed data types:
Like all numeric types floats may be cast into other numeric types (byte, short, long, int, double). When lossy casts to integer types are done (e.g. float to short) the fractional part is truncated and the
conversion is done modulo the length of the smaller type.
Chars are not the same as bytes, ints, shorts or Strings.
Chars may not be cast into any other type nor may those types be cast to chars.
However comments that begin with a
Superclasses of a class are indicated with the
Features removed that make Java easier to read and understand than C++
include #defines, typedefs, operator overloading, enums, unions and structs.
The main feature removed to make Java safer and more robust than C++ is pointer arithmetic.
Other features removed include global variables, standalone functions (everything is a method),
friend functions (Everything in a package is a friend of everything else in a package.)
and virtual functions. (More accurately every function is virtual.)
A number of features have been added to Java to make it safer including true arrays with
bounds checking, garbage collection, concurrency, interfaces (from Objective C) and packages. There is no need to explicitly allocate or
free memory in Java.
Long answer: Object variables in Java are all references. A reference would be a pointer in any other language. The main difference is that you can't do pointer arithmetic on references. Therefore wherever you'd use a pointer to an object in C++, in Java you should just use the object itself.
On the other hand the primitive data types (int, float, double, char, byte, short, long and boolean) are not references. If you want to get a reference to one of these you need to wrap it in a class first. Java provides ready-made type-wrapper classes for Integer, Double, Float, and Long. For the others you should roll your own.
See the Java class API documents for details of the syntax for these methods.
Next use the
StringTokenizer
class in java.util to split the String into tokens.
By default StringTokenizer splits on white space (spaces,tabs, carriage returns and newlines)
but that is user definable.
Within an application, however, file access is straight-forward. There are several ways but here is a simple example using formatted output streams:
You should also learn about DataOutputStreams and the
Several people have written to me with apparently different methods that
involve deep, dark hacks to the java interpreter, dump and undump and
other tricks. However so far I don't understand any of this.
An abstract class cannot be instantiated. Only its subclasses can be instantiated.
For applets on the same page Arthur van Hoff has provided this example:
Applet 1:
To prevent this, you need to create an Image member of your applet.
Then override the
Extensions are planned for the class library though. In particular Sun is working on extensions
for 3D, multimedia and multicasting.
It's also possible to make a variable final to get the effect of C++'s const statement
or some uses of C's #define, e.g.
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
Instead if you need to do clipping,
create separate offscreen Images
for each clipping region.
Each Image should be the size of the clipping region you desire. Draw into
those offScreen Images, and then copy them onto the appropriate
section of the of your applet window using java.awt.Graphics.drawImage().
Some coordinate conversion will
almost certainly be necessary.
If the background image isn't a simple color then you'll first need to
copy the appropriate part of that image to your offscreen clipping
Image. You can do this by drawing your background Image into your
offscreen region with Graphics.drawImage and a suitable shifting of
coordinates.
This all works for rectangular regions only since all Images are
rectangular. More complicated geometries can be faked if
all but one section contains only simple colors.
Unlike most random functions in other libraries the
The cookbook approach is simple. Add the following three private member variables to your applet and the public update method. Flicker will magically disappear.
The CLASS_PATH is an environment variable that defines where Java looks for these
imported classes. If the CLASS_PATH isn't set properly every program written in Java
won't be able to run.
Thus when you import java.applet.Applet java tries to find the relevant code in
$CLASS_PATH/java/applet/Applet
If there are multiple directories in $CLASS_PATH then each of them will be searched in order from left to right.
In Netscape, at least in 2.0b6, you should make sure that the first directory in CLASS_PATH.
is the directory that contains netscape's class files (The defaults are /usr/local/netscape/java/classes on Unix and C:\NETSCAPE\NAVIGATOR\Program\java\classes in Windows.)
JDK CLASS_PATH.
Setting the class path.
If the class is part of a package then it needs to be in the appropriate subpath
of the CLASS_PATH directory. For instance if your class is part of package foo.bar,
then it should be in $CLASS_PATH/foo/bar.
You must use the new operator like:
In Netscape you don't even get the keys to the cage so you can't let the applets out into your system even if you wanted to. With HotJava it is possible to give your applets more access to the system. However they still can't do anything a C program could do.
Specifically a Java applet cannot write anything to a hard drive without permission. It cannot write directly to memory, and it cannot introduce a virus into your system. A Java applet can use a lot of your CPU time though not 100% of it. It cannot crash your system (though the Java enabled browser could).
Finally an applet can display pictures or text or play sounds which the
user may find annoying or offensive, but this hardly qualifies as a security flaw and is not unique to Java enabled browsers.
Jim Friskel reports that there is a new prototype of a Java/HTML IDE for Windows 95 at http://www.inch.com/~friske
It contains:
Borland, Metrowerks, and Natural Intelligence have all announced various levels of vapor.
Natural Intelligence's
Roaster is a PowerMac hosted applet development environment. It
has been designed from the public specs with no help from Sun.
Metrowerks plans on adding Java applet support to Code Warrior 9 for the Mac, due in May, 1996. Metrowerks has licensed Sun's source code.
Sun has announced that they will release a
payware IDE currently referred to as "Workshop for Java"
in the first half of 1996. Early access (i.e. beta testing) is scheduled to begin in
November. Call 1-800-SUNSOFT or keep your eye on
Sun's Developer
Web pages for details.
Workshop for Java is supposed to be similar to Sun's existing Workshop products
for Fortran and C++. However it is written entirely in Java and will
hopefully be available across all platforms simultaneously. Workshop for Java
is composed of three parts:
Sometime after the first half of 1996 you should see tools for visual development as in
Visual Basic, a Tool API, a team development environment and a dynamic optimizer (i.e. a
compiler that produces machine code.)
The Java source code is freely available for non-commercial use though a license must be signed.
(I do not know what qualifies as commercial versus non-commercial use).
If you want to license the Java source code for commercial use you will
need to pay $125,000 for the first platform, $25,000 per additional platform and
a $2/unit royalty. Annual upgrades are $50,000 plus $5,000 for each additional platform.
Complete details are at
http://java.sun.com/license.html.
Furthermore whether your product is commercial or non-commercial
you may not use the trademark "Java" to describe your product
unless you pass an as yet unreleased verification and test suite.
Why am I taking on such a Herculean task? It's often said that you never
really understand a subject until you teach it. I'm going to endeavor
to learn Java and understand it by teaching it. The result should be
interesting at least. Since I'm very new to Java and clearly do not
yet understand the language, I'll have a perspective on the issues that should be
helpful to newcomers.
Are there mistakes here? Absolutely. I hope people here and elsewhere
will correct me gently and help lead me on the path to true Java
enlightenment when I err. And if they aren't so gentle, well, I've developed a
pretty thick skin after five years of Usenet.
My companion tutorial in how
to write Java is going to reflect the programs I'm actually writing.
As I learn to do a Hello World program, I'll write about Hello World.
(OK, I've actually already gotten beyond Hello World but not much
beyond.) How fast the FAQ list grows will depend in large part on how fast my
skills grow. You'll get to watch me learn, make mistakes, correct
mistakes and so on.
There may be an advantage to this approach. People who want to learn
Java will be coming from almost identical places as me. I always
hate having to write down or talk down to people and I don't do it
very well. Similarly I find it frustrating to try to communicate with
people who are way beyond me (as obviously some people on the Java mailing lists
are). Right now I am at the level of the lowest of the low. This
means that I can write for people without much prior experience
without boring myself or, hopefully, my audience, to tears.
Finally I'll emphasize that I'm not trying to prevent anyone else or
any other team of people from taking on a similar project. I hope
someone does. I'll probably learn from what they do, and they'll learn from
what I do, even if it's only to learn the sorts of things novices are
confused about. And of course not everyone shares the same learning
style so while some people may enjoy my approach to Java I am sure
others will find it dense, incoherent and ultimately
incomprehensible. More choices are better.
Ultimately I'm doing this because I think Java is very, very cool and
I am convinced I need to learn it sooner rather than later. I think
this project will propel my Java knowledge forward, and if it does
that I'll consider my project a success. If I can help a few other
lost sould to climb out of the pit with me at the same time, so much
the better.
However I do not allow the FAQ list, either the text or HTML version, to be placed on any web sites but my own. Mirroring HTML files is a fundamentally bad idea that is at cross-purposes with the design of the web. Among other problems it makes maintaining up-to-date copies phenomenally difficult. If you think this file would be a useful addition to your web site, then link to it. That's the way the web is designed. Not all information needs to reside in one central location. No permission is needed to link to this or any other of my HTML files. In fact I'd prefer it if you'd not ask me, since then I don't have to spend time answering you.
Although there's more reason to want to translate the document rather than merely mirror it, I regret that I do not have the time or resources to support any translation efforts. This document will be available in English only for the foreseeable future.
Doesn't the World Wide Web have something to do with this?
Not necessarily. Java is a programming language. When work began on what has
become Java, the World Wide Web was just getting started at CERN and Mosaic
wasn't even a glint in Marc Andreesen's eye. The original
use of the Java language (settop boxes) required security and the ability
to execute code from untrusted hosts. It turns out these are virtually the
same requirements for allowing people to download and run programs from the Web.
No other language has the built-in security of Java. The key here are
the security features. The object-oriented nature of Java is secondary, and
mainly reflects the preferences and prejudices of the developers who set
out to write a secure language. The C-like syntax of the language is even
less important to the problem.
What Platforms does Java run on?
Java is currently available for Sparc Solaris, Windows NT for Intel, and Windows 95.Do I need to know C++ to learn Java?
No. Java is in fact a much easier language to learn than C++. The only problem is that most tutorials, books and classes about Java are in a very preliminary state; and are probably not yet ready for consumption by people who know nothing about programming. However there is a flood of Java resources coming in the next few months which should be helpful. What other Java Resources are available?
Web Sites
The key site for Java information is http://www.javasoft.com/.
This is Sun's official site for Java, and contains the latest
published version of all official Java information. As of this writing this is the only
web site with any worthwhile information about the details of Java (including this one).
Here are the most important pages at that site:
http://www.yahoo.com/Computers/Languages/Java/.
http://www.yahoo.com/Computers_and_Internet/Internet/World_Wide_Web/Browsers/HotJava.
Mailing Lists
There are several Java related mailing lists. Complete details are available
at http://java.sun.com/mail.html.
Digest versions of java-interest, java-porting and hotjava-interest are available
as java-interest-digest, java-porting-digest and hotjava-interest-digest.Newsgroups
Books
According to
I'm still writing it, so the table of contents is fluctuating
quite a bit, BUT, it's organized into three weeks:
I haven't seen this book myself yet, but the consensus of the net is that
it's a hack to make a quick buck from the popularity of Java.
This book provides a variety of applets, such as text manipulation,
sound, animation, etc., and shows users how to easily plug them into
existing web pages. Easy directions on how to customize these applets
to suit specific needs. Includes CD-ROM.
Java is presented through examples, showing the development of Java
applets from simple to complex. Explains by example the key elements
of the language, such as classes/interfaces, memory management, and
distributed computing support. Appendices include complete code
samples. Includes CD-ROM.
This book provides an introduction to Java and object-oriented
programming, from the author of Expert C Programming: Deep C
Secrets. Just Java covers all the basics and describes the elements
of window and network programming in Java. Includes CD-ROM.
These books appear to be based on documentation already available at the Java web site though they will be updated to cover the then current version of Java and the Java API. Additional volumes will be added over time. They will be published by Addison-Wesley.
See http://www.aw.com/cp/javaseries.htmlTraining
un sponsored a free seminar series on Java in several California locations including
Mountainview, Pleasanton and Sacramento. Details including class notes are available
at http://www.sunsales.com/java/.
It does not appear these classes will be offered again.
People who took the first iteration of Basic Java Programming hated it. The general feeling was that the material covered could have easily been completed in half a day or less. Even those students who had never programmed before felt this course was at far too low a level. The students were invited back to take the advanced course at no charge. Later reports have been somewhat more positive.
Sun has recently announced some one-day Developer Camps.
These are geared toward techies, not designers or salespeople.
According to Sun prorpaganda you will spend just one day with
SunSoft experts in Java and you will be able to:
Prerequisites allegedly
include experience writing network-based applications with object-
oriented software languages, and familiarity with the
current problems in network performance and security.
Cost is $225.00 per person. Full payment is required to reserve space.
The fee includes all class materials, special offers on tools
for Java developers, and lunch.
Java for C++ programmers
In the large Java looks like Smalltalk. In the small it looks like C.
The syntax of Java is deliberately similar to C and C++. If you know C++ you already know
large chunks of Java. Here, in brief, is Java syntax for C programmers:Data Types
Java's primitive data types are very similar to those of C. Boolean,
String and true arrays have been added. However the implementation of the data types has been
substantially cleaned up in several ways.
int) Java specifies
everything.
true and false only.true and false are defined constants of the language and are not the same as True and False, TRUE and FALSE, zero and nonzero, 1 and 0 or any other numeric value. Booleans may not be cast into any other type of variable nor may any other variable be cast into a boolean.sizeof isn't necessary in Java because all sizes are precisely
defined. i.e. an int is always 4 bytes.
This may not seem to be adequate when dealing with objects that
aren't base data types. However even if you did know the size of
a particular object, you couldn't do anything with it anyway.
The Object class does not contain a copy or serialize method
so there's you need to know how many bytes a particular object uses.
This is part of Java separating
you from physical memory.Control Statements
Java contains if, else, for, while, do while and switch statements.
The syntax is identical to C's. However all condition tests must return boolean values. Since assignment and arithmetic statements
do not return a boolean value,
some of the more obfuscated condition tests in C are prohibited.Command Line Arguments
Command line arguments are like C's except that argv has become a string array called args and args[0] is the first command line argument,
not the name of the program. The other arguments are all shifted one to the left from
where they'd be in C or C++.Comments
Java supports both the /* This is a comment */ comment from C and the
// This is a C++ comment
comment from C++. /**
are treated specially by the compiler.
These comments should only
be used before a declaration. They indicate that the comment should be included in automatically generated documentation for that declaration. Classes
Java does not support multiple inheritance.extends keyword rather than with
a :.Methods
Methods must be defined within the block that defines the class they belong to,
not outside of it as they commonly are in C++.Concurrency
Java is internally multithreaded. The model includes threads, synchronization,
and monitors.How is Java unlike C++?
Two classes of language features have been removed from C++ to make it Java. These
are those language features which make C++ unsafe and those which make it hard to read.How Do I...
Make a linked list without pointers?
Short answer: 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. Read Data From A File?
There are a number of ways to read data from a file. If you're reading a file as raw binary data, you open a file using a FileInputStream(String) constructor and use one of the various read() methods to read the data into an array of bytes. For example the following program reads raw data from a file specified on the command line. It then writes the same data to the standard output.
On the other hand if you're reading a text file you'll probably want to use a DataInputStream which gives you a readLine() method that returns successive lines of the file as Java Strings. You can then process each String as you see fit. import java.io.*;
class ReadRawData {
public static void main (String args[]) {
boolean done = false;
byte b[] = new byte[1024];
int num_bytes = 0;
FileInputStream fin = null;
try {
fin = new FileInputStream(args[0]);
}
catch(ArrayIndexOutOfBoundsException e) {
System.out.println("You have to give me the name of a file to open.");
System.exit(0);
}
catch (FileNotFoundException e) {
System.out.println("Could not open input file " + args[0]);
System.exit(0);
}
catch(IOException e) {
System.out.println("Error while opening input file" + args[0]);
System.exit(0);
}
catch (Exception e) {
System.out.println("Unexpected exception: " + e);
System.exit(0);
}
try {
num_bytes = fin.read(b);
}
catch(IOException e) {
System.out.println("Finished Reading: " + e);
done = true;
}
catch (Exception e) {
System.out.println("Unexpected exception: " + e);
System.exit(0);
}
while(!done) {
System.out.write(b, 0, num_bytes);
try {
num_bytes = fin.read(b);
}
catch(IOException e) {
System.out.println("Finished Reading: " + e);
done = true;
}
catch (Exception e) {
System.out.println("Unexpected exception: " + e);
System.exit(0);
}
if (num_bytes == -1) done = true;
} // end while
} // end main
} // end ReadRawData
This code emulates the Unix "cat" command. Given a series of filenames on the command line it concatenates the files onto the standard output. Since this program didn't work the first few times I wrote it, I even tossed in some error checking and exception handling via try and catch.// Implement the Unix cat utility in java
import java.io.*;
class cat {
public static void main (String args[]) {
String thisLine;
//Loop across the arguments
for (int i=0; i < args.length; i++) {
//Open the file for reading
try {
FileInputStream fin = new FileInputStream(args[i]);
// now turn the FileInputStream into a TextFileStream
try {
DataInputStream myInput = new DataInputStream(fin);
try {
while ((thisLine = myInput.readLine()) != null) { // while loop begins here
System.out.println(thisLine);
} // while loop ends here
}
catch (Exception e) {
System.out.println("Error: " + e);
}
} // end try
catch (Exception e) {
System.out.println("Error: " + e);
}
} // end try
catch (Exception e) {
System.out.println("failed to open file " + args[i]);
System.out.println("Error: " + e);
}
} // for ends here
} // main ends here
}How do I scanf in Java?
Java has no exact equivalent to C's scanf, fscanf and sscanf functions.
Roughly equivalent functionality is scattered across several classes though.
You first read an input line into a string
using DataInputStream.readline()
as discussed in the previous question.
prints the following output:
import java.util.StringTokenizer;
class STTest {
public static void main(String args[]) {
String s = "9 23 45.4 56.7";
StringTokenizer st = new StringTokenizer(s);
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
}
}
9
23
45.4
56.7
Finally you convert these tokens into numbers using the
type wrapper classes as described in the next question.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:
For reasons that are unclear there are no equivalent Short and Byte classes.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);
}
}How do I write data to a file?
You should only assume you'll be able to write to a file from an application. Although it may be possible to write data into a file from an applet if the browser viewing the applet is HotJava, I haven't been able to make this happen. From within Netscape there is no way for an applet to write to a file on the local hard drive.
There are a number of other things to note about writing data to a file. This program creates or opens a file called "test.out" in the same directory as the running program. However you could pass it a full pathname to a file in a different directory instead.import java.io.*;
class PrintToAFile {
public static void main (String args[]) {
//First open the file you want to write into
try {
FileOutputStream fout = new FileOutputStream("test.out");
// now convert the FileOutputStream into a PrintStream
PrintStream myOutput = new PrintStream(fout);
// Now you're able to use println statements just as if you were using System.out.println
// to write to the terminal
myOutput.println("Hello There!");
myOutput.println(1 + " + " + 1 + " = " + (1+1));
}
catch (IOException e) {
System.out.println("Error opening file: " + e);
System.exit(1);
}
} // main ends here
}write()
method when you get a chance.
DataOutputStreams and DataInputStreams are used for moving data between Java programs in a portable way. The various incarnations of the write() method are used for writing and reading arbitrary byte streams. What we've demonstrated here is more suitable for human consumption. How Do I Call C Code from Java?
First of all for security reasons you can only call external code from an application.
You cannot call external code from an applet. (Otherwise all the security would go out
the window.) Furthermore all code you write in this way will be non-portable. If these aren't problems for you, check out javah in the beta developer's kit.How Do I Call Java from C?
Since Java is not as of yet a true compiled language, the only way I know
to call Java code from C is
by using the system() call (or your OS's equivalent) to execute the java interpreter with appropriate command line arguments.How do you do multiple inheritance?
Use interfaces.Alright, what's an interface?
An interface is an idea taken from Objective C. It
describes the public methods that a class implements and their
calling conventions without saying anything about how those methods are implemented.
It is the responsibility of each class that implements an interface to provide code to
handle the cases where the methods of the interface are called. What are abstract classes?
Abstract classes are classes which leave one or more methods to be implemented
by subclasses. These methods are declared but are not implemented. Each subclass
of an abstract class must override the abstract methods.Can I write objects to and read objects from a file or other stream?
In theory yes, but once again
all the coding is up to you. There is no general method for doing this.
The problem is made harder by Java's security features that don't let you forge arbitrary
byte streams into objects.How do I call the native API from Java?
You can do this only in an application, not in an applet. You will need to write some
intermediary code in C or another traditional language and call your C code from Java.Programming Applets
Can applets communicate with each other?
At this point in time applets may communicate with other applets on the same page.
As yet there is no way for applets on different pages to communicate directly.
This may be added at some point in the future.
Applet 2: import java.awt.*;
public class Applet1 extends java.applet.Applet {
public boolean handleEvent(Event evt) {
Applet2 buddy = (Applet2)getAppletContext().getApplet("buddy");
return (buddy != null) ? buddy.handleEvent(evt) : false;
}
}
HTML:
import java.awt.*;
public class Applet2 extends java.applet.Applet {
String str = "";
public boolean handleEvent(Event evt) {
str = evt.toString();
repaint();
return true;
}
public void paint(Graphics g) {
g.drawString(str, 0, size().height * 2 / 3);
}
}
It is conceivable to have applets that talk to a server somewhere on the Internet and store any
data that needs to be serialized there. Then, when another applet needs this data, it could
connect to this same server. Implementing this is non-trivial. However there is currently no secure way to store this data
on the client.
<HTML>
<HEAD>
</HEAD>
<BODY>
<applet code=Applet1.class width=100 height=100></applet>
<applet code=Applet2.class width=400 height=30 name=buddy></applet>
</BODY>
</HTML>
Can applets launch programs on the server?
Yes, using cgi. Any other implementation would be server dependent. Of course this requires a
lot of coding and is non-trivial. A simple way to do this is not built into Java because
that would require a special server. One of Java's strengths is that it is httpd server
independent.Can applet's launch programs on the client?
Absolutely not. This would be a security hole big enough to walk three herds of elephants,
two marching bands and at least one quarter of the people laid off by IBM through.Can I record audio from an applet?
This is what is known as "a third-party opportunity". In other words not this year and probably not next year either. This would make a neat Java plug-in if anyone cares to write one in C.How can I avoid blinking and flashing in an applet?
Flashing applets are caused by the invalidation of a section of the applet's
screen space. The affected area is erased and then redrawn. update() method
with one that draws to this
(offscreen) Image. Finally, in your paint() method, do nothing but use
Graphics.drawImage() to copy this offscreen bitmap onto the screen. All other
drawing takes place offscreen in the update() method.Language Issues
Why doesn't Java include insert your favorite feature here
The Java language has been extensively debated and argued about within Sun.
Almost every language construct of existing languages has already been considered
for inclusion in Java.
While there may still be room for addition, it is very unlikely that your pet feature
will be added to the language spec if it isn't already there. In a couple of
years parameterized types may be added to the language. Otherwise the spec is pretty
much frozen except for minor changes and bug fixes.Is Java CORBA compliant?
Not yet. In the future Java and CORBA will get a lot closer through NEO.Can I cast an int to an Integer? a float to a Float?
No, in general you cannot promote a base data type
like int or float to an
Object such as an Integer or a Float. However the proper way to do this isn't very
hard. Instead doint x = 5;
myInteger = new Integer(x);How do I version a class?
You don't. There is no support for versioning classes in Java nor is there
likely to be in the near future. A solution to this problem will probably
have to wait for the next object oriented language which will learn from
Java's mistakes as Java has learned from C++'s.Why isn't there operator overloading?
Because C++ has proven by example that operator overloading makes code
almost impossible to maintain. In fact there very nearly wasn't even method overloading
in Java but it was thought that this was too useful for some very basic
methods like print().
Note that some of the classes like DataOutputStream have unoverloaded
methods like writeInt() and writeByte().Does Java pass function arguments by value or by reference?
Objects, including arrays and Strings are passed by reference. Other data types are passed by value. What does it mean that a class 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 small optimizations.public static final int myVar = 0
What does it mean that a method or variable 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 object changes for all
instances of that object.System.out.println() work.Are there parameterized types?
Not in the first iteration of the language. However this is being seriously
considered for future versions.How does garbage collection work?
Current implementations of
Java uses a mark and sweep garbage collector. Reference counting is not used.
Thus circular linked lists do not lead to memory leaks.Perform
Sorry Smalltalkers. There's no equivalent for perform in Java. Perform
would probably be a security hole. There are workarounds for some things you might want to do
using interfaces.
What are peer "classes"?
Peer classes exist mainly for the convenience of the people who wrote
the Java environment. They help in translating between the awt user interface and
the native (Windows, OpenWindows, Mac etc.) interfaces. Unless you're porting Java to
a new platform you shouldn't have to use them.The Java Class Library
java.awt
What Does AWT Stand For?
So far I've heard it claimed that AWT stands for:
I do not know which if any of these are correct.
Clipping
java.awt.Graphics.clipRect(int, int, int, int)
and related methods are hopelessly flawed,
at least as of the second beta. Ignore them completely. java.net
How do I convert a numeric IP address like 199.1.32.90 into a hostname like star.blackstar.com?
Unfortunately due to an unintended side effect (i.e. a bug) in Java's caching
of IP addresses and hostnames, you can't convert numeric IP addresses into hostnames
as of beta 2. This may be fixed in a
future release.java.util
How random is Random()?
It's good enough for games. I wouldn't use it for cryptography.Math.random() method seeds itself
with the current time in milliseconds. Thus you do not need to seed it explicitly at the start of your program. If you require a non-random Random() for test purposes or you need more randomness than the current time in milliseconds can provide, then you can use java.util.Random() which has a constructor that lets you specify a seed.Common Errors and Problems
How Can I Avoid Flicker in an Applet?
The key to fixing flicker is realizing that the screen isn't actually painted in the paint() method. The pixels get put on the screen in the update() method which most applets don't overrride. However by overriding the update method you can do all your painting in an offscreen Image and then just copy the final Image onto the screen with no visible flicker.
private Image offScreenImage;
private Dimension offScreenSize;
private Graphics offScreenGraphics;
public final synchronized void update (Graphics g) {
Dimension d = size();
if((offScreenImage == null) || (d.width != offScreenSize.width) || (d.height != offScreenSize.height)) {
offScreenImage = createImage(d.width, d.height);
offScreenSize = d;
offScreenGraphics = offScreenImage.getGraphics();
}
paint(offScreenGraphics);
g.drawImage(offScreenImage, 0, 0, null);
}
Can you explain CLASS_PATH?
Most Java applets and applications aren't self-contained. They need to get access
to other classes to do their work. For instance when you call System.out.println()
java needs to know where to look to find the file that includes the System package.Netscape gives me "Applet Not Initialized Error"
Make sure your CLASS_PATH environment variable is set to point to the directory containing
the class file. Under Unix this is done with the command setenv CLASS_PATH my_class_directory
Under Windows this is set by adding the
line SET CLASSPATH=C:\JDK\JAVA\CLASSES;
to your autoexec.bat file. You can of course point it at a different directory,
but then your classes should reside in that directory.Other Netscape Problems
As of version 2.0b6 Netscape has many problems handling Java applets.In no
particular order they are:
I keep getting access privilege violations, " Java tried to read file foo.class in directory bar."
This happens when you try to load a class from a local hard disk instead of a server, the
class is not a subclass of Applet, and the
directory where the class resides is not in the HotJava read path. The solution is to move the
class file into a directory in the HotJava read path. On Unix one such directory is ~/public_html/classes (where ~ is your home directory). Alternatively you can change the HOT_JAVA_READPATH environment variable to point to the directory containing your classes directory.Javac keeps insisting that it can't find the right constructor function in my class, but I'm sure it's in a file I imported. Why is it even looking in my class instead of the imported file?
You cannot construct instances of a class on the fly using syntax likeSystem.out.println(Double(0.56).toString());
In other words, constructors are only called after a new operator.Double myDouble = new Double(0.56);
System.out.println(myDouble.toString());Security
System Level Security
On a system level Java applets live in a cage. They can do pretty much anything they want inside their cage but they can't get outside the cage and do damage unless you unlock the door to the cage. Even then they wear shackles that prevent them from doing things like writing to arbitrary addresses in memory.User Level Security
A Java applet can trick the user into doing something stupid such as revealing their root password though their are efforts to avoid this. A Java applet can also send this information back to the applet's server.Tools
IDE
Symantec has released Espresso, an applet
development add-on for their C++ compiler for Windows 95 and NT. It is freely
available from their web site, but it requires the payware Symantec C++. It
includes a source code editor and a class browser.
At least initially Workshop for Java won't contain any sort of revision control system
though of course SCCS works as well with Java files as anything else. An FCS system
for Java may be announced in the first half of 1996.Debugger
A preliminary jdb is available with the beta.Editors
An emacs mode for Java is available at ftp://ftp.javasoft.com/pub/java/contrib/emacs/
YACC grammar?
Scott Hudson has written an LALR grammar for Java. You can ftp it from
ftp://ftp.cc.gatech.edu/people/hudson/java_grammar/
Profilers
javaprofThe Java Virtual Machine and Byte Codes
The most recent Java Class File / Java Virtual Machine specs are at
http://java.sun.com/doc/vmspec/html/vmspec-1.htmlCan I program directly in byte code?
In theory, yes, you can. There are no tools to help you do so.
You need to use a tool that lets you write bytes to a file
like Norton Disk Editor.
The Java interpreter will check your byte codes to make sure they
don't violate security. If you write security violating byte codes
the interpreter won't run them.Optimizing Java
Legal Issues
Some portions of Java and HotJava are neither in the public domain nor
copylefted. However no license is required to write and distribute most Java
applications and applets. Nor is any license from Sun is required to distribute
the Java or HotJava in binary form.FAQ's about the FAQ
Who is this Elliotte guy, and just what qualified him to write a Java FAQ anyway?
He was willing to do it. Seriously months on the Java mailing lists made
it obvious that a FAQ was needed and since none seemed to be forthcoming
from those more qualified than I, I boldly and with a complete disregard for
my absolute lack of qualifications stepped forward and volunteered.
I do have some hope that my previous experience with FAQ lists, the world wide web
and a variety of programming languages may somehow cover up the fact that
I have no idea what I'm doing. You've read the FAQ list by now. Did I succeed?Why don't you include X in your FAQ?
Please do make suggestions about topics for FAQ list inclusion.
You can email them to elharo@sunsite.unc.edu.
I do follow the java-interest mailing list religiously, and have
a pretty good idea of what's discussed there. However I don't necessarily
understand all the conversations that take place on it. I am not a Java genius,
at least not yet, and a FAQ is far more likely to be included here if you
propose not only a question but also an answer. Please be as clear and explicit
with your answer as possible so that even someone with as small a brain as I
can understand it. Thank you.This is really cool. Can I republish or translate it?
This FAQ list and its entire contents are copyright 1995 by Elliotte Rusty Harold.
If you have specific desires to republish it in whole or part contact me at elharo@sunsite.unc.edu and tell me
exactly what you want to
do. I'm generally receptive to non-profits that want to make it available to the public
at no charge and to anyone who's willing to make reasonable payment arrangments.
Copyright 1995
elharo@sunsite.unc.edu
Last Modified January 26, 1996