Dear customers, please be informed that our shopping cart will be unavailable between August 21 and September 1, 2014, as we will be making some changes to serve you better. To minimise any possible delivery disruption, we encourage you to make your purchases before August 21. We appreciate your understanding and apologise for any inconvenience.

Wiley
Wiley.com
Print this page Share

Beginning Java 2, SDK 1.4 Edition

ISBN: 978-0-7645-4365-4
1200 pages
March 2002
Beginning Java 2, SDK 1.4 Edition (0764543652) cover image
What is this book about?

The Java language has been growing from strength to strength since its inception in 1995. It has since proved to be both powerful and extraordinarily easy to learn and use. This is what makes it ideal for the beginner. With dramatic changes to the handling of files, and the introduction of native support for XML, Java has been updated to work faster and to be current with the incredible rise of XML as a medium for communicating data.

This edition of the Beginning Java books outlines everything the beginning programmer needs to know to program with the Java programming language and the 1.4 Java Developer Kit (JDK). With the release of JDK 1.4, programmers can look forward to the most stable edition yet, and even better performance than was available previously.

Over the course of the book, you will build an example application called Sketcher — a simple drawing tool — that teaches you how to build an interactive user interface with Java, how to save and open files, how to use color, and how to respond to user input.

What does this book cover?

  • Teaches the Java language from scratch
  • Object-oriented Programming in Java
  • Handling errors and exceptions in applications
  • Manipulating data and files
  • Concurrent programming and threads
  • A comprehensive introduction to Swing, the graphical user interface API for Java
  • Printing in Java
  • An introduction to XML

Who is this book for?

Ivor's inimitable style has proved to be a hit with nearly half a million people with its easy to learn approach and the many useful examples. Regularly voted the most popular Java programming book, this book teaches Java from scratch and assumes no previous knowledge. It is also suitable for those who have got some programming experience, especially C or C++, which will make learning easier.

See More
Introduction.

Chapter 1: Introducing Java.

Chapter 2: Programs, Data, Variables and Calculation.

Chapter 3: Loops and Logic.

Chapter 4: Arrays and Strings.

Chapter 5: Defining Classes.

Chapter 6: Extending Classes and Inheritance.

Chapter 7: Exceptions.

Chapter 8: Understanding Streams.

Chapter 9: Accessing Files and Directories.

Chapter 10: Writing Files.

Chapter 11: Reading Files.

Chapter 12: Serializing Objects.

Chapter 13: Collection Classes.

Chapter 14: A Collection of Useful Classes.

Chapter 15: Threads.

Chapter 16: Creating Windows.

Chapter 17: Handling Events.

Chapter 18: Drawing in a Window.

Chapter 19: Extending the GUI.

Chapter 20: Filing and Printing Documents.

Chapter 21: Java and XML.

Chapter 22: Creating and Modifying XML Documents.

Appendix A: Keywords.

Appendix B: Computer Arithmetic.

See More
Ivor Horton has extensive experience of programming and large-scale systems implementation in a wide range of industrial environments. He has in-depth knowledge and experience of production scheduling and online control systems, computer-aided design and manufacturing systems, as well diverse engineering and scientific applications. He's also taught programming in a variety of languages to engineering and scientific personnel primarily in aerospace and automotive companies. After countless years in the computer industry both doing and managing, Ivor now writes on programming topics for relaxation. When not relaxing, he takes an interest in cosmology, cacti, chaos, and cameras, and does a little editing and criticising of other peoples' efforts on the side.
See More
Download TitleSizeDownload
Download all the code and excercise samples from the book. (corrected)
Note: This corrected version addresses errors in previously posted versions. (Feb 07, 2006)
This download is archived using the .rar format. You will need software like WinRAR to extract the files from the archive.
275.08 KB Click to Download
See More

Do you think you've discovered an error in this book? Please check the list of errata below to see if we've already addressed the error. If not, please submit the error via our Errata Form. We will attempt to verify your error; if you're right, we will post a correction below.

ChapterPageDetailsDatePrint Run
Code Replacement / Content Posting
The content for this title has been posted and may be accessed via:
http://www.wrox.com/WileyCDA/WroxTitle/productCd-0764543652,descCd-download_code.html
02/13/2006
4 Change in Text

Last paragraph: delete the line "For more instructions on how to enroll, please see Appendix F at the back of this book."

31-Jul-02 1
7 Change in the text

Last paragraph, 2nd line: change "runon" to "run on"

25-Jul-02 1
24 Change in the code

In the code "private bool hatOn = false;" should be "private boolean hatOn = false;"

25-Jul-02 1
24 Change in text

