Wiley
Wiley.com
Print this page Share

Ivor Horton's Beginning Java, Java 7 Edition

ISBN: 978-0-470-40414-0
1152 pages
September 2011
Ivor Horton

Description

Find out why thousands have turned to Ivor Horton for learning Java

Ivor Horton's approach is teaching Java is so effective and popular that he is one of the leading authors of introductory programming tutorials, with over 160,000 copies of his Java books sold. In this latest edition, whether you're a beginner or an experienced programmer switching to Java, you'll learn how to build real-world Java applications using Java SE 7. The author thoroughly covers the basics as well as new features such as extensions and classes; extended coverage of the Swing Application Framework; and he does it all in his unique, highly accessible style that beginners love.

  • Provides a thorough introduction to the latest version of the Java programming language, Java SE 7
  • Introduces you to a host of new features for both novices and experienced programmers
  • Covers the basics as well as new language extensions and classes and class methods
  • Guides you through the Swing Application Framework for creating Swing apps
  • Uses numerous step-by-step programming examples to guide you through the development process

There's no better way to get thoroughly up to speed on the latest version of Java than with Ivor Horton's latest, comprehensive guide.

See More

Table of Contents

WELCOME xxix

CHAPTER 1: INTRODUCING JAVA 1

CHAPTER 2: PROGRAMS, DATA, VARIABLES, AND CALCULATION 27

CHAPTER 3: LOOPS AND LOGIC 71

CHAPTER 4: ARRAYS AND STRINGS 113

CHAPTER 5: DEFINING CLASSES 165

CHAPTER 6: EXTENDING CLASSES AND INHERITANCE 221

CHAPTER 7: EXCEPTIONS 279

CHAPTER 8: UNDERSTANDING STREAMS 309

CHAPTER 9: ACCESSING FILES AND DIRECTORIES 335

CHAPTER 10: WRITING FILES 365

CHAPTER 11: READING FILES 415

CHAPTER 12: SERIALIZING OBJECTS 451

CHAPTER 13: GENERIC CLASS TYPES 469

CHAPTER 14: THE COLLECTIONS FRAMEWORK 517

CHAPTER 15: A COLLECTION OF USEFUL CLASSES 565

CHAPTER 16: THREADS 619

CHAPTER 17: CREATING WINDOWS 661

CHAPTER 18: HANDLING EVENTS 733

CHAPTER 19: DRAWING IN A WINDOW 787

CHAPTER 20: EXTENDING THE GUI 845

CHAPTER 21: FILING AND PRINTING DOCUMENTS 913

CHAPTER 22: JAVA AND XML 969

CHAPTER 23: CREATING AND MODIFYING XML DOCUMENTS 1031

APPENDIX A: KEYWORDS 1077

APPENDIX B: COMPUTER ARITHMETIC 1079

INDEX 1085

See More

Author Information

Ivor Horton is one of the preeminent authors of tutorials on the Java, C, and C++ programming languages. He is widely known for the tutorial style of his books, which provide step-by-step guidance easily understood even by first-time programmers. Horton is also a systems consultant in private practice.

See More

Downloads

Download TitleSizeDownload
README FIRST 1.27 KB Click to Download
Complete code download for Ivor Horton's Beginning Java, Java 7 Edition 868.00 KB Click to Download
Exercise Solutions 602.51 KB Click to Download
Errata - Error in Code, Chapter 19
3/26/13
87.94 KB Click to Download
Errata - Error in Code, Chapter 20
3/26/13
149.18 KB Click to Download
Errata - Error in Code, Chapter 23
3/26/13
35.90 KB Click to Download
Errata - Error in Code, Chapter 21
3/26/13
267.74 KB Click to Download
Errata--Error in Figure, 4-13, pg 157
Figure 4-13 is incorrect. The correction has been uploaded.
14.28 KB Click to Download
See More

Errata

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
5 Error in Text
Currently reads:
"By coding everything yourself you will maximizes your learning experience."

Should read:
"By coding everything yourself you will maximize your learning experience."
03/16/2012
6, Figure 1-1 Errors in Text
Text accompanying Figure 1-1:

Currently reads: Foot
Should read: Root


Currently reads: Containe a sro zip file that contain
Should read: Contains a src zip file that contains


Currently reads: Cheader files
Should read: C header files
02/12/2012
7 Error in Text
Page 7, sentence just before the code sample (MyProgram.java):

