Exam (elaborations) TEST BANK Annotated Solution Guide for Thinking in Java 4th Edition By Bruce Eckel and Ervin Varga Thinking in Java, ISBN: 2876
Annotated Solution Guide for
Thinking
in
Java
Fourth Edition
TIJ4 published February, 2006
Solution Guide published September 2007
Bruce Eckel
President, MindView, Inc.
Ervin Varga
Ph.D. Computer Science,
University of Novi Sad, Serbia;
Faculty of Technical Sciences
©2007, MindView, Inc.
All Rights Reserved
v
Contents
Copyright & Disclamer i
About this Document iii
Unpacking
the Distribution.................. iii
No Exercises in Chapter 1.. iv
Additional exercises........... iv
Installing the Code 1
Using Eclipse....................... 3
Packages & IDEs 5
Left to the Reader 7
Everything is an Object 9
Exercise 1............................. 9
Exercise 2 ............................ 9
Exercise 3 ...........................10
Exercise 4 ...........................10
Exercise 5 ........................... 11
Exercise 6 ........................... 11
Exercise 7 ...........................12
Exercise 8 ...........................13
Exercise 9 ...........................13
Exercise 10 .........................14
Exercise 11 ..........................16
Exercise 12 .........................16
Exercise 13..........................17
Exercise 14 .........................17
Exercise 15..........................18
Exercise 16 .........................18
Operators 21
Exercise 1............................21
Exercise 2 ...........................21
Exercise 3 .......................... 22
Exercise 4 .......................... 23
Exercise 5 .......................... 24
Exercise 6 .......................... 24
Exercise 7 .......................... 26
vi Thinking in Java, 4th Edition Annotated Solution Guide
Exercise 8 .......................... 27
Exercise 9 .......................... 27
Exercise 10 ........................ 28
Exercise 11 ......................... 29
Exercise 12 .........................31
Exercise 13......................... 33
Exercise 14 ........................ 33
Controlling Execution 35
Exercise 1........................... 35
Exercise 2 .......................... 35
Exercise 3 .......................... 37
Exercise 4 .......................... 38
Exercise 5 .......................... 39
Exercise 6 ...........................41
Exercise 7 .......................... 42
Exercise 8 .......................... 43
Exercise 9 .......................... 45
Exercise 10 ........................ 46
Initialization & Cleanup 49
Exercise 1........................... 49
Exercise 2 .......................... 49
Exercise 3 .......................... 50
Exercise 4 ...........................51
Exercise 5 ...........................51
Exercise 6 .......................... 52
Exercise 7 .......................... 53
Exercise 8 .......................... 54
Exercise 9 .......................... 54
Exercise 10 ........................ 55
Exercise 11 ......................... 55
Exercise 12 ........................ 56
Exercise 13..........................57
Exercise 14 ........................ 58
Exercise 15......................... 58
Exercise 16 ........................ 59
Exercise 17.........................60
Exercise 18 .........................61
Exercise 19 .........................61
Exercise 20........................ 62
Exercise 21 ........................ 63
Exercise 22........................ 63
Contents vii
Access Control 65
Exercise 1........................... 65
Exercise 2 .......................... 65
Exercise 3 .......................... 66
Exercise 4 .......................... 67
Exercise 5 .......................... 68
Exercise 6 .......................... 70
Exercise 7 .......................... 70
Exercise 8 ...........................71
Exercise 9 ...........................75
Reusing Classes 77
Exercise 1............................77
Exercise 2 .......................... 78
Exercise 3 .......................... 79
Exercise 4 ..........................80
Exercise 5 ...........................81
Exercise 6 ...........................81
Exercise 7 .......................... 82
Exercise 8 .......................... 83
Exercise 9 .......................... 84
Exercise 10 ........................ 85
Exercise 11 ......................... 86
Exercise 12 ........................ 87
Exercise 13......................... 89
Exercise 14 ........................90
Exercise 15..........................91
Exercise 16 ........................ 92
Exercise 17......................... 92
Exercise 18 ........................ 93
Exercise 19 ........................ 94
Exercise 20........................ 95
Exercise 21 ........................ 96
Exercise 22........................ 96
Exercise 23 ........................ 97
Exercise 24........................ 98
Polymorphism 99
Exercise 1........................... 99
Exercise 2 ........................ 100
Exercise 3 ........................ 102
Exercise 4 ........................ 104
Exercise 5 .........................105
Exercise 6 ........................ 106
viii Thinking in Java, 4th Edition Annotated Solution Guide
Exercise 7 ........................ 108
Exercise 8 ........................ 109
Exercise 9 ..........................111
Exercise 10 ....................... 113
Exercise 11 ........................ 114
Exercise 12 ....................... 115
Exercise 13........................ 116
Exercise 14 .......................118
Exercise 15........................ 121
Exercise 16 .......................122
Exercise 17........................123
Interfaces 125
Exercise 1..........................125
Exercise 2 .........................126
Exercise 3 .........................127
Exercise 4 ........................ 128
Exercise 5 .........................129
Exercise 6 ........................ 130
Exercise 7 ........................ 130
Exercise 8 .........................132
Exercise 9 .........................133
Exercise 10 .......................135
Exercise 11 ........................136
Exercise 12 .......................138
Exercise 13........................139
Exercise 14 ...................... 140
Exercise 15........................142
Exercise 16 .......................143
Exercise 17........................145
Exercise 18 .......................146
Exercise 19 .......................147
Inner Classes 149
Exercise 1..........................149
Exercise 2 .........................149
Exercise 3 .........................150
Exercise 4 ......................... 151
Exercise 5 .........................152
Exercise 6 .........................152
Exercise 7 .........................153
Exercise 8 .........................154
Exercise 9 .........................155
Exercise 10 .......................156
Contents ix
Exercise 11 ........................157
Exercise 12 .......................158
Exercise 13........................158
Exercise 14 .......................159
Exercise 15....................... 160
Exercise 16 ....................... 161
Exercise 17........................162
Exercise 18 .......................163
Exercise 19 .......................164
Exercise 20.......................165
Exercise 21 .......................166
Exercise 22.......................167
Exercise 23 ...................... 168
Exercise 24.......................170
Exercise 25 .......................174
Exercise 26 .......................175
Holding Your Objects 179
Exercise 1..........................179
Exercise 2 ........................ 180
Exercise 3 ........................ 180
Exercise 4 .........................181
Exercise 5 .........................183
Exercise 6 .........................185
Exercise 7 .........................187
Exercise 8 ........................ 188
Exercise 9 ........................ 189
Exercise 10 ...................... 190
Exercise 11 ........................ 191
Exercise 12 .......................192
Exercise 13........................193
Exercise 14 .......................197
Exercise 15........................197
Exercise 16 ...................... 198
Exercise 17........................199
Exercise 18 ......................200
Exercise 19 ...................... 201
Exercise 20......................202
Exercise 21 ......................203
Exercise 22......................204
Exercise 23 ......................206
Exercise 24......................208
Exercise 25 ......................209
Exercise 26 ...................... 210
x Thinking in Java, 4th Edition Annotated Solution Guide
Exercise 27 .......................212
Exercise 28.......................214
Exercise 29 .......................214
Exercise 30.......................215
Exercise 31........................217
Exercise 32 .......................219
Error Handling
with Exceptions 221
Exercise 1..........................221
Exercise 2 .........................221
Exercise 3 ........................ 222
Exercise 4 ........................ 223
Exercise 5 ........................ 224
Exercise 6 ........................ 225
Exercise 7 ........................ 226
Exercise 8 ........................ 227
Exercise 9 ........................228
Exercise 10 ...................... 229
Exercise 11 ....................... 229
Exercise 12 ......................230
Exercise 13........................231
Exercise 14 ...................... 232
Exercise 15....................... 233
Exercise 16 ...................... 234
Exercise 17....................... 235
Exercise 18 ...................... 237
Exercise 19 ......................238
Exercise 20...................... 239
Exercise 21 .......................241
Exercise 22...................... 242
Exercise 23 ...................... 243
Exercise 24...................... 245
Exercise 25 ...................... 246
Exercise 26 ...................... 247
Exercise 27 ......................248
Exercise 28......................248
Exercise 29 ...................... 249
Exercise 30...................... 250
Strings 253
Exercise 1......................... 253
Exercise 2 ........................ 254
Exercise 3 ........................ 255
Contents xi
Exercise 4 ........................ 256
Exercise 5 ........................ 257
Exercise 6 ........................260
Exercise 7 .........................261
Exercise 8 ........................ 262
Exercise 9 ........................ 262
Exercise 10 ...................... 263
Exercise 11 ....................... 266
Exercise 12 ...................... 267
Exercise 13.......................268
Exercise 14 ...................... 270
Exercise 15....................... 270
Exercise 16 ...................... 272
Exercise 17....................... 273
Alternative A ...............................274
Alternative B ...............................275
Exercise 18 ...................... 278
Alternative A ...............................278
Alternative B ...............................279
Exercise 19 ......................280
Alternative A .............................. 280
Alternative B ...............................281
Exercise 20......................282
Type Information 285
Exercise 1......................... 285
Exercise 2 ........................286
Exercise 3 ........................288
Exercise 4 ........................288
Exercise 5 ........................289
Exercise 6 ........................290
Exercise 7 ........................ 293
Exercise 8 ........................ 294
Exercise 9 ........................ 295
Exercise 10 ......................298
Exercise 11 ....................... 299
Exercise 12 ......................303
Exercise 13.......................303
Exercise 14 ......................304
Exercise 15.......................306
Exercise 16 ......................309
Exercise 17........................312
Exercise 18 .......................313
Exercise 19 .......................315
xii Thinking in Java, 4th Edition Annotated Solution Guide
Exercise 20.......................316
Exercise 21 .......................317
Exercise 22.......................318
Exercise 23 ......................320
Exercise 24.......................321
Exercise 25 ...................... 324
Exercise 26 ...................... 325
Generics 329
Exercise 1......................... 329
Exercise 2 ........................ 329
Exercise 3 ........................330
Exercise 4 .........................331
Exercise 5 ........................ 332
Exercise 6 ........................ 333
Exercise 7 ........................ 334
Exercise 8 ........................ 335
Exercise 9 ........................ 337
Exercise 10 ...................... 338
Exercise 11 ....................... 338
Exercise 12 ...................... 339
Exercise 13.......................340
Exercise 14 .......................341
Exercise 15....................... 342
Exercise 16 ...................... 343
Exercise 17....................... 344
Exercise 18 ...................... 346
Exercise 19 ...................... 347
Exercise 20...................... 349
Exercise 21 ...................... 350
Exercise 22.......................351
Exercise 23 ...................... 352
Exercise 24...................... 353
Exercise 25 ...................... 354
Exercise 26 ...................... 355
Exercise 27 ...................... 356
Exercise 28...................... 356
Exercise 29 ...................... 357
Exercise 30...................... 359
Exercise 31.......................360
Exercise 32 ......................360
Exercise 33 .......................361
Exercise 34...................... 363
Exercise 35 ...................... 364
Contents xiii
Exercise 36 ...................... 365
Exercise 37 ...................... 367
Exercise 38......................368
Exercise 39 ...................... 370
Exercise 40...................... 370
Exercise 41 ...................... 372
Exercise 42...................... 373
Arrays 377
Exercise 1..........................377
Exercise 2 ........................ 378
Exercise 3 ........................ 378
Exercise 4 ........................380
Exercise 5 ........................ 383
Exercise 6 ........................384
Exercise 7 ........................384
Exercise 8 ........................ 385
Exercise 9 ........................386
Exercise 10 ...................... 387
Exercise 11 ....................... 387
Exercise 12 ......................388
Exercise 13.......................388
Exercise 14 ......................389
Exercise 15.......................390
Exercise 16 ...................... 392
Exercise 17....................... 395
Exercise 18 ...................... 396
Exercise 19 ...................... 397
Exercise 20......................398
Exercise 21 ...................... 399
Exercise 22...................... 401
Exercise 23 ......................402
Exercise 24......................403
Exercise 25 ......................404
Containers in Depth 407
Exercise 1......................... 407
Exercise 2 ........................408
Exercise 3 ........................409
Exercise 4 ........................409
Exercise 5 ........................409
Exercise 6 ......................... 411
Exercise 7 .........................413
Exercise 8 .........................414
xiv Thinking in Java, 4th Edition Annotated Solution Guide
Exercise 9 ........................ 418
Exercise 10 .......................419
Exercise 11 ....................... 424
Exercise 12 ...................... 425
Exercise 13....................... 426
Exercise 14 ......................428
Exercise 15....................... 429
Exercise 16 ......................430
Exercise 17....................... 434
Exercise 18 ...................... 434
Exercise 19 ...................... 435
Exercise 20...................... 436
Exercise 21 ...................... 439
Exercise 22......................440
Exercise 23 .......................441
Exercise 24...................... 443
Exercise 25 ...................... 445
Exercise 26 ...................... 449
Exercise 27 .......................451
Exercise 28...................... 453
Exercise 29 ...................... 458
Exercise 30...................... 462
Exercise 31....................... 464
Exercise 32 ...................... 466
Exercise 33 ...................... 467
Exercise 34...................... 472
Exercise 35 ...................... 474
Exercise 36 ...................... 476
Exercise 37 ...................... 481
Exercise 38......................484
Exercise 39 ......................486
Exercise 40......................489
Exercise 41 ...................... 492
Exercise 42...................... 494
I/O 497
Exercise 1......................... 497
Exercise 2 ........................498
Exercise 3 ........................ 499
Exercise 4 ........................500
Exercise 5 .........................501
Exercise 6 ........................ 502
Exercise 7 ........................ 503
Exercise 8 ........................504
Contents xv
Exercise 9 ........................ 505
Exercise 10 ...................... 505
Exercise 11 .......................506
Exercise 12 ....................... 511
Exercise 13........................512
Exercise 14 .......................513
Exercise 15........................514
Exercise 16 .......................515
Exercise 17........................517
Exercise 18 .......................518
Exercise 19 ...................... 520
Exercise 20.......................521
Exercise 21 ...................... 522
Exercise 22...................... 522
Exercise 23 ...................... 524
Exercise 24...................... 525
Exercise 25 ...................... 525
Exercise 26 ...................... 530
Exercise 27 .......................531
Exercise 28...................... 533
Exercise 29 ...................... 535
Exercise 30...................... 537
Exercise 31.......................540
Exercise 32 ...................... 543
Exercise 33 ...................... 544
Enumerated Types 547
Exercise 1......................... 547
Exercise 2 ........................ 548
Exercise 3 ........................ 549
Exercise 4 ........................ 550
Exercise 5 ........................ 552
Exercise 6 ........................ 554
Exercise 7 ........................ 554
Exercise 8 ........................ 555
Exercise 9 ........................ 559
Exercise 10 ...................... 562
Exercise 11 ....................... 567
Annotations 575
Exercise 1..........................575
Exercise 2 ........................ 578
Exercise 3 .........................581
Exercise 4 ........................ 584
xvi Thinking in Java, 4th Edition Annotated Solution Guide
Exercise 5 ........................ 585
Exercise 6 ........................ 585
Exercise 7 ........................ 586
Exercise 8 ........................ 587
Exercise 9 ........................588
Exercise 10 ...................... 589
Exercise 11 .......................590
Concurrency 597
Exercise 1......................... 597
Exercise 2 ........................ 598
Exercise 3 ........................ 599
Exercise 4 ........................600
Exercise 5 ........................ 601
Exercise 6 ........................603
Exercise 7 ........................604
Exercise 8 ........................605
Exercise 9 ........................605
Exercise 10 ...................... 607
Exercise 11 .......................609
Exercise 12 ....................... 611
Exercise 13........................612
Exercise 14 .......................613
Exercise 15........................614
Exercise 16 .......................617
Exercise 17........................621
Exercise 18 ...................... 623
Exercise 19 ...................... 623
Exercise 20...................... 625
Exercise 21 ...................... 626
Exercise 22......................628
Exercise 23 ......................630
Exercise 24...................... 632
Exercise 25 ...................... 635
Exercise 26 ...................... 637
Exercise 27 ......................640
Exercise 28...................... 643
Exercise 29 ...................... 645
Exercise 30......................650
Exercise 31....................... 652
Exercise 32 ...................... 655
Exercise 33 ...................... 657
Exercise 34...................... 662
Exercise 35 ...................... 664
Contents xvii
Exercise 36 ......................668
Exercise 37 ...................... 676
Exercise 38......................682
Exercise 39 ...................... 687
Exercise 40......................690
Exercise 41 ...................... 692
Exercise 42...................... 694
Graphical
User Interfaces 697
Exercise 1......................... 697
Exercise 2 ........................ 697
Exercise 3 ........................698
Exercise 4 ........................699
Exercise 5 ........................700
Exercise 6 .........................701
Exercise 7 ........................ 702
Exercise 8 ........................ 704
Exercise 9 ........................ 705
Exercise 10 ......................708
Exercise 11 ....................... 709
Exercise 12 .......................710
Exercise 13........................712
Exercise 14 .......................714
Exercise 15........................715
Exercise 16 .......................716
Exercise 17........................718
Exercise 18 .......................719
Exercise 19 ...................... 720
Exercise 20...................... 724
Exercise 21 ...................... 726
Exercise 22...................... 728
Exercise 23 ...................... 729
Exercise 24.......................731
Exercise 25 ...................... 734
Exercise 26 .......................737
Exercise 27 ...................... 738
Exercise 28...................... 740
Exercise 29 ...................... 742
Exercise 30...................... 743
Exercise 31....................... 744
Exercise 32 ...................... 745
Exercise 33 ...................... 746
Exercise 34...................... 749
xviii Thinking in Java, 4th Edition Annotated Solution Guide
Exercise 35 .......................751
Exercise 36 .......................751
Exercise 37 ...................... 752
Exercise 38...................... 753
Exercise 39 ...................... 753
Exercise 40...................... 754
Exercise 41 ...................... 754
Exercise 42.......................755
Exercise 43...................... 758
1
Installing the Code
Detailed instructions for installing, configuring and testing the
source code.
These instructions describe a Windows installation, but they will also act as a
guide for OSX and Linux installations.
These instructions also work with the free demo version of the guide.
1. Create a directory called C:TIJ4-Solutionscode.
2. Using WinZip or some other zip utility (if one is not preinstalled, search
the web for a free utility), extract the zip file containing the code that you
received when you purchased the guide. Unzip it into the
C:TIJ4-Solutionscode directory. When you’re done, you should see
numerous subdirectories in the C:TIJ4-Solutionscode directory,
including subdirectories corresponding to the chapters in the solution
guide.
3. Install the Java SE Development Kit (JDK), version 5 or newer, from the
download site at Sun (
You’ll also eventually want the documentation, which is available from the
same site.
4. Set the CLASSPATH in your computer’s environment. For Windows
machines, right-click on the “My Computer” icon and select “Properties.”
Then select the “Advanced” tab and click the “Environment Variables”
button at the bottom. Under “System Variables,” look to see if there’s
already a “CLASSPATH” variable. If there is, double click it and add
;.;..;C:TIJ4-Solutionscode;
to the end of the current entry.
If there is no “CLASSPATH” variable, click the “New” button and enter
CLASSPATH
In the “Variable name” box, and
.;..;C:TIJ4-Solutionscode;
In the “Variable value” box, then click “OK”. To verify that your classpath
has been set, start a command prompt (see below), then enter set and
look for the CLASSPATH information in the output.
5. Using the same technique as in Step 4, but for PATH instead of
CLASSPATH, add the bin directory from your Java installation into your
2 Thinking in Java, 4th Edition Annotated Solution Guide
system’s PATH environment variable. On Windows, the default JDK
installation path is under “C:Program Files” and because this has
spaces, you must quote that directory when adding it to the PATH:
C:"Program Files"Javabin;
6. Create a directory called C:jars. Place the following files into this
directory:
• (download here:
may need to search for it).
• from the Eclipse SWT library
(
recent build number, then scroll down to “SWT Binary and Source”
and select the file corresponding to your platform. Further details
about finding the jar file are in Thinking in Java, 4th Edition, under
the heading “Installing SWT.”
• , which is actually part of the JDK, but you must explicitly
add it to your classpath. You’ll find it in the lib directory wherever you
installed the JDK on your machine. (The default is C:"Program
Files"Javalib).
• , also part of the JDK, in the /jre/lib/ directory.
• , available from
7. You must explicitly add each of the Jar files to your CLASSPATH,
following the directions in Step 4. However, you must also include the
name of the Jar file in the CLASSPATH entry. For example, after you put
the file into the C:jars directory, the associated
CLASSPATH entry is C:jars;.
8. Install the Ant 1.7 (or newer) build tool by following the instructions you
will find in the Ant download at
Note: Ant is required in order to compile the examples in the book. Once
you successfully run ‘ant build’ in the root directory, you can also
compile each example individually (once you have the CLASSPATH set, as
described in Step 4) using the javac command-line compiler that was
installed when you completed the steps 3 and 5. To compile a file called
MyP, you type javac MyP.
9. Start a command prompt in the C:TIJ4- Solutionscode directory. To
do this in Windows, press the “Start” button, then select “Run” and type
“cmd” and press “OK.” then type
Installing the Code 3
cd C:TIJ4-Solutionscode
into the resulting command window.
10. At the prompt, type
ant build
The build should successfully compile all the chapters in the solution
guide.
11. Once you’ve run ant build in the root directory, you can also move into
individual chapters and type ant (to compile and execute the code in that
chapter) or ant build (to compile the code only).
12. This code is designed to work without an IDE, but it has also been tested
with Eclipse (free at
for instructions on how to use the code with Eclipse.
If you want to use this code inside other IDEs you might need to make
appropriate adjustments. Different IDEs have different requirements and
you might find it’s more trouble than it’s worth right now; instead, you
may want to begin with a more basic editor like JEdit (free at
13. Note: The output for the programs has been verified for Java 6. Certain
programs (primarily those that use hashing) can produce different output
from one version to the next.
Using Eclipse
Once you’ve followed the above instructions, you can use the code inside the
Eclipse development environment as follows:
1. Install Eclipse from
for Java developers and follow the installation instructions.
2. Start Eclipse, then choose File | New | Java Project from the main menu.
3. In the ensuing dialog box, under “Contents,” select “Create Project from
Existing Source.” Press the “Browse” button and navigate to C:TIJ4-
Solutionscode. Enter “TIJ4-Solutions” as the project name and press
the “Finish” button.
Note: If you are installing the demo version of the solution guide, you do
not need to perform any of the following steps.
4 Thinking in Java, 4th Edition Annotated Solution Guide
4. Eclipse will work for awhile and then present you with a “problems” pane
containing a lot of errors and warnings. We’ll remove the errors in the
following steps.
5. In the “Package Explorer” pane, right click on “TIJ4-Solutions” and select
“Properties” (at the bottom). In the left column of the ensuing dialog box,
select “Java Build Path.”
6. Select the “Source” tab. The default Eclipse configuration may have
chosen to exclude and include some files. Click on “Included” and press
the “Remove” button, then click on “Excluded” and press “Remove.”
7. Click on “Excluded” and press “Edit.” Under “Exclusion Patterns,” add the
following files, which are not intended to compile. After you add the files,
press the “Finish” button.
• access/E04_ForeignC
• arrays/E11_AutoboxingWithA
• interfaces/E02_A
• reusing/E06_ChessWithoutDefC
• reusing/E20_OverrideA
• reusing/E21_FinalM
• reusing/E22_FinalC
8. Click on the “Libraries” tab, then the “Add External Jars” button. Add
, , and that are described in step
6 of the previous section.
9. When you press OK to close the dialog box, the project should rebuild
without any errors. The warnings that you see refer to code that is
intentional for those solutions, in order to demonstrate features and
issues of the language.
5
Packages & IDEs
When Java first appeared there was no Integrated
Development Environment (IDE) support, so you typically
used a text editor and the command-line compiler. Over the
years, IDE support has gotten so good (and many prevalent
IDEs are free) that it’s less and less likely that you’ll develop in
Java – or even learn the language – without an IDE.
There’s a conflict, however, between IDEs and the way that Thinking in Java
attempts to teach the language: One step at a time, using language features only
after they’ve been introduced.
An IDE like Eclipse (from www.E) likes to have all its code in packages
(later versions have become more tolerant of unpackaged code, but it still prefers
packages). Packages, however, are not introduced until the Access Control
chapter.
Because of the prevalence of IDEs, we have chosen to include package
statements for all the code in this book, even for chapters before Access Control.
If you have solved the problems in those chapters without using package
statements, your solutions are still correct.
7
Left to the Reader
We have left only a few exercises to the reader. For these, the solution typically
requires some configuration on your own computer.
The exercises left to the reader include:
• Exercises 12 & 13 from the chapter Everything Is an Object
• Exercise 13 from the chapter Initialization & Cleanup
• Exercise 2 from the chapter Access Control
• Exercise 15 from the chapter Generics
• Exercise 8 from the chapter Arrays
• Exercise 21 from the chapter Containers in Depth
• Exercise 35, 36, 38, 39, and 43 from the chapter Graphical User Interfaces
9
Everything is an
Object
To satisfy IDEs like Eclipse, we have included package statements for chapters
before Access Control. If you have solved the problems in this chapter without
using package statements, your solutions are still correct.
Exercise 1
//: object/E01_DefaultI
/****************** Exercise 1 *****************
* Create a class containing an int and a char
* that are not initialized. Print their values
* to verify that Java performs default
* initialization.
***********************************************/
package object;
public class E01_DefaultInitialization {
int i;
char c;
public E01_DefaultInitialization() {
Sln("i = " + i);
Sln("c = [" + c + ']');
}
public static void main(String[] args) {
new E01_DefaultInitialization();
}
} /* Output:
i = 0
c = [ ]
*///:~
When you run the program you’ll see that both variables are given default
values: 0 for the int, and a “space” for the char.
Exercise 2
//: object/E02_HelloW
10 Thinking in Java, 4th Edition Annotated Solution Guide
/****************** Exercise 2 ******************
* Follow the HelloD example in this
* chapter to create a "hello, world" program that
* simply displays that statement. You need only a
* single method in your class (the "main" one that
* executes when the program starts). Remember
* to make it static and to include the argument
* list (even though you don't use it).
* Compile the program with javac and run it using
* java. If you are using a different development
* environment than the JDK, learn how to compile
* and run programs in that environment.
************************************************/
package object;
public class E02_HelloWorld {
public static void main(String[] args) {
Sln("Hello, world!");
}
} /* Output:
Hello, world!
*///:~
Exercise 3
//: object/E03_ATypeN
/****************** Exercise 3 ******************
* Turn the code fragments involving ATypeName
* into a program that compiles and
* runs.
************************************************/
package object;
public class E03_ATypeName {
public static void main(String[] args) {
E03_ATypeName a = new E03_ATypeName();
}
} ///:~
Exercise 4
//: object/E04_DataO
/****************** Exercise 4 ******************
* Turn the DataOnly code fragments into a
* program that compiles and runs.
Everything is an Object 11
************************************************/
package object;
public class E04_DataOnly {
int i;
double d;
boolean b;
public static void main(String[] args) {
E04_DataOnly d = new E04_DataOnly();
d.i = 47;
d.d = 1.1;
d.b = false;
}
} ///:~
Exercise 5
//: object/E05_DataO
/****************** Exercise 5 ******************
* Modify Exercise 4 so the values
* of the data in DataOnly are assigned to and
* printed in main().
************************************************/
package object;
public class E05_DataOnly2 {
public static void main(String[] args) {
E04_DataOnly d = new E04_DataOnly();
d.i = 47;
Sln("d.i = " + d.i);
d.d = 1.1;
Sln("d.d = " + d.d);
d.b = false;
Sln("d.b = " + d.b);
}
} /* Output:
d.i = 47
d.d = 1.1
d.b = false
*///:~
Exercise 6
//: object/E06_S
/****************** Exercise 6 ******************
12 Thinking in Java, 4th Edition Annotated Solution Guide
* Write a program that includes and calls the
* storage() method defined as a code fragment in
* this chapter.
************************************************/
package object;
public class E06_Storage {
String s = "Hello, World!";
int storage(String s) {
return h() * 2;
}
void print() {
Sln("storage(s) = " + storage(s));
}
public static void main(String[] args) {
E06_Storage st = new E06_Storage();
();
}
} /* Output:
storage(s) = 26
*///:~
Exercise 7
//: object/E07_I
/****************** Exercise 7 ******************
* Turn the Incrementable code fragments into a
* working program.
************************************************/
package object;
class StaticTest {
static int i = 47;
}
public class E07_Incrementable {
static void increment() { StaticTest.i++; }
public static void main(String[] args) {
E07_Incrementable sf = new E07_Incrementable();
ment();
E07_Iment();
increment();
}
} ///:~
Everything is an Object 13
You can call increment( ) by itself, because a static method (main( ), in this
case) can call another static method without qualification.
Exercise 8
//: object/E08_StaticT
/****************** Exercise 8 ******************
* Write a program to demonstrate that no
* matter how many objects you create of a
* particular class, there is only one instance
* of a particular static field in that class.
************************************************/
package object;
public class E08_StaticTest {
static int i = 47;
public static void main(String[] args) {
E08_StaticTest st1 = new E08_StaticTest();
E08_StaticTest st2 = new E08_StaticTest();
Sln(st1.i + " == " + st2.i);
st1.i++;
Sln(st1.i + " == " + st2.i);
}
} /* Output:
47 == 47
48 == 48
*///:~
The output shows that both instances of E08_StaticTest share the same static
field. We incremented the shared field through the first instance and the effect
was visible in the second instance.
Exercise 9
//: object/E09_AutoboxingT
/****************** Exercise 9 ******************
* Write a program to demonstrate that
* autoboxing works for all the primitive types
* and their wrappers.
************************************************/
package object;
public class E09_AutoboxingTest {
public static void main(String[] args) {
14 Thinking in Java, 4th Edition Annotated Solution Guide
Byte by = 1;
byte bt = by;
Sln("byte = " + bt);
Short sh = 1;
short s = sh;
Sln("short = " + s);
Integer in = 1;
int i = in;
Sln("int = " + i);
Long lo = 1L;
long l = lo;
Sln("long = " + l);
Boolean bo = true;
boolean b = bo;
Sln("boolean = " + b);
Character ch = 'x';
char c = ch;
Sln("char = " + c);
Float fl = 1.0f;
float f = fl;
Sln("float = " + f);
Double db = 1.0d;
double d = db;
Sln("double = " + d);
}
} /* Output:
byte = 1
short = 1
int = 1
long = 1
boolean = true
char = x
float = 1.0
double = 1.0
*///:~
The terms Autoboxing and Autounboxing appear often in the literature. The
only difference is the direction of the conversion: autoboxing converts from the
primitive type to the wrapper object, and autounboxing converts from the
wrapped type to the primitive type.
Exercise 10
//: object/E10_ShowA
// {Args: A B C}
/****************** Exercise 10 ****************
Everything is an Object 15
* Write a program that prints three arguments
* taken from the command line.
* You'll need to index into the command-line
* array of Strings.
***********************************************/
package object;
public class E10_ShowArgs {
public static void main(String[] args) {
Sln(args[0]);
Sln(args[1]);
Sln(args[2]);
}
} /* Output:
A
B
C
*///:~
Remember, when you want to get an argument from the command line:
• Arguments are provided in a String array.
• args[0] is the first command-line argument and not the name of the
program (as it is in C).
• You’ll cause a runtime exception if you run the program without enough
arguments.
You can test for the length of the command-line argument array like this:
//: object/E10_ShowA
// {Args: A B C}
package object;
public class E10_ShowArgs2 {
public static void main(String[] args) {
if(h 3) {
Sln("Need 3 arguments");
S(1);
}
Sln(args[0]);
Sln(args[1]);
Sln(args[2]);
}
} /* Output:
A
B
16 Thinking in Java, 4th Edition Annotated Solution Guide
C
*///:~
S( ) terminates the program and passes its argument back to the
operating system as a status code. (With most operating systems, a non-zero
status code indicates that the program execution failed.) Typically, you send
error messages to S, as shown above.
Exercise 11
//: object/E11_AllTheColorsOfTheR
/****************** Exercise 11 *****************
* Turn the AllTheColorsOfTheRainbow example into
* a program that compiles and runs.
************************************************/
package object;
public class E11_AllTheColorsOfTheRainbow {
int anIntegerRepresentingColors;
void changeTheHueOfTheColor(int newHue) {
anIntegerRepresentingColors = newHue;
}
public static void main(String[] args) {
E11_AllTheColorsOfTheRainbow all =
new E11_AllTheColorsOfTheRainbow();
eTheHueOfTheColor(27);
}
} ///:~
Exercise 12
//: object/E12_LeftToR
/****************** Exercise 12 *****************
* Find the code for the second version of
* HelloD, the simple comment-
* documentation example. Execute Javadoc on the
* file and view the results with your Web browser.
************************************************/
package object;
public class E12_LeftToReader {
public static void main(String args[]) {
Sln("Exercise left to reader");
}
} ///:~
Everything is an Object 17
Note that Javadoc doesn’t automatically create the destination directory.
Consult the Javadoc reference in the JDK documentation to learn the many
uses of Javadoc.
Exercise 13
//: object/E13_LeftToR
/****************** Exercise 13 *****************
* Run D, D,
* and D through Javadoc. Verify
* the resulting documentation with your Web
* browser.
************************************************/
package object;
public class E13_LeftToReader {
public static void main(String args[]) {
Sln("Exercise left to reader");
}
} ///:~
Exercise 14
//: object/E14_DocT
/****************** Exercise 14 *****************
* Add an HTML list of items to the documentation
* in Exercise 13.
************************************************/
package object;
/** A class comment
* pre
* Sln(new Date());
* /pre
*/
public class E14_DocTest {
/** A variable comment */
public int i;
/** A method comment
* You can emeven/em insert a list:
* ol
* li Item one
* li Item two
* li Item three
18 Thinking in Java, 4th Edition Annotated Solution Guide
* /ol
*/
public void f() {}
} ///:~
We simply added the HTML code fragments from the chapter examples.
Exercise 15
//: object/E15_HelloWorldD
/****************** Exercise 15 *****************
* Add comment documentation to the program in Exercise 2.
* Extract it into an HTML file using Javadoc
* and view it with your Web browser.
************************************************/
package object;
/** A first example from isTIJ4/i.
* Demonstrates the basic class
* structure and the creation of a
* codemain()/code method.
*/
public class E15_HelloWorldDoc {
/** The codemain()/code method which is
called when the program is executed by saying
codejava E15_HelloWorldDoc/code.
@param args array passed from the command-line
*/
public static void main(String[] args) {
Sln("Hello, world!");
}
} /* Output:
Hello, world!
*///:~
Exercise 16
//: object/E16_OverloadingD
/****************** Exercise 16 *****************
* In the Initialization and Cleanup chapter, add
* Javadoc documentation to the O example.
* Extract it into an HTML file using Javadoc
* and view it with your Web browser.
************************************************/
package object;
Everything is an Object 19
/** Model of a single arboreal unit. */
class Tree {
/** Current vertical aspect to the tip. */
int height; // 0 by default
/** Plant a seedling. Assume height can
be considered as zero. */
Tree() {
Sln("Planting a seedling");
}
/** Transplant an existing tree with a given height. */
Tree(int i) {
Sln("Creating new Tree that is "
+ i + " feet tall");
height = i;
}
/** Produce information about this unit. */
void info() {
Sln("Tree is " + height + " feet tall");
}
/** Produce information with optional message. */
void info(String s) {
Sln(s + ": Tree is "
+ height + " feet tall");
}
}
/** Simple test code for Tree class */
public class E16_OverloadingDoc {
/** Creates bTree/b objects and exercises the two
different codeinfo()/code methods. */
public static void main(String[] args) {
for(int i = 0; i 5; i++) {
Tree t = new Tree(i);
();
("overloaded method");
}
// Overloaded constructor:
new Tree();
}
} /* Output:
Creating new Tree that is 0 feet tall
Tree is 0 feet tall
overloaded method: Tree is 0 feet tall
Creating new Tree that is 1 feet tall
Tree is 1 feet tall
overloaded method: Tree is 1 feet tall
20 Thinking in Java, 4th Edition Annotated Solution Guide
Creating new Tree that is 2 feet tall
Tree is 2 feet tall
overloaded method: Tree is 2 feet tall
Creating new Tree that is 3 feet tall
Tree is 3 feet tall
overloaded method: Tree is 3 feet tall
Creating new Tree that is 4 feet tall
Tree is 4 feet tall
overloaded method: Tree is 4 feet tall
Planting a seedling
*///:~
The one-argument constructor does not check the input argument, which should
be greater than zero. Statements that control the execution flow of the program
appear in a later chapter of TIJ4.
21
Operators
To satisfy IDEs like Eclipse, we have included package statements for chapters
before Access Control. If you have solved the problems in this chapter without
using package statements, your solutions are still correct.
Exercise 1
//: operators/E01_PrintS
/****************** Exercise 1 *****************
* Write a program that uses the "short" and
* normal form of print statement.
***********************************************/
package operators;
import .Date;
import static .Print.*;
public class E01_PrintStatements {
public static void main(String[] args) {
Date currDate = new Date();
Sln("Hello, it's: " + currDate);
print("Hello, it's: " + currDate);
}
} /* Output: (Sample)
Hello, it's: Wed Mar 30 17:39:26 CEST 2005
Hello, it's: Wed Mar 30 17:39:26 CEST 2005
*///:~
Exercise 2
//: operators/E02_A
/****************** Exercise 2 *****************
* Create a class containing a float and use it to
* demonstrate aliasing.
***********************************************/
package operators;
import static .Print.*;
class Integral {
float f;
}
22 Thinking in Java, 4th Edition Annotated Solution Guide
public class E02_Aliasing {
public static void main(String[] args) {
Integral n1 = new Integral();
Integral n2 = new Integral();
n1.f = 9f;
n2.f = 47f;
print("1: n1.f: " + n1.f + ", n2.f: " + n2.f);
n1 = n2;
print("2: n1.f: " + n1.f + ", n2.f: " + n2.f);
n1.f = 27f;
print("3: n1.f: " + n1.f + ", n2.f: " + n2.f);
}
} /* Output:
1: n1.f: 9.0, n2.f: 47.0
2: n1.f: 47.0, n2.f: 47.0
3: n1.f: 27.0, n2.f: 27.0
*///:~
You can see the effect of aliasing after n2 is assigned to n1: they both point to
the same object.
Exercise 3
//: operators/E03_A
/****************** Exercise 3 *****************
* Create a class containing a float and use it
* to demonstrate aliasing during method calls.
***********************************************/
package operators;
import static .Print.*;
public class E03_Aliasing2 {
static void f(Integral y) { y.f = 1.0f; }
public static void main(String[] args) {
Integral x = new Integral();
x.f = 2.0f;
print("1: x.f: " + x.f);
f(x);
print("2: x.f: " + x.f);
}
} /* Output:
1: x.f: 2.0
2: x.f: 1.0
*///:~
Operators 23
This exercise emphasizes that you’re always passing references around, thus
you’re always aliasing. Even when you don’t actually see changes being made to
the code you’re writing or the method you’re calling, that code or method could
be calling other methods that modify the object.
Exercise 4
//: operators/E04_V
// {Args: 30.5 3.2}
/****************** Exercise 4 *****************
* Write a program that calculates velocity
* using a constant distance and a constant time.
***********************************************/
package operators;
public class E04_Velocity {
public static void main(String[] args) {
if(h 2) {
Sln(
"Usage: java E04_Velocity distance time");
S(1);
}
float distance = FFloat(args[0]);
float time = FFloat(args[1]);
S("Velocity = ");
S(distance / time);
// Change the next line if you want to use a different
// unit for 'distance'
Sln(" m/s");
}
} /* Output:
Velocity = 9.53125 m/s
*///:~
Here we take the distance and time values from the command line. Arguments
come in as a String array; if you need a float instead, use the static
parseFloat( ) method of class Float. This can be difficult to locate using the
JDK HTML documentation; you must remember either “parse” or that it’s part
of class Float.
Note the difference between S( ) and
Sln( ); the latter terminates the current line by writing the
line separator string.
24 Thinking in Java, 4th Edition Annotated Solution Guide
Exercise 5
//: operators/E05_D
/****************** Exercise 5 *****************
* Create a class called Dog with two Strings:
* name and says. In main(), create two dogs,
* "spot" who says, "Ruff!", and "scruffy" who
* says, "Wurf!". Then display their names and
* what they say.
***********************************************/
package operators;
class Dog {
String name;
String says;
}
public class E05_Dogs {
public static void main(String[] args) {
Dog dog1 = new Dog();
Dog dog2 = new Dog();
= "spot"; = "ruff!";
= "scruffy"; = "wurf!";
Sln( + " says " + );
Sln( + " says " + );
}
} /* Output:
spot says ruff!
scruffy says wurf!
*///:~
This walks you through the basics of objects, and demonstrates that each object
has its own distinct storage space.
Exercise 6
//: operators/E06_DogsC
/****************** Exercise 6 *****************
* Following Exercise 5 assign, a new Dog
* reference to spot's object. Test for comparison
* using == and equals() for all references.
***********************************************/
package operators;
import static .Print.*;
Operators 25
public class E06_DogsComparison {
static void compare(Dog dog1, Dog dog2) {
print("== on top references: " + (dog1 == dog2));
print(
"equals() on top references: " + s(dog2)
);
print("== on names: " + ( == ));
print(
"equals() on names: " + s()
);
print("== on says: " + ( == ));
print(
"equals() on says: " + s()
);
}
public static void main(String[] args) {
Dog dog1 = new Dog();
Dog dog2 = new Dog();
Dog dog3 = dog1; // "Aliased" reference
= "spot"; = "ruff!";
= "scruffy"; = "wurf!";
print("Comparing dog1 and dog2 objects...");
compare(dog1, dog2);
print("nComparing dog1 and dog3 objects...");
compare(dog1, dog3);
print("nComparing dog2 and dog3 objects...");
compare(dog2, dog3);
}
} /* Output:
Comparing dog1 and dog2 objects...
== on top references: false
equals() on top references: false
== on names: false
equals() on names: false
== on says: false
equals() on says: false
Comparing dog1 and dog3 objects...
== on top references: true
equals() on top references: true
== on names: true
equals() on names: true
== on says: true
equals() on says: true
Comparing dog2 and dog3 objects...
== on top references: false
26 Thinking in Java, 4th Edition Annotated Solution Guide
equals() on top references: false
== on names: false
equals() on names: false
== on says: false
equals() on says: false
*///:~
Guess whether the following line compiles:
print("== on top references: " + dog1 == dog2);
Why or why not? (Hint: Read the Precedence and String operator + and +=
sections in TIJ4.) Apply the same reasoning to the next case and explain why the
comparison always results in false:
print("== on says: " + == );
Exercise 7
//: operators/E07_CoinF
/****************** Exercise 7 *****************
* Write a program that simulates coin-flipping.
***********************************************/
package operators;
import .Random;
public class E07_CoinFlipping {
public static void main(String[] args) {
Random rand = new Random(47);
boolean flip = Boolean();
S("OUTCOME: ");
Sln(flip ? "HEAD" : "TAIL");
}
} /* Output:
OUTCOME: HEAD
*///:~
This is partly an exercise in Standard Java Library usage. After familiarizing
yourself with the HTML documentation for the JDK (downloadable from
), select “R” at the JDK index to see various ways to generate
random numbers.
The program uses a ternary if-else operator to produce output. (See the Ternary
if-else Operator section in TIJ4 for more information.)
NOTE: You will normally create a Random object with no arguments to
produce different output for each execution of the program. Otherwise it can
Operators 27
hardly be called a simulator. In this exercise and throughout the book, we use
the seed value of 47 to make the output identical, thus verifiable, for each run.
Exercise 8
//: operators/E08_LongL
/****************** Exercise 8 *****************
* Show that hex and octal notations work with long
* values. Use LBinaryString() to display
* the results.
***********************************************/
package operators;
import static .Print.*;
public class E08_LongLiterals {
public static void main(String[] args) {
long l1 = 0x2f; // Hexadecimal (lowercase)
print("l1: " + LBinaryString(l1));
long l2 = 0X2F; // Hexadecimal (uppercase)
print("l2: " + LBinaryString(l2));
long l3 = 0177; // Octal (leading zero)
print("l3: " + LBinaryString(l3));
}
} /* Output:
l1:
l2:
l3:
*///:~
Note that LBinaryString( ) does not print leading zeroes.
Exercise 9
//: operators/E09_MinMaxE
/****************** Exercise 9 *****************
* Display the largest and smallest numbers for
* both float and double exponential notation.
***********************************************/
package operators;
import static .Print.*;
public class E09_MinMaxExponents {
public static void main(String[] args) {
print("Float MIN: " + Float.MIN_VALUE);
print("Float MAX: " + Float.MAX_VALUE);
28
Content preview
,Annotated Solution Guide for
Thinking
in
Java
Fourth Edition
TIJ4 published February, 2006
Solution Guide published September 2007
Bruce Eckel
President, MindView, Inc.
Ervin Varga
Ph.D. Computer Science,
University of Novi Sad, Serbia;
Faculty of Technical Sciences
©2007, MindView, Inc.
All Rights Reserved
,Contents
Copyright & Disclamer i
About this Document iii
Unpacking
the Distribution.................. iii
No Exercises in Chapter 1.. iv
Additional exercises........... iv
Installing the Code 1
Using Eclipse....................... 3
Packages & IDEs 5
Left to the Reader 7
Everything is an Object 9
Exercise 1............................. 9
Exercise 2 ............................ 9
Exercise 3 ...........................10
Exercise 4 ...........................10
Exercise 5 ........................... 11
Exercise 6 ........................... 11
Exercise 7 ...........................12
Exercise 8 ...........................13
Exercise 9 ...........................13
Exercise 10 .........................14
Exercise 11 ..........................16
Exercise 12 .........................16
Exercise 13.......................... 17
Exercise 14 ......................... 17
Exercise 15..........................18
Exercise 16 .........................18
Operators 21
Exercise 1............................21
Exercise 2 ...........................21
Exercise 3 .......................... 22
Exercise 4 .......................... 23
Exercise 5 .......................... 24
Exercise 6 .......................... 24
Exercise 7 .......................... 26
v
, Exercise 8 .......................... 27
Exercise 9 .......................... 27
Exercise 10 ........................ 28
Exercise 11 ......................... 29
Exercise 12 .........................31
Exercise 13......................... 33
Exercise 14 ........................ 33
Controlling Execution 35
Exercise 1........................... 35
Exercise 2 .......................... 35
Exercise 3 .......................... 37
Exercise 4 .......................... 38
Exercise 5 .......................... 39
Exercise 6 ...........................41
Exercise 7 .......................... 42
Exercise 8 .......................... 43
Exercise 9 .......................... 45
Exercise 10 ........................ 46
Initialization & Cleanup 49
Exercise 1........................... 49
Exercise 2 .......................... 49
Exercise 3 .......................... 50
Exercise 4 ...........................51
Exercise 5 ...........................51
Exercise 6 .......................... 52
Exercise 7 .......................... 53
Exercise 8 .......................... 54
Exercise 9 .......................... 54
Exercise 10 ........................ 55
Exercise 11 ......................... 55
Exercise 12 ........................ 56
Exercise 13..........................57
Exercise 14 ........................ 58
Exercise 15......................... 58
Exercise 16 ........................ 59
Exercise 17......................... 60
Exercise 18 .........................61
Exercise 19 .........................61
Exercise 20........................ 62
Exercise 21 ........................ 63
Exercise 22 ........................ 63
vi Thinking in Java, 4th Edition Annotated Solution Guide