Third line in the second paragraph after the diagram whould read: "The class has four instance variables, owner, type, size, and hatOn, and this last variable is always initialized as false."

19-Aug-02 1
38 Error in Text
'... that is not integral'.

should be:

'...that is not integer'.
03/10/2008
49 Variable names in shaded block of code
In the shaded block of code at the top of the page, each occurrence of the variable names "apples", "oranges" and "fruit" should be replaced by numOranges", "numApples" and "numFruit" respectively.
1/22/05
2 49 Change in Code

The code has three variables declared at the beginning which should be:

int numOranges = 5;
int numApples = 10;
int numFruit = 0;
04-Feb-03 4
3 101 Mistake in diagram

The second algorithm for the While loop has a mistake. The arrow below the Test condition box should be pointing down and not upwards.

03-Feb-03 4
110 Change in code

In the code there is an extra } bracket after System.out.println(i);

05-Aug-02 1
116 White space

Line 2 should read as "assert false : "daysInMonth has the value " + daysInMonth;" (there should be a white space after "value").

05-Aug-02 1
125 Change in the diagram

In the diagram the arrow should also poit to the newly created array.

20-Aug-02 1
131 Extra } bracket

In the code, remove the } bracket after: "temperature [i][j] = (float)(45.0*Math.random() - 10.0);".

18-Aug-02 1
4 135 Change in text

The third last paragraph. It is \unnn and not \Unnn. Also, delete line "The U can be upper or lower case" and replace with "The u can only be in lower case".

04-Feb-03 1
136 Remove text

Last paragraph: Remove the sentence "However, if you try to compile a program containing this statement you will get an error."

19-Aug-02 1
178 Change in heading

Change the heading "Running from a Method" to "Returning from a Method"

31-Jul-02 1
188 Wrong "," use

In the second paragraph after the diagram the sentence should read: "Now we have a Sphere object with a radius of 10.0 located at the coordinates (1.0, 1.0, 1.0)."

19-Aug-02 1
196 Change in code

Add the following statement to the code for the Sphere() constructor in the middle of the page:

++count; // Increment the object count
24-Sept-03 1
5 204 Error in notation

In the table near the top of the page, for n<0, n=0, and n>0, the characters after x should all be in superscript (raised-to). The ones in error are:

x-n
1/xn
x0
x1
04-Feb-03 1
208 Change in the text

Last paragraph: The sentence "For more information on the use of the JAR tool to create .jar archives, see Appendix A." should be removed.

24-Jul-02 1
6 259 Change in text

The last paragraph, third last line, it should read "Flea object from the myPet data member" and not thePet.

04-Feb-03 4
262 Order of Class boxes wrong

In the diagram the order of the class boxex is wrong. It should be Animal ->Dog->Spaniel and not Dog->Animal->Spaniel. Also, "Spanial" should be "Spaniel"

05-Aug-02 1
266 Change in sentence

The sentence below the illustration should read:
"This shows two polylines, one defined by four points, the other defined by six points."

24-Sept-03 1
268 PolyLine - Image - Errata

The diagram at the top contains a representation of a PolyLine class with the code 'ListPoint and; ListPoint start;' This should be read as, 'ListPoint end; ListPoint start;'

11-Sep-02 1
270 Change in code

The PolyLine constructor contains superfluous code. The addPoint() method already takes care of the start and end manipulations so they aren't needed in the constructor. It therefore can be coded like this:

public PolyLine(Point[] points) {
if(points != null) { // Make sure there is an array
for(int i = 0; i < points.length; i++)
addPoint(points[i]);
}
}
24-Sept-03 1
271 Code improvement

Because the addPoint() method takes care of the start and end manipulations the constructor at the top of the page can be coded more simply as follows:

public PolyLine(double[][] coords) {
if(coords != null) {
for(int i = 0; i < coords.length ; i++)
addPoint(coords[i][0], coords[i][1]);
}
}
24-Sept-03 1
279 public MyOtherClass - Code Errata
The second code Blurb on the page should read as follows.
public MyOtherClass implements ConversionFactors

should read as

public class MyOtherClass implements ConversionFactors
11-Sep-02 1
283 Code correction

The line at the bottom of the page is part of the comment. This should be on the line above:

Conversions converter = null; // Variable of the Conversions interface type
24-Sept-03 1
285 Semicolon causes error in code
Remove the semicolon at the end of the last if statement.
12/3/04
298 Change in text

Line 18: It should be "Chapter 13" instead of "Chapter 10".

19-Aug-02 1
298 Change in text

Line 36: It should be "Chapter 15" instead of "Chapter 11".