Currently reads: Here's a simple program that you use to can try out the compiler:
Should read: Here's a simple program that you can use to try out the compiler:
02/12/2012
16 Error in Figure 1.7 Code
//Method to put hat on
public void putHston() {

should read:
public void putHatOn() {
10/18/11
2 28 Error in Text
(second sentence in the second Note box)
Currently Reads:
If it is not, you must specify the -encoding option to tell the compiler about the character encoding for you source code.
Should Read:
If it is not, you must specify the -encoding option to tell the compiler about the character encoding for your source code.
5 June 2015
30 Error in Text
Passage: For example you can write the value 1,234,567,890 as the literal 1234567899L or as the literal 1_234_567_890L

Currently reads: 1234567899L
Should read: 1234567890L
02/09/2012
2 39 Error in Text
(third paragraph under Integer Division and Remainder)
Currently Reads:
When the divisor is a negative integer of the largest possible magnitude and the divisor is-1, the result is the same as the dividend, which is negative and therefore violates the rule.
Should Read:
When the dividend is a negative integer of the largest possible magnitude and the divisor is-1, the result is the same as the dividend, which is negative and therefore violates the rule.
5 June 2015
2 42 Error in Text
(paragraph under code)
Currently Reads:
The value stored in number is converted to type a, and that is multiplied by the value of factor
Should Read:
The value stored in number is converted to type long, and that is multiplied by the value of factor
5 June 2015
54 Error in Text
5th paragraph:

"I can illustrate how this works by assuming the variable indicators contains the binary value 0b1111_1111_0000_1111, which you could also write as the hexadecimal value 0xFF07."

The binary value cited is actually 0xFF0F.
12/9/2011
55 Error in Text
Page 55, first table:

Given the mask value of 0b0000_0000_0000_0100, the ~mask value should be 0b1111_1111_1111_1011, not 0b1111_1111_1111_0100.
12/9/2011
2 59 Error in Text
(middle of the paragraph under Figure 2-5)
Currently Reads:
When the sign bit is not propagated, the shift right operation does not have a numerical interpretation for negative values because the sign bit is treated the same as any other bit, and zeros are inserted from the right.
Should Read:
When the sign bit is not propagated, the shift right operation does not have a numerical interpretation for negative values because the sign bit is treated the same as any other bit, and zeros are inserted from the left.
8 June 2015
2 59 Error in Text
(text in the middle of figure 2-5)
Currently Reads:
Y = value & 0xFF
Should Read:
Y=value & 0xFFFF
8 June 2015
97 Error in Text
Currently reads:

"The semicolon is optional, but putting in shows..."

Should read:

"The semicolon is optional, but putting it in shows..."
05/02/2012
118 Error in Code
In Figure 4-3 the box containing the name "values" should contain "value" and the statement at the bottom of Figure 4-3 should read:
long[] value = even;
11/29/2011
4 123 Error in Code
There is currently an error in the code in the TRY IT OUT: The Weather Fanatic example for a 2 dimensional array.

The 7th line of code currently reads:
temperature[ i ] [ j ] = (float)(45.0*Math.random() ? 10.0);

Should read:
temperature[i][j] = (float)(45.0*Math.random() - 10.0);
03/13/2012
172 Error in Text (Figure 5-3)
Figure 5-3 on page 172 contains a typo.

The second line of code reads:
double x 5 MyClass.mean(3.0, 5.0);

but should read:
double x = MyClass.mean(3.0, 5.0);
07/15/2012
188 Error in Code
Near the top of page 188, there is code used to create a duplicate of an existing sphere.
The 6th line of this code doesn't quite fit with the intent:

Currently reads:
zCenter = oldSphere.yCenter;

Should read:
zCenter = oldSphere.zCenter;
07/18/2012
195 Error in Text
The second to last line contains a typo:
Currently reads: keywordo

Should read: keyword
07/31/2012
6 242 Error in Code
(code that starts at the bottom of the page)
Public class PetDog extends Dog {
//Constructor
public PetDog (String name,String breed,String fleaName,String fleaSpecies {
super (name, bree);
petFlea= new Flea ("Max", "circus flea");     //Initialize petFlea
Should Read:
Public class PetDog extends Dog {
//Constructor
public PetDog (String name, String breed, String fleaName, String fleaSpecies {
super (name, bree);
petFlea= new Flea(fleaName, fleaSpecies);     //Initialize petFlea
9 June 2015
255 Error in Figure
Diagram is incorrect. The first box in the second row should be labeled as a ListPoint, not a PolyLine.
04/10/2012
7 289 Error in Text
(text at top of Figure 7-2)
Currently Reads:
double do Something (IntaParam
      throw & Exception type 1, Exception Type 2
{
Should Read:
double do Something (IntaParam
      throw Exception type 1, Exception Type 2
{
17 June 2015
325 Error in Code
There is an error in the readString function.

Currently reads:

   || ttype == '''')  {

Should read:

   || ttype == '\'')  {
04/27/2012
361 Error in Text
Sentence in the first paragraph following the "How It Works" heading:

Currently reads:
fetParent()

Should read:
getParent()
05/03/2012
9 351 Error in Code
(middle of the code block in bold font)
Currently Reads:
// Get files with a 3 character extension begiining with 'j'
Should Read:
// Get files with a 3 character extension beginning with 'j'
17 June 2015
9 353 Error in Code
(code under Moving and Copying Files and Directories)
CurrentlyReads:
Path sourcePath=Paths.get("D:/Temp1/output.txt");
Path destinationPath=Paths.get("D:/Temp2/output.txt");
Try {
   sourcePath.moveTo (destinationPath);
} catch (NoSuchFileException e) {
   System.err.print1n(Move failed." + e);
} catch(FileAlreadyExistsException e) {
   System.err.print1n(File already exists." + e);
} catch (IOException e) {
System.err.print1n("I/O error." + e);
}
Should read:
Path sourcePath = Paths.get("D:/Temp1/output.txt");
Path destinationPath = Paths.get("D:/Temp2/output.txt");
try {
   Files.move(sourcePath, destinationPath);
} catch(FileAlreadyExistsException e) {
    System.err.println("File already exists." + e);
} catch(IOException e) {
   System.err.println("I/O error." + e);
}
17 June 2015
9 356 Error in Code
(code at the top of the page, about 2/3rd the through the code)
Currently Reads:
catch(IOException e) {
System.err.println("I/O error in copyFiles. " + e);
return false;
Should Read:
catch(IOException e) {
System.err.println("I/O error in moveFiles. " + e);
return false;
17 June 2015
13 493 Error in Code
(about halfway through code on the page)
Currently Reads:
LinkedList<T> values = new LinkedList<>();     //Create a linked list
treeSort(root);                // Sort the objects into the list
return values;
}
Should Read:
LinkedList<T> values = new LinkedList<>();     //Create a linked list
treeSort(root, values);          // Sort the objects into the list
return values;
}
13 June 2015
13 489 Error in Text
(first sentence in the last paragraph on the page)
Currently Reads:
You need to be able to decide whether an object to be stored in a tree is greater or less than existing objects so bjects that are to be added
Should Read:
You need to be able to decide whether an object to be stored in a tree is greater or less than existing objects so objects that are to be added
17 June 2015
14 526 Error in Text
(Figure 14-6, middle box)
Currently Reads:
HashMAP<K,V> Should Read:
HashMap<K,V>
17 June 2015
716 Error in Text
Figure 17-33.
Text in this figure reads "Width contraint" and "Height contraint". In both cases, "contraint" should be "constraint."
03/13/2012
769 Error in Text
Currently reads:
"The second stores the name by calling the first constructor and then creates...."
Should read:
"The second stores the name by calling the base class constructor and then creates...."
03/13/2012
782 Error in Text
Currently reads:
"new16.gif"

Should read:
"New16.gif"
03/09/2013
802 Error in Code
The following lines should be deleted:
p1.setLocation(p1.x, p1.y - height1); 
p2.setLocation(p2.x, p2.y - height2);               
g2D.draw(new Line2D.Float(p1, p2));
03/09/2013
807 Error in Text
The variable declaration for endC currently reads:
"private private"

One "private" should be deleted.
03/09/2013
823 Error in Code
Code currently reads:
import java.awt.*;
import java.io.Serializable;
public abstract class Element implements Serializable {
protected Element(Point position, Color color) {
this.position = position;
this.color = color;
}
public Color getColor() {
return color;
}
public Point getPosition() {
return position;
}
public java.awt.Rectangle getBounds() {
return bounds;
}
public abstract void draw(Graphics2D g2D);
public abstract void modify(Point start, Point last);
protected Point position; // Position of a shape
protected Color color; // Color of a shape
protected java.awt.Rectangle bounds; // Bounding rectangle
private final static long serialVersionUID = 1001L;
}

Code should read:
import java.awt.*;
import java.io.Serializable;
public abstract class Element implements Serializable {
protected Element(Point position, Color color) {
this.position = position;
this.color = color;
}
public Color getColor() {
return color;
}
public Point getPosition() {
return position;
}
public java.awt.Rectangle getBounds() {
return bounds;
}
public abstract void draw(Graphics2D g2D);
public abstract void modify(Point start, Point last);
protected Point position; // Position of a shape
protected Color color; // Color of a shape
protected java.awt.Rectangle bounds; // Bounding rectangle
  protected static final Point origin = new Point();                   // Origin for elements
private final static long serialVersionUID = 1001L;
}
06/14/2012
14 529 Error in Text
(bottom of the page)
Currently Reads:
The capacity-doubling mechanism means that the capacity is always a value of the form 〖100X2〗^n, and the smallest n to accommodate 7,000 references is 128.
Should Read:
The capacity-doubling mechanism means that the capacity is always a value of the form〖100X2〗^n, and the smallest n to accommodate 7,000 references is 7.
17 June 2015
834 Error in Code
In the draw() method:

Currently reads:
g2D.translate(position)

Should read:
g2D.translate(position.x, position.y)
03/09/2013
838 Error in Code
Code currently reads:
circle = new Ellipse2D.Double(origin.x, origin.y, 2. * radius, 2. * radius);

Code should read:
circle = new Ellipse2D.Double(origin.x, origin.y, 2.0 * radius, 2.0 * radius);
06/14/2012
861 Error in Code
The line of code that calls setPaint() in the block of code at the top of page 861 should read g2D.setPaint(color);
03/09/2013
859 Error in Code
The following lines should be in bold:

public final static int TEXT = 105;
public final static int Font DEFAULT_FONT = new Font("Serif", Font.BOLD, 12);
03/09/2013
867 Error in Text
The middle paragraph refers to:
setCurrentFont()

This should be:
setFont()
03/09/2013
876 Error in Code
In SketcherFrame constructor, line above 1st bolded line should also be in bold, and the statement is incorrect. It should read:
optionsMenu = new JMenu("Options");
03/09/2013
903-905 Error in Text
Please add the following text and code in a new paragraph following the import statement for java.awt.geom.Line2D, about one third down page 905:

When you rotate an element, the bounding rectangle changes. You must determine the bounding rectangle for an element based on its position and rotation angle in the getBounds() method that the shape classes inherit from the Element class. If you don't do this, elements will not display correctly when you rotate them. Here's a new version of the getBounds() method in the Element class in Element.java:
  public java.awt.Rectangle getBounds() {
    AffineTransform at = AffineTransform.getTranslateInstance(position.x, position.y);
    at.rotate(angle);
    at.translate(-position.x, -position.y);
    return  at.createTransformedShape(bounds).getBounds();
  }

This first create an AffineTransform object, at, that represents a translation from the origin to the point, position. A transform that is a rotation through angle radians is then concatenated with at so the combination represents the transform that will position the bounding rectangle for the element at the correct location with the rotation applied. You want to produce a bounding rectangle for the element in its rotated position with the top-left at the origin so you concatenate a translation transform with at that moves the rotated bounding rectangle back to the origin. Finally you call the createTransformedShape() member of at to apply the transformation the the bounding rectangle for the element and return the Shape object that results. You then call the getBounds() member for the Shape object to obtain the bounding rectangle for the element when it is rotated.
03/09/2013
922 Error in Text
After the code ending on page 922, please insert text:

Add the following definition for DEFAULT_FILENAME to SketcherConstants.jav:

public final static String DEFAULT_FILENAME = "Sketch.ske";
03/09/2013
924 Error in Code
In the code for setFileExtension() the statement:

if(fileName.indexOf(extension) >= 0) {

should read:

if(fileName.indexOf(".") >= 0) {
03/09/2013
932 Error in Text
In the first sentence of 4th paragraph, the text currently reads:

"This defines... from the WindowHandler...."

Should be:

WindowAdapter
03/09/2013
935 Error in Code
Currently reads:

PrintService printer = printJob().getPrintService();

Should read:

PrintService printer = printJob.getPrintService();
03/09/2013
958 Error in Code
getPrintable() is missing the closing } for the else statement.
The code should read:
  public Printable getPrintable(int pageIndex) {
    if(pageIndex == 0) {                                                // For the first page
      return new SketchCoverPage(theApp.getWindow().getSketchName());   // return the cover page
    } else {
      return this;
    }
  }
03/09/2013
959 Error in Code
The code at the top of page 959 should read:

//      return NO_SUCH_PAGE;
//    }
    Graphics2D g2D = (Graphics2D) g;


The first two lines should be bold code font. The third line should be code font but not bold.
03/09/2013
15 612 Error in Code
Currently Reads:
if (tries<MAXTRIES) {
Should Read:
if(++tries<MAXTRIES) {
6/12/2015
21 943 Error in Text
(text at bottom of Figure 21-10)
Currently reads:
Origin was moved by-rect.x in the x direction
       and by-rect.y in the y direction
       then moved by dxin the x direction
          and by dy in the y direction
Should Read:
Origin was moved by dx in the x direction
      And by dy in the y directin
Then moved by-rect.x in the x direction
      And by-rect.y in the y direction
16 June 2015
21 955 Error in Text
(Text in Figure 21-14)
Currently reads:
getImageableX(), getImageable()
Should Read:
getImageableX(), getImageableY()
16 June 2015
19 837 Error in Text
(2nd Paragraph under "Defining Circles")
Currently Reads:
You have the center of the circle and a point on the circumference available in the methods that handle the mouse events, but the Ellipse2D class that you use to define a circle expects it to be defined by the coordinates of the point on the top-right corner of the rectangle that encloses the circle plus its height and width.
Should read:
You have the center of the circle and a point on the circumference available in the methods that handle the mouse events, but the Ellipse2D class that you use to define a circle expects it to be defined by the coordinates of the point on the top-left corner of the rectangle that encloses the circle plus its height and width.
16 June 2015
18 782 Error in Code
(last line of first code block under "Adding Menu Icons")
Currently Reads:
public final static Icon PRINT16 = new ImageIcon (imagePath+"print16.gif");
Should Read:
public final static Icon PRINT16 = new ImageIcon (imagePath+"Print16.gif");
16 June 2015
18 740 Error in Text
(last paragraph on the page)
Currently Reads:
If you had not removed the call to the setDefaultCloseOperation() method, your processWindowEvent() method would still have been called when the close icon was clicked. with the call
Should Read:
If you had not removed the call to the setDefaultCloseOperation() method, your processWindowEvent() method would still have been called when the close icon was clicked. With the call
16 June 2015
15 612 Error in Text
(3rd line from bottom in code)
Currently Reads:
if (tries Should Read:
if(++tries
17 June 2015
18 739 Error in Code
(half way through code)
Currently Reads:
//Handle window events
protcted void processWindowEvent (WindowEvent e) {
Should Read:
//Handle window events
protected void processWindowEvent (WindowEvent e) {
16 June 2015
17 717 Error in Code
(code at the bottom of the page)
Currently Reads:
constrains.setY (xSpring);
Should Read:
constains.setY (ySpring);
17 June 2015
17 710 Error in Text
(Table 17-6, description of ipadx)
Currently Reads:
An int value that defines the number of pixels by which the top and bottom edges of the component are to be expanded. The default value is 0.
Should Read:
An int value that defines the number of pixels by which the right and left edges of the component are to be expanded. The default value is 0.
(Table 17-6 description of ipady)
Currently Reads:
An int value that defines the number of pixels by which the left and right edges of the component are to be expanded. The default value is 0.
Should Read:
An int value that defines the number of pixels by which the top and bottom edges of the component are to be expanded. The default value is 0.
17 June 2015
17 709 Error in Text
(bottom of Figure 17-27)
Currently Reads:
gridx=3
Should Read:
gridx=2
17 June 2015
10 388 Error in Text
(second sentence in the paragraph preceding the code)
Currently Reads:
Typically this beis a try block with resources
Should read:
Typically this is a try block with resources
17 June 2015
23 1033 Error in Text
(Text in Setting Dom Parser Features)
Currently Reads:
The factory object has methods corresponding to each of the getXXX ()
Should Read:
The factory object has methods corresponding to each of the isXXX ()
16 June 2015
See More
Back to Top