19-Aug-02 1
321 Change in code

The code for method1() in the diagram should be:

void method1(...){
try {
int x = method2(...);
} catch(Exception1 e) {
// Handle exception...
}
catch(Exception2 e) {
// Handle exception...
}
}
24-Sept-03 1
8 347 Change in sentence

The last sentence on the page should read:
"This will show the user that the value cannot be displayed within the specified width."

24-Sept-03 1
8 347 Error in code

The 2nd and 7th line of code from the top of the page should be:

this(output, true, width, ......);

not

this(output, false, width, .....);
04-Feb-03 5
8 350 Change in code

The last line of code on this page and the bit on the next page should be changed to:


      out.print(strings[i]);  // Override width
    }
    out.flush();
  }
}
04-Feb-03 5
350 Change in comment

The last comment line on the page should be deleted.

24-Sept-03 1
350 Change in code

The following line of code should be inserted immediately before the last for loop:

out.setWidth(14);
24-Sept-03 1
357 Change in code

The line of code towards the bottom of the page should be: File remoteFile = new File(new URI("http://p2p.wrox.com/java"));

24-Sept-03 1
359 Change in code

The code fragment : File myFile = new File ("dir" + separator + "output.txt"); should read as : File myFile = new File("dir" + File.separator + "output.txt");

16-Jul-02 1
359 Change in sentences

The first two sentences should be replaced by:
"This statement creates a File object encapsulating a pathname string that is just the name "output.txt". This will be interpreted as being the name of a file in the current directory when the File object is used. Unless it has been changed programmatically, the current directory will be the directory that was current when program execution was initiated."

24-Sept-03 1
362 Change in sentence

The third sentence in the last paragraph should read:
"For a File object created from a relative path string consisting of just the name of the file, the getParent() method will return null."

24-Sept-03 1
368 Change in code

The following import statement in the example is not required and should be deleted:

import java.util.Date; // For the Date class
24-Sept-03 1
377 Linux code correction

The example on this page works under MS Windows but fails under Linux. To make the example work in both environments replace the last line of the do-while loop with:

}while(newFile.exists()); // Stop when no such File exists
and add the following statement immediately after the do-while loop:
aFile.renameTo(newFile); // Rename the file
24-Sept-03 1
390 Change in text
The relationship at the bottom of the page should be:
0 = position = limit = capacity
24-Sept-03 1
394 Incorrect captions

In the bottom diagram on the page the captions are incorrect.
IntBuffe capacity = 2r should be IntBuffer capacity = 2
Char Buffer capacity = 6 should be CharBuffer capacity = 6

24-Sept-03 1
401 Change in Code

Instead of "DoubleBuffer doubleBuf=buf.asCharBuffer();" it should be "DoubleBuffer doubleBuf = buf.asDoubleBuffer();"

22-Jul-02 1
402 Change in position arrow

The location of the position arrow in the diagram is incorrect. It should point to the first empty element as the text describes and have the value 6.

24-Sept-03 1
10 402 Error in Code
The code in the book states...buf.setPosition(8*doubleBuf.getPosition());
The statement should have been: buf.position(doubleBuf.position());
The position() method without a parameter returns the current position, and the version with a parameter sets the position to the integer value you pass as the argument and then returns a reference to the buffer object so you can use it to call another method for it.
9/7/04
411 Change in Code

The last line of code on the page should be:

outChannel.write((ByteBuffer) (buf.put(phrase.getBytes()).flip()));
24-Sept-03 1
422 Text Errata line 2

On page 422, Line 2, the following sentence,
' We insert the length as type double in the view buffer, longBuf. '
Should be read as follows:
' We insert the length as type double in the view buffer, doubleBuf '

19-Sep-02 1
439 Change in Code

In the code at the bottom of the page, the following line should be deleted:

primes = new long[inChannel.size()/8]; // Array to hold 5 primes
24-Sept-03 1
444 Change in sentence

The sentence in the middle of the page that reads:
"We will also need an array of type byte[] to hold the string characters - remember, we wrote the string as bytes, not Unicode characters."
should be replaced by the sentences:
"We will also need an array of type byte[] to hold the string characters. Remember, we wrote the string as Unicode characters so we must allow 2 bytes for each character in the original string."

24-Sept-03 1
445 Change in code

The code does not account for the fact that string characters were written to the file by the example on P421 as Unicode and therefore occupy two bytes. The code at the top of the page should be:

buf = ByteBuffer.allocate(2*strLength+8); // Buffer for the string & the prime

if(inChannel.read(buf) == -1) // Read the string & binary prime value
{
assert false; // Should not get here!
break; // Exit loop on EOF
}
buf.flip();
strChars = new byte[2*strLength]; // Create the array for the string
buf.get(strChars); // Extract string & binary prime value

System.out.println("String length: "+strChars.length+" String: "+
ByteBuffer.wrap(strChars).asCharBuffer()+" Binary value: "+buf.getLong());

lengthBuf.clear(); // Clear the buffer for the next read
}
24-Sept-03 1
446 Change in code

Because of the change on P445, the code at the top of this page should be:

try
{
ByteBuffer lengthBuf = ByteBuffer.allocate(8);
int strLength = 0; // Stores the string length
ByteBuffer buf = null; // Stores a reference to the second byte buffer
byte[] strChars = null; // Stores a reference to an array to hold the string

while(true)
{
if(inChannel.read(lengthBuf) == -1) // Read the string length, if its EOF
break; // exit the loop

lengthBuf.flip();
strLength = (int)lengthBuf.getDouble(); // Extract the length and convert to int
buf = ByteBuffer.allocate(2*strLength+8); // Buffer for the string & the prime

if(inChannel.read(buf) == -1) // Read the string & binary prime value
{
assert false; // Should not get here!
break; // Exit loop on EOF
}
buf.flip();
strChars = new byte[2*strLength]; // Create the array for the string
buf.get(strChars); // Extract string & binary prime value

System.out.println("String length: "+strChars.length+" String: "+
ByteBuffer.wrap(strChars).asCharBuffer()+" Binary value: "+buf.getLong());

lengthBuf.clear(); // Clear the buffer for the next read
}
System.out.println("\nEOF reached.");
inFile.close(); // Close the file and the channel

}
catch(IOException e)
{
e.printStackTrace(System.err);
System.exit(1);
}
System.exit(0);
}
}
24-Sept-03 1
448 Unnecessary method

The replenish() method is unnecessarily complicated and is not required for the example that follows - once corrected. Thus the second paragraph on the page, the code that follows it, and the paragraph following the code can be deleted.

24-Sept-03 1
449 Change in code
This contains the same error as the previous example so the test for available bytes in the buffer and the statement that follows that allocates the strChars array need to be changed. The replenish() method is unnecessarily complicated since the read() method for the channel will not attempt to read more bytes than are available from the channel. The example can therefore be coded much more simply without the need for the replenish() method as follows:
import java.io.FileInputStream;
import java.io.IOException;
import java.io.File;
import java.io.FileNotFoundException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class ReadPrimesMixedData
{
  public static void main(String[] args)
  {
    File aFile = new File("C:/Beg Java Stuff/primes.txt");
    FileInputStream inFile = null;
    
    try
    {
      inFile = new FileInputStream(aFile);
    }
    catch(FileNotFoundException e)
    {
      e.printStackTrace(System.err);
      System.exit(1);
    }
    
    FileChannel inChannel = inFile.getChannel();
    
    try
    {
      ByteBuffer buf = ByteBuffer.allocateDirect (1024);
      buf.position(buf.limit());  //Set the position for the loop operation
      int strLength = 0;  //Stores the string length
      byte[] strChars = null; //Stores a reference to an array to hold the string
      while(true)
      {
        if(buf.remaining() < 8)
        {
          //Verify enough bytes for string length
          if(inChannel.read(buf.compact()) == -1)
            break;
          buf.flip();
        }
        
        strLength = (int)buf.getDouble();
        
        if(buf.remaining() < 2*strLength)
        {
          //Verify enough bytes for complete string
          if(inChannel.read(buf.compact()) == -1)
            break;
          buf.flip();
        }
        
        strChars = new byte[2*strLength];
        buf.get(strChars);
        
        if(buf.remaining() < 8)
        {
          //Verify enough bytes for prime value
          if(inChannel.read(buf.compact()) == -1)
            break;
          buf.flip();
        }
        
        System.out.println("String length: " + strChars.length + "  String: " +
            ByteBuffer.wrap( strChars ).asCharBuffer() + "  Binary value: " + buf.getLong());
      }
      
      System.out.println("\nEOF reached.");
      inFile.close(); //Close the file and the channel
      
    }
    catch(IOException e)
    {
      e.printStackTrace(System.err);
      System.exit(1);
    }
    
    System.exit(0);    
  }
}
24-Sept-03 1
450 Change in text

To take account of the code changes on P449, the second paragraph in the How It Works Section should be changed to:

"Within the loop we first check whether there are sufficient bytes for the double value specifying the string length. On the first iteration, this will definitely not be the case so the compact() method will be called to compact the buffer and the reference to buf that is returned will be passed to the read() method for inChannel read data from the file. We then flip the buffer and get the length of the string. Of course, data in the file should be in groups of three items - string length, string, binary prime value - so the end-of-file should be detected trying to obtain the first of these by the read() method for the channel returning -1. In this case we exit the loop by executing a break statement."

24-Sept-03 1
457 Change in output statement

The output will be presented better, particularly under Linux if the newline is written after each group of 5 primes. To do this, the output statement can be changed to:

System.out.print(str.substring(str.length()-12, str.length())+
((i+1)%5 == 0 ? "\n" : ""));
24-Sept-03 1
458 Change in statement

The buffer is unnecessarily large. The statement allocating the buffer should be changed to:

ByteBuffer buf = ByteBuffer.allocate(8);
24-Sept-03 1
11 463 Change in code due to change in 1.4 SDK
Due to change in 1.4 SDK, the map modes have changed. They are now defined in the static inner class, MapMode, which is a part of the clas FileChannel. Hence, the code should change to:
MappedByteBuffer buf = ioChannel.map( FileChannel.MapMode.READ_WRITE, 0L, ioChannel.size() ).load();
14-Mar-03 5
463/464 Improperly shaded code
The code has not been shaded properly. It should look like this:
import java.io.*;
import java.nio.*;
import java.nio.channels.FileChannel;

public class MemoryMappedFile
{
  public static void main(String[] args)
  {
    File aFile = new File("C:/Beg Java Stuff/primes.bin");
    RandomAccessFile ioFile = null;
    
    try
    {
      ioFile = new RandomAccessFile(aFile,"rw");
    }
    catch(FileNotFoundException e)
    {
      e.printStackTrace(System.err);
      System.exit(1);
    }
    FileChannel ioChannel = ioFile.getChannel();
    final int PRIMESREQUIRED = 10;
    long[] primes = new long[PRIMESREQUIRED];
    
    int index = 0;  //Position for a prime in the file

    final long REPLACEMENT = 999999L; //Replacement for a selected prime
    
    try
    {
      final int PRIMECOUNT = (int)ioChannel.size()/8;
      MappedByteBuffer buf =
        ioChannel.map( ioChannel.MAP_RW, 0L, (int)ioChannel.size() ).load();
      for(int i = 0 ; i < PRIMESREQUIRED ; i++)
      {
         index = 8*(int)(PRIMECOUNT*Math.random());
         primes[i] = buf.getLong(index);
         buf.putLong(index, REPLACEMENT );
      }
      
      StringBuffer str = null;
      
      for(int i = 0 ; i&tl;PRIMESREQUIRED ; i++)
      {
        str = new StringBuffer("           ").append(primes[i]);
        System.out.print( str.substring(str.length() - 12, str.length()) +
          ((i + 1) % 5 == 0 ? "\n" : ""));
      }
      ioFile.close(); // Close the file and the channel
    }
    catch(IOException e)
    {
      e.printStackTrace(System.err);
      System.exit(1);
    }
    System.exit(0);
  }
}
24-Sept-03 1
494 Change in sentence

The last sentence in exercise 3 "You can get and set the file position from the underlying file input stream object" should be replaced by "You can't get the file position in an object stream in the same way as you can with a channel. However, you can use the sequence number for an object as the index - the first object being 1, the second being 2, and so on."

22-Jul-02 1
494 Change in the sentence

In Chapter 12 Exercise 4, the last sentence should be changed to "When an IndexEntry is found, you use the sequence number it contains to retrieve the appropriate Person object."

22-Jul-02 1
515 Code Re-write

the code should be re-written as follows

Transaction[] data = new Transaction[transactions.size()];
data = (Transaction[]) transactions.toArray(data);

should be read as follows:

Transaction[] data = new Transaction[0]; //Array with Zero elements
data = (Transaction[]) transactions.toArray(data);
11-Sep-02 1
562 Typo

In the table the next method should be written as nextInt(int limit).

19-Aug-02 1
567 Code Errata on Pg 567

The Code on the bottom of this page should be read as follows:

DateFormat fmt = getDateTimeInstance(Locale.FULL, Locale.US);

should be read as

DateFormat fmt = getDateTimeInstance(DateFormat.FULL, DataFormat.FULL, Locale.US);
24-Sep-02 1
646 Change in figure

"java.swing" should be "javax.swing" in the figure.

19-Aug-02 1
16 652 Error in diagram

In the figure, the third and top-most pane should say "contentPane object" and not "constantPane obejct".

04-Feb-03 4
See More
Back to Top