100% found this document useful (13 votes)
111 views

Get Murach S Java Programming 4th Edition Joel Murach PDF Ebook With Full Chapters Now

Programming

Uploaded by

pinginilaca
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (13 votes)
111 views

Get Murach S Java Programming 4th Edition Joel Murach PDF Ebook With Full Chapters Now

Programming

Uploaded by

pinginilaca
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 60

Get ebook downloads in full at ebookname.

com

Murach s Java Programming 4th Edition Joel Murach

https://ebookname.com/product/murach-s-java-programming-4th-
edition-joel-murach/

OR CLICK BUTTON

DOWNLOAD EBOOK

Explore and download more ebook at https://ebookname.com


Instant digital products (PDF, ePub, MOBI) available
Download now and explore formats that suit you...

Murach s Android Programming 2nd Edition Joel Murach

https://ebookname.com/product/murach-s-android-programming-2nd-
edition-joel-murach/

Murach s C 2012 5th Edition Joel Murach

https://ebookname.com/product/murach-s-c-2012-5th-edition-joel-
murach/

Murach s PHP and MySQL training reference 2nd Edition


Joel Murach

https://ebookname.com/product/murach-s-php-and-mysql-training-
reference-2nd-edition-joel-murach/

Financial Accounting and Reporting 12th Edition Barry


Elliott

https://ebookname.com/product/financial-accounting-and-
reporting-12th-edition-barry-elliott/
The Timberclads in the Civil War 1st HARDCOVER Edition
Myron J.

https://ebookname.com/product/the-timberclads-in-the-civil-
war-1st-hardcover-edition-myron-j/

Asymmetric Catalysis on Industrial Scale Challenges


Approaches and Solutions Second Edition Hans Ulrich
Blaser

https://ebookname.com/product/asymmetric-catalysis-on-industrial-
scale-challenges-approaches-and-solutions-second-edition-hans-
ulrich-blaser/

Angel Roleplaying Game 1st Edition C. J. Carella

https://ebookname.com/product/angel-roleplaying-game-1st-edition-
c-j-carella/

Thomas Hematopoietic Cell Transplantation 4 Har/Cdr


Edition Frederick R. Appelbaum

https://ebookname.com/product/thomas-hematopoietic-cell-
transplantation-4-har-cdr-edition-frederick-r-appelbaum/

Software Requirements Encapsulation Quality And Reuse


1st Edition Rick Lutowski

https://ebookname.com/product/software-requirements-
encapsulation-quality-and-reuse-1st-edition-rick-lutowski/
CliffsAP calculus AB and BC 3rd ed Edition Kerry J.
King

https://ebookname.com/product/cliffsap-calculus-ab-and-bc-3rd-ed-
edition-kerry-j-king/
M urach

mu rach's

programming
4™ EDITION
JOEL MURACH

A CORE JAVA BOOK


that teaches you the Java essentials
at a professional pace,
using the time-saving features ofNetBeans

AN OBJECT-ORIENTED BOOK
that shows you how ro use business classes,
inheritance, and interfaces the way they’re
used in the real world

A GUI PROGRAMMING BOOK


that show's you how to develop graphical user
interfaces that handle events and validate data

A DATA ACCESS BOOK


that shows you how to develop
3-tier, object-oriented, database applications
the way the pros do it
TRAINING & REFERENCE

murach's

programming
4th EDITION
Joel Murach

M ike M u r a c h & A sso ciates , I n c .


4340 N. Knoll Ave. · Fresno, CA 93722
www.murach.com · [email protected]
Author: Joel Murach
Editor: Anne Boehm
Cover design: Zylka Design
Production: Maria Pedroza David

Books for Java programmers


Murach’s Java Programming
Murach’s Java Servlets and JSP

Books for database programmers


Murach’s Oracle SQL and PL/SQL
Murach’s MySQL
Murach’s SQL Server fo r Developers

Books for web developers


Murach ’s HTML5 and CSS3
Murach’s JavaScript and DOM Scripting
Murach’s PHP and MySQL

Books for .NET programmers


Murach’s C # 2010
Murach’s ASP.NET 4 Web Programming with C#2010
Murach’s ADO.NET 4 Database Programming with C# 2010
Murach’s Visual Basic 2010
Murach’s ASP.NET 4 Web Programming with VB 2010
Murach’s ADO.NET 4 Database Programming with VB 2010

Books for IBM mainframe programmers


Murach’s OS/390 and z/OS JCL
Murach’s Mainframe COBOL
Murach’s CICSforthe COBOL Programmer
DB2 for the COBOL Programmer, Part 1

© 2011, Mike Murach & Associates, Inc.


All rights reserved.

Printed in the United States of America

10 9 8 7 6 5 4 3 2 1
ISBN: 978-1-890774-65-3
Contents
Introduction XV

S ection 1 Essential Java skills


Chapter 1 How to get started with Java and NetBeans 3
Chapter 2 Introduction to Java programming 35
Chapter 3 How to work with data 79
Chapter 4 How to code control statements 111
Chapter 5 How to validate input data 145
Chapter 6 How to test and debug an application 167

S ection 2 O b ject-oriented program m ing w ith Java


Chapter 7 How to define and use classes 185
Chapter 8 How to work with inheritance 237
Chapter 9 How to work with interfaces 275
Chapter 10 Other object-oriented programming skills 311

S ection 3 M ore Jav a skills


Chapter 11 How to work with arrays 339
Chapter 12 How to work with collections and generics 363
Chapter 13 How to work with dates and strings 405
Chapter 14 How to handle exceptions 431

S ection 4 GUI program m ing w ith Swing


Chapter 15 How to develop a form 459
Chapter 16 How to work with controls and handle events 501
Chapter 17 How to develop and deploy applets 537

S ection 5 D ata access program m ing w ith Java


Chapter 18 How to work with text and binary files 559
Chapter 19 How to work with XML 613
Chapter 20 How to work with a Derby database 645
Chapter 21 How to use JDBC to work with a database 677

S ection 6 Advanced J ava skills


Chapter 22 How to work with threads 717
Chapter 23 How to deploy an application 751

A ppendixes
Appendix A How to set up your PC for this book 771
Appendix B How to set up your Mac for this book 111
E x p a n d e d c o n te n ts

Section 1 Essential Java skills


Chapter 1 How to get started with Java and NetBeans
Introduction to Java............................................................................. 4
Toolkits and platforms..................................................................................................... 4
How Java compares to C++ and C #................................................................................. 4
Applications, applets, and servlets.................................................................................. 6
The code for the console version of the Future Value application.................................. 8
How Java compiles and interprets code....................................................................... 10
Introduction to Java ID E s............................................................................................. 12
How to use NetBeans to work with existing projects................... 14
Introduction to Java projects and the NetBeans ID E ................................................... 14
How to open, close, and delete a project..................................................................... 16
How to compile and run a project................................................................................. 16
How to use the Output window with a console application........................................ 18
How to work with two or more projects........................................................................ 20
How to use NetBeans to develop new projects............................ 22
How to create a new project.......................................................................................... 22
How to set the Java version for a project....................................................................... 24
How to work with Java source code and files................................................................26
How to use the code completion feature........................................................................ 28
How to detect and correct syntax errors........................................................................ 30

Chapter 2 Introduction to Java programming


Basic coding skills............................................................................36
How to code statements................................................................................................. 36
How to code comments................................................................................................. 36
How to create identifiers.................................................................................................38
How to declare a class and a main method....................................................................40
How to work with numeric variables...............................................42
How to declare and initialize variables..........................................................................42
How to code assignment statements..............................................................................44
How to code arithmetic expressions..............................................................................44
How to work with string variables...................................................46
How to create a String object......................................................................................... 46
How to join and append strings..................................................................................... 46
How to include special characters in strings..................................................................48
How to use Java classes, objects, andmethods............................50
How to create objects and call methods........................................................................ 50
How to import Java classes............................................................................................ 52
How to use the API documentation to research Java classes........................................ 54
How to use the console for input and output................................ 56
How to use the System.out object to print output to the console................................. 56
How to use the Scanner class to read input from the console...................................... 58
Examples that get input from the console.....................................................................60
How to code simple control statements........................................ 62
How to compare numeric variables............................................................................... 62
How to compare string variables................................................................................... 62
How to code if/else statements...................................................................................... 64
How to code while statements....................................................................................... 66
Expanded contents V

Two illustrative applications............................................................. 68


The Invoice application.................................................................................................. 68
The Test Score application..............................................................................................70
How to test and debug an application............................................. 72
How to test an application..............................................................................................72
How to debug an application..........................................................................................72

Chapter 3 How to work with data


Basic skills for working with d a ta .................................................... 80
The eight primitive data types........................................................................................80
How to declare and initialize variables........................................................................ 82
How to declare and initialize constants....................................................................... 84
How to code assignment statements and arithmetic expressions.................................. 86
How to use the shortcut assignment operators...............................................................88
How to work with the order of precedence.................................................................... 90
How to work with casting...............................................................................................92
How to use Java classes for working with data typ es................... 94
How to use the NumberFormat class........................................................................... 94
How to use the Math class........................................................................................... 96
How to use the Integer and Double classes.................................................................98
The formatted Invoice application.................................................. 100
The code for the application....................................................................................... 100
A bug in the arithmetic............................................................................................... 102
How to debug the application..................................................................................... 102
How to use the BigDecimal class................................................... 104
The constructors and methods.................................................................................... 104
How to use BigDecimal arithmetic............................................................................. 106

Chapter 4 How to code control statements


How to code Boolean expressions................................................. 112
How to compare primitive data types......................................................................... 112
How to compare strings.............................................................................................. 114
How to use the logical operators................................................................................ 116
How to code if/else and switch statements................................... 118
How to code if/else statements................................................................................... 118
How to code switch statements................................................................................... 120
An enhanced version of the Invoice application......................................................... 124
How to code loops............................................................................126
How to code while and do-while loops...................................................................... 126
How to code for loops................................................................................................. 128
The Future Value application...................................................................................... 130
How to code nested loops........................................................................................... 132
How to code break and continue statements................................ 134
How to code break statements.................................................................................... 134
How to code continue statements.................................................................................136
How to code and call static methods............................................. 138
How to code static methods........................................................................................ 138
How to call static methods.......................................................................................... 138
The Future Value application with a static method..................................................... 140
Expanded contents

Chapter 5 How to validate input data


How to handle exceptions............................................................... 146
How exceptions w ork...................................................................................................146
How to catch exceptions............................................................................................. 148
The Future Value application with exception handling...............................................150
How to validate data......................................................................... 152
How to prevent exceptions from being thrown.......................................................... 152
How to validate a single entry................................................................................... 154
How to use generic methods to validate an entry...................................................... 156
The Future Value application with data validation........................158
The console................................................................................................................. 158
The co d e....................................................................................................................... 160

Chapter 6 How to test and debug an application


Basic skills for testing and debugging.......................................... 168
Typical test phases...................................................................................................... 168
The three types of errors............................................................................................. 168
Common Java errors.....................................................................................................170
A simple way to trace code execution....................................................................... 172
How to use NetBeans to debug an application.............................174
How to set and remove breakpoints........................................................................... 174
How to step through code........................................................................................... 176
How to inspect variables...............................................................................................176
How to inspect the stack trace.................................................................................... 178

Section 2 Object-oriented programming with Java

Chapter 7 How to define and use classes


An introduction to classes.............................................................. 186
How classes can be used to structure an application................................................. 186
How encapsulation works.............................................................................................188
The relationship between a class and its objects......................................................... 190
How to code a class that defines an object...................................192
How to use NetBeans to create a new class............................................................... 192
The code for the Product class.................................................................................... 194
How to code instance variables.................................................................................. 196
How to code constructors........................................................................................... 198
How to code m ethods.................................................................................................. 200
How to overload methods............................................................................................ 202
How to use the this keyword........................................................................................ 204
How to use NetBeans to work with classes.................................................................206
How to create and use an object....................................................208
How to create an object............................................................................................... 208
How to call the methods of an object.......................................................................... 210
How primitive types and reference types are passed to a method.............................. 212
A ProductDB class that creates a Product object........................................................214
A ProductApp class that uses a Product object...........................................................216
How to code and use static fields and methods...........................218
How to code static fields and methods........................................................................ 218
How to call static fields and methods.......................................................................... 220
How to code a static initialization block......................................................................222
When to use static fields and methods.........................................................................222
Expanded contents

The Line Item application................................................................ 224


The console...................................................................................................................224
The class diagrams....................................................................................................... 224
The code for the classes................................................................................................226

Chapter 8 How to work with inheritance


An introduction to inheritance........................................................ 238
How inheritance works.................................................................................................238
How the Java API uses inheritance.............................................................................. 240
How the Object class works......................................................................................... 242
How to use inheritance in your applications................................................................244
Basic skills for working with inheritance.......................................246
How to create a superclass........................................................................................... 246
How to create a subclass...............................................................................................248
How polymorphism works........................................................................................... 250
The Product application.................................................................. 252
The console...................................................................................................................252
The ProductApp class.................................................................................................. 254
The Product, Book, and Software classes.................................................................... 256
The ProductDB class....................................................................................................256
More skills for working with inheritance........................................260
How to get information about an object’s type............................................................260
How to cast objects...................................................................................................... 262
How to compare objects.............................................................................................. 264
How to work with the abstract and finalkeywords....................... 266
How to work with the abstract keyword...................................................................... 266
How to work with the final keyword......................................................................... 268

Chapter 9 How to work with interfaces


An introduction to interfaces.......................................................... 276
A simple interface.........................................................................................................276
Interfaces compared to abstract classes....................................................................... 278
Some interfaces of the Java A P I.................................................................................. 280
How to work with interfaces............................................................282
How to code an interface........................................................................................... 282
How to implement an interface.................................................................................... 284
How to inherit a class and implement an interface......................................................286
How to use an interface as a parameter..................................................................... 288
How to use inheritance with interfaces...................................................................... 290
How to use NetBeans to work with interfaces...........................................................292
A Product Maintenance application thatuses interfaces.............294
The class diagram.........................................................................................................294
The console...................................................................................................................296
The DAOFactory class..................................................................................................298
The ProductTextFile class............................................................................................ 298
The ProductMaintApp class........................................................................................ 300
How to implement the Cloneable interface...................................304
A Product class that implements the Cloneable interface...........................................304
A Lineltem class that implements the Cloneable interface........................................ 306
Viiî Expanded contents

Chapter 10 Other object-oriented programming skills


How to work with packages.............................................................312
An introduction to packages.........................................................................................312
How to use NetBeans to work with packages.............................................................. 314
How to use NetBeans to work with libraries................................................................316
How to use javadoc to document a package................................. 318
How to add javadoc comments to a class.....................................................................318
How to use HTML and javadoc tags in javadoc comments......................................... 320
How to use NetBeans to generate documentation....................................................... 322
How to view the documentation for a package............................................................ 322
How to code classes that are closely related................................ 324
How to code more than one class per file.....................................................................324
An introduction to nested classes.................................................................................326
How to work with enumerations..................................................... 328
How to declare an enumeration....................................................................................328
How to use an enumeration.......................................................................................... 328
How to enhance an enumeration...................................................................................330
How to work with static imports...................................................................................330

Section 3 More Java skills

Chapter 11 How to work with arrays


Basic skills for working with arrays............................................... 340
How to create an array.................................................................................................. 340
How to assign values to the elements of an array........................................................ 342
How to use for loops with arrays..................................................................................344
How to use enhanced for loops with arrays..................................................................346
More skills for working with arrays................................................ 348
The methods of the Arrays class................................................................................... 348
Code examples that work with the Arrays class.......................................................... 350
How to implement the Comparable interface.............................................................. 352
How to create a reference to an array...........................................................................354
How to copy an array.................................................................................................... 354
How to work with two-dimensional arrays.................................... 356
How to work with rectangular arrays...........................................................................356
How to work with jagged arrays................................................................................... 358

Chapter 12 How to work with collections and generics


An introduction to Java collections............................................... 364
A comparison of arrays and collections.......................................................................364
An overview of the Java collection framework............................................................366
An introduction to generics.......................................................................................... 368
How to use the ArrayList class....................................................... 370
The ArrayList class....................................................................................................... 370
Code examples that work with array lists.....................................................................372
An Invoice application that uses an array lis t............................... 374
An overview of the Invoice application........................................................................374
The code for the Invoice class......................................................................................376
The code for the InvoiceApp class...............................................................................378
Expanded contents ix

How to use the LinkedList class..................................................... 380


The LinkedList class..................................................................................................... 380
Code examples that work with linked lists...................................................................382
A class that uses a linked list to implement a generic queue....................................... 384
An enhanced version of the Invoice application........................... 386
An overview of the enhanced Invoice application....................................................... 386
The code for the InvoiceApp class...............................................................................388
How to work with m aps................................................................... 392
The HashMap and TreeMap classes.............................................................................392
Code examples that work with hash maps and tree m aps........................................... 394
How to work with legacy collections.............................................. 396
An introduction to legacy collection classes................................................................ 396
How to use an untyped collection.................................................................................398
How to use wrapper classes with untyped collections................................................. 400

Chapter 13 How to work with dates and strings


How to work with dates and tim es................................................. 406
How to use the GregorianCalendar class to set dates and times.................................. 406
How to use the Calendar and GregorianCalendar fields and methods........................408
How to use the Date class.............................................................................................410
How to use the DateFormat class to format dates and tim es....................................... 412
A DateUtils class that provides methods for handling dates....................................... 414
An Invoice class that includes an invoice date............................................................. 416
How to work with the String class.................................................. 418
Constructors of the String class....................................................................................418
Code examples that create strings.................................................................................418
Methods of the String class..........................................................................................420
Code examples that work with strings......................................................................... 422
How to work with the StringBuilder class..................................... 424
Constructors and methods of the StringBuilder class.................................................. 424
Code examples that work with the StringBuilder class............................................... 426

Chapter 14 How to handle exceptions


An introduction to exceptions........................................................ 432
The exception hierarchy...............................................................................................432
How exceptions are propagated....................................................................................434
How to work with exceptions.......................................................... 436
How to use the try statement........................................................................................ 436
How to use the try-with-resources statement............................................................... 438
How to use the methods of an exception..................................................................... 440
How to use a multi-catch block....................................................................................442
How to use the throws clause.......................................................................................444
How to use the throw statement....................................................................................446
How to work with custom exception classes................................ 448
How to create your own exception class.......................................................................448
How to use exception chaining.....................................................................................450
How to work with assertions........................................................... 452
How to code assert statements......................................................................................452
How to enable and disable assertions.......................................................................... 452
Expanded contents

Section 4 GUI programming with Swing


Chapter 15 How to develop a form
An introduction to S w ing.................................................................460
The user interface for the Future Value Calculator application................................... 460
The inheritance hierarchy for Swing components....................................................... 462
How to design a form........................................................................464
How to create a project for a GUI application...........................................................464
How to add a form to a project.................................................................................. 464
How to add controls to a form ................................................................................... 466
How to set properties.................................................................................................... 468
Common properties for forms and controls................................................................. 470
How to add code to a form .............................................................. 472
How to set the variable name for a control................................................................472
How to create an event handler for a control.............................................................474
How to rename or remove an event handler................................................................ 476
How to enter the code for a form..................................................................................478
Common methods for controls.....................................................................................480
How to display and center a form.................................................................................482
The code for the FutureValueFrame class................................................................... 484
How to validate Swing input data................................................... 486
How to display error messages.....................................................................................486
How to validate the data entered into a text field ........................................................ 488
The SwingValidator class............................................................................................. 490
How to validate multiple entries...................................................................................492
The Future Value application...........................................................494
The user interface......................................................................................................... 494
The co d e........................................................................................................................494

Chapter 16 How to work with controls and handle events


How to work with components........................................................502
How to work with text areas......................................................................................... 502
How to work with check boxes..................................................................................... 504
How to work with radio buttons...................................................................................506
How to work with combo boxes...................................................................................508
How to work with lists.................................................................................................. 510
The Payment application..................................................................514
The user interface......................................................................................................... 514
The co d e........................................................................................................................514
How to code low-level events..........................................................518
A summary of low-level events....................................................................................518
How to work with focus events....................................................................................520
How to work with keyboard events..............................................................................522
The Product Maintenance application........................................... 524
The user interface......................................................................................................... 524
The co d e........................................................................................................................526

Chapter 17 How to develop and deploy applets


An introduction to applets...............................................................538
The Future Value Calculator applet..............................................................................538
A brief history of applets.............................................................................................. 538
Applet security issues................................................................................................... 540
The inheritance hierarchy for applets...........................................................................542
Four methods of an applet............................................................................................ 542
Expanded contents XI

How to develop applets................................................................... 544


How to develop a panel for an applet.......................................................................... 544
How to code an applet..................................................................................................546
How to test an applet with the Applet Viewer............................................................. 546
How to deploy applets..................................................................... 548
A procedure for deploying an applet........................................................................... 548
How to create an HTML document for an applet........................................................ 550
How to run an applet within a web browser................................................................ 552

Section 5 Data access programming with Java


Chapter 18 How to work with text and binary files
Introduction to directories and files............................................... 560
A package for working with directories and files........................................................ 560
Code examples that work with directories and files....................................................562
Introduction to file input and output.............................................. 564
How files and streams work..........................................................................................564
A file I/O example........................................................................................................ 566
How to work with I/O exceptions.................................................................................568
How to work with text files .............................................................. 570
How to connect a character output stream to a file...................................................... 570
How to write to a text file .............................................................................................572
How to connect a character input stream to a file........................................................574
How to read from a text file..........................................................................................576
An interface for working with file I/O ......................................................................... 578
A class that works with a text file.................................................................................580
How to work with binary files.......................................................... 584
How to connect a binary output stream to a file.......................................................... 584
How to write to a binary file.........................................................................................586
How to connect a binary input stream to a file............................................................ 588
How to read from a binary file......................................................................................590
Two ways to work with binary strings......................................................................... 592
How to work with random-access files.......................................... 594
How to connect to a random-access file ...................................................................... 594
How to read to and write from a random-access file................................................... 596
How to read and write fixed-length strings.................................................................. 598
A class that works with a random-access file.............................................................. 600

Chapter 19 How to work with XML


Introduction to X M L ......................................................................... 614
An XML document.......................................................................................................614
XML tags, declarations, and comments...................................................................... 616
XML elements.............................................................................................................. 616
XML attributes.............................................................................................................. 618
An introduction to DTDs..............................................................................................620
How to view and edit an XML file.................................................... 622
How to view an XML file.............................................................................................622
How to edit an XML file...............................................................................................622
An introduction to three XML APIs................................................. 624
DOM ............................................................................................................................. 624
SA X .............................................................................................................................. 624
StAX............................................................................................................................. 624
xii Expanded, contents

How to use StAX to work with XML...............................................626


How to create an XMLStreamWriter object................................................................ 626
How to write X M L ....................................................................................................... 628
How to create an XMLStreamReader object............................................................... 630
How to read XML......................................................................................................... 632
A class that works with an XML file............................................................................636

Chapter 20 How to work with a Derby database


How a relational database is organized....................................... 646
How a table is organized............................................................................................... 646
How the tables in a database are related.......................................................................648
How the columns in a database are defined................................................................. 650
How to use SQL to work with the data in a database................. 652
How to query a single table..........................................................................................652
How to join data from two or more tables................................................................... 654
How to add, update, and delete data in a table............................................................ 656
An introduction to Derby................................................................658
An overview of D erby.................................................................................................. 658
How to configure your system to work with a Derby database...................................660
How to use the ij tool to work with a Derby database................ 662
How to start and stop the ij tool....................................................................................662
How to connect to and disconnect from a database..................................................... 662
How to create a database and connect to i t .................................................................. 664
How to run SQL statements....................................................................................... 664
How to run SQL scripts from the ij prompt...............................................................666
How to run SQL scripts from the command prompt.................................................668
How to start and stop the Derby database server...................... 670
How to start the server................................................................................................670
How to stop the server................................................................................................670
How to learn more about Derby.....................................................672
How to view the Derby documentation....................................................................... 672
How to navigate through the documentation............................................................... 672

Chapter 21 How to use JDBC to work with databases


An introduction to Java database drivers................................... 678
The four driver types..................................................................................................... 678
How to add a database driver to a project.................................................................... 680
How to use Java to connect to a database...................................682
How to load a database driver.......................................................................................682
How to connect to an embedded database................................................................... 684
How to disconnect from an embedded database.......................................................... 686
How to connect to a networked database..................................................................... 688
How to use Java to work with a database................................... 690
How to return a result set..............................................................................................690
How to move the cursor through a result s e t............................................................... 692
How to return data from a result s e t............................................................................ 694
How to modify data in a database.................................................................................696
How to work with prepared statements....................................................................... 698
Two classes for working with databases..................................... 700
A utility class for working with strings....................................................................... 700
A class that works with a database...............................................................................702
Expanded contents xiii

An introduction to working with metadata....................................708


How to work with metadata......................................................................................... 708
How SQL data types map to Java data types...............................................................710

Section 6 Advanced Java skills


Chapter 22 How to work with threads
An introduction to threads.............................................................. 718
How threads work.........................................................................................................718
Typical uses for threads............................................................................................... 718
Classes and interfaces for working with threads.........................................................720
The life cycle of a thread............................................................................................. 722
How to create threads...................................................................... 724
Constructors and methods of the Thread class............................................................724
How to create a thread by extending the Thread class................................................726
How to create a thread by implementing the Runnable interface............................... 728
How to manipulate threads............................................................. 730
How to set a thread’s priority....................................................................................... 730
How to interrupt a thread............................................................................................. 732
How to synchronize threads........................................................... 734
How to create synchronized threads............................................................................734
How to communicate among threads.......................................................................... 736
The Order Queue application..........................................................738
The operation................................................................................................................738
The classes....................................................................................................................740
The OrderQueueApp class........................................................................................... 742
The Order class.............................................................................................................742
The OrderTaker class................................................................................................... 744
The OrderHandler class............................................................................................... 746
The QrderQueue class................................................................................................. 746

Chapter 23 How to deploy an application


An introduction to deployment....................................................... 752
How executable JAR files work................................................................................... 752
How Java Web Start w orks.......................................................................................... 752
How an installer program works.................................................................................. 752
How to use an executable JAR file ................................................. 754
How to create an executable JAR file.......................................................................... 754
How to deploy a GUI application................................................................................ 756
How to deploy a console application........................................................................... 758
How to use Java Web Start.............................................................. 760
A procedure for using Java Web S tart......................................................................... 760
How to create a JNLP file............................................................................................ 762
How to create an HTML document that launches an application.............................. 764
How to deploy an application to a remote web server.................................................766
How to launch an application...................................................................................... 768
How to fix a common problem.................................................................................... 768
Introduction
Since its release in 1996, the Java language has established itself as one of
the leading languages for object-oriented programming. Today, Java continues
to be one of the most popular languages for application development, especially
for web applications and for mobile applications like Android apps. And that’s
going to continue for many years to come, for several reasons.
First, developers can obtain Java and a wide variety of tools for working
with Java for free. Second, Java code can run on any modem operating system.
Third, Java’s development has been guided largely by the Java community, and
Sun Microsystems released most of Java as open source software in 2007. As a
result, the Java platform is able to evolve according to the needs of the
programmers who use the language. Although Sun was acquired by Oracle
Corporation in 2010, Oracle has committed itself to supporting Java and the
Java community.

Who this book is for


This book is for anyone who wants to learn the core features of the Java
language. It works if you have no programming experience at all. It works if
you have programming experience with another language. It works if you
already know an older version of Java and you want to get up-to-speed with the
latest version. And it works if you’ve already read three or four other Java books
and still don’t know how to develop a real-world application.
If you’re completely new to programming, the prerequisites are minimal.
You just need to be familiar with the operation of the platform that you’re using.
If, for example, you’re developing programs using Windows on a PC, you
should know how to use Windows to perform tasks like opening, saving,
printing, closing, copying, and deleting files.

What version of Java this book supports


This book is designed to work with the Java Platform, Standard Edition 7
(Java SE 7) or later. This edition of Java includes the Java Development Kit
(JDK). For marketing reasons, Oracle sometimes refers to this version of the
JDK as JDK 7. However, from a developer’s point of view, this version of the
JDK is commonly referred to as version 1.7.
Introduction

As you work with Java SE 7, please keep in mind that all Java versions are
backwards-compatible. That means that everything in this book will also work
with future versions of the JDK.

What operating systems this book supports


The Oracle web site provides the most current version of the JDK for the
Windows, Linux, and Solaris operating systems. As this book goes to press, the
Mac OS X operating system includes JDK 1.6, and there are some unofficial
builds available for JDK 1.7. Before long, OS X will provide support for JDK
1.7. Until then, you can install an unofficial build as described in appendix B.
Since most Java development today is done under Windows, this book uses
Windows to illustrate any platform-dependent procedures. However, whenever
possible, we describe these procedures for other operating systems too. For
example, appendix B shows how to install the software for this book on Mac
OS X. However, if you’re using another platform such as Linux or Solaris, you
may need to search the Internet for more information about performing these
platform-dependent procedures. Fortunately, if you use NetBeans as described
in this book, there are very few platform-dependent procedures.

What IDE this book supports


This book shows you how to use the NetBeans IDE (Integrated
Development Environment) to code, test, and debug applications. Although
there are other excellent IDEs for working with Java, we decided to present
NetBeans because we think it’s the best IDE for getting started with Java. It’s
intuitive, easy to use, available for free, and it runs on all operating systems.
Even if you want to use another IDE such as Eclipse, we recommend that
you use NetBeans to work with the applications presented in this book. Then,
once you’re done with this book, it should be easy for you to switch from
NetBeans to another IDE. However, if you’d prefer to get started with another
IDE right away, you can do that too. But first, you’ll need to convert the
NetBeans projects that are available from our web site so you can work with
them in your preferred IDE.

How to get the software you need


You can download all of the software that you need for this book for free
from the Internet. To make that easier for you, appendix A shows how to
download and install the JDK as well as NetBeans on a PC. Similarly, appendix
B shows how to download and install the JDK, NetBeans, and Derby on a Mac.
That’s all the software you need to start developing professional Java
applications on your own.
Introduction XVII

What you’ll learn in this book


Unlike competing books, this one focuses on the practical features that
you’ll need for developing professional Java applications. Here’s a quick tour:
• In section 1, you’ll quickly master the basics of the Java language. In chapter
1, you’ll learn how to get started with NetBeans. In chapter 2, you’ll learn
how to write console applications that use the Scanner class to get input
from the user. By the end of chapter 5, you’ll know how to code applications
that use custom methods to validate user input so they won’t crash. And in
chapter 6, you’ll learn how to use NetBeans to thoroughly test and debug
your applications.
• In section 2, you’ll learn how to use Java for object-oriented programming.
In chapter 7, you’ll learn how to create and use your own classes, which is
the basis for developing applications that are easier to test, debug, and
maintain. Then, in chapters 8 through 10, you’ll learn how to develop more
sophisticated classes that use inheritance, interfaces, packages, type-safe
enumerations, and the factory pattern. In addition, you’ll learn how to use
the three-tiered architecture that’s the standard used by most professionals
for designing and developing object-oriented, database applications.
• In section 3, you’ll learn more of the core Java features that you’ll use all the
time. In chapters 11 through 14, for instance, you’ll learn how to work with
arrays, collections, dates, strings, and exceptions. Along the way, you’ll
learn how to use features such as enhanced for loops, typed collections,
generics, and the StringBuilder class. You’ll also learn how to use JDK 1.7
features such as the try-with-resources statement.
• In section 4, you’ll learn how to use a built-in tool provided by NetBeans to
develop graphical user interfaces (GUIs). We highly recommend this
approach for getting started with GUI programming. First, you’ll learn how
to use Swing components to develop real-world GUI applications that handle
events, validate data, and populate objects. Then, you’ll learn how to develop
applets, a special type of Java application that can be downloaded from the
Internet and run within a web browser.
• Because storing data is critical to most applications, section 5 shows you
how to store data in a file or database. In chapter 18, you’ll learn how to
work with text files and binary files, including random-access files. In
chapter 19, you’ll learn how to use an API known as StAX (the Streaming
API for XML) that was introduced with JDK 1.6 to work with XML
documents and files. In chapter 20, you’ll learn how to work with the open-
source Apache Derby database. And in chapter 21, you’ll learn how to use
JDBC to work with any database.
• In section 6, you’ll learn some advanced Java skills. In chapter 22, you’ll
learn how to use threads so your applications can perform two or more tasks
at the same time. Finally, in chapter 23, you’ll learn how to deploy your
finished applications using executable JAR files or Java Web Start.
XVÎii Introduction

Why you’ll learn faster and better with this book


Like all our books, this one has features that you won’t find in competing
books. That’s why we believe that you’ll learn faster and better with our book
than with any other. Here are just three of those features.
• To help you develop applications at a professional level, this book presents
complete, non-trivial applications. For example, chapter 16 presents a
Product Maintenance application that uses presentation classes, business
classes, and data access classes. You won’t find complete, real-world
applications like this in other Java books even though studying these types of
applications is the best way to master Java development.
• All of the information in this book is presented in our unique paired-pages
format, with the essential syntax, guidelines, and examples on the right page
and the perspective and extra explanation on the left page. This helps you
learn more while reading less, and it helps you quickly find the information
that you need when you use this book for reference.
• The exercises at the end of each chapter give you a chance to try out what
you’ve just learned. They guide you through the development of some of the
book’s applications, and they challenge you to apply what you’ve learned in
new ways. As a result, you’ll gain valuable, hands-on experience in Java
programming that will build both your skills and your confidence.

How our downloadable files make learning easier


To make learning easier, you can download the source code for all the
applications presented in this book from our web site (www.murach.com). This
source code includes the files and databases required by these applications.
Then, you can view the complete code for these applications as you read each
chapter; you can run these applications to see how they work; and you can copy
portions of code for use in your own applications.
You can also download the source code that you need for doing the
exercises in this book. That way, you don’t have to start every exercise from
scratch. This takes the busywork out of doing these exercises so you can get
more practice in less time. For more information about these downloads, please
see appendix A (Windows) and appendix B (Mac OS X).
Introduction

Support materials for trainers and instructors


If you’re a corporate trainer or a college instructor who would like to use
this book for a course, we offer an Instructor’s CD that includes: (1) a complete
set of PowerPoint slides that you can use to review and reinforce the content of
the book; (2) instructional objectives that describe the skills a student should
have upon completion of each chapter; (3) the solutions to the exercises in this
book; (4) projects that the students start from scratch; (5) solutions to those
projects; and (6) test banks that measure mastery of those skills.
To learn more about this Instructor’s CD and to find out how to get it, please
go to our web site at www.murach.com and click the Trainers link or Instructors
link. Or, if you prefer, you can call Kelly at 1-800-221-5528 or send an email to
kellv @murach.com.

A companion book for web developers


Since web programming is one of the primary uses of Java, we also offer a
book on web programming called Murach’s Java Servlets and JSP. It shows you
how to use Java servlets and JavaServer Pages as you develop professional web
applications. As you read that book, you’ll discover that Java web programming
requires most of the skills that are presented in sections 1-3 of this book. That’s
why we see this book as the perfect companion for Murach ’s Java Servlets and
JSP.

Please let us know how this book works for you


When we started the first edition of this book, our goals were (1) to teach
you Java as quickly and easily as possible and (2) to teach you the practical Java
concepts and skills that you need for developing real-world business
applications. We’ve tried to improve on that with each subsequent edition, and
as this fourth edition goes to press, we hope that the book is more effective than
ever before. Many of the improvements have come from the feedback we’ve
received from our readers, so if you have any comments about this book, we
would appreciate hearing from you at murachbooks @murach.com.
Thanks for buying this book. We hope you enjoy reading it, and we wish
you great success with your Java programming.

Joel Murach Anne Boehm


Author Editor
Section 1

Essential Java skills


This section gets you started quickly with Java programming. First,
chapter 1 introduces you to Java applications and shows you how to use
NetBeans to work with Java projects. Then, chapter 2 introduces you to the
basic skills that you need for developing Java applications. When you
complete these chapters, you’ll be able to write, test, and debug simple
applications of your own.
After that, chapter 3 presents the details for working with numeric
data. Chapter 4 presents the details for coding control statements. Chapter
5 shows how to validate the data that’s entered by the user. And chapter 6
shows how to thoroughly test and debug an application. These are the
essential skills that you’ll use in almost every Java application that you
develop. When you finish these chapters, you’ll be able to write solid
programs of your own. And you’ll have the background that you need for
learning how to develop object-oriented programs.
1

How to get started


with Java and NetBeans
Before you can begin learning the Java language, you need to install Java. In
addition, you need to choose an IDE or a text editor for working with Java. For
this book, we recommend that you use the NetBeans IDE. Appendix A of this
book shows you how to install both Java and NetBeans on a Windows system,
and appendix B shows you how to install them on a Macintosh OS X system.
Then, this chapter shows how to use the NetBeans IDE to create and work with
a Java application. But first, this chapter presents some background information
about Java.

Introduction to Java ................................................................ 4


Toolkits and platforms...................................................................................... 4
How Java compares to C++ and C # .................................................................4
Applications, applets, and servlets................................................................... 6
The code for the console version of the Future Value application...................8
How Java compiles and interprets code.......................................................... 10
Introduction to Java ID Es................................................................................12
How to use NetBeans to work with existing projects...... 14
Introduction to Java projects and the NetBeans IDE......................................14
How to open, close, and delete a project........................................................ 16
How to compile and run a project.................................................................. 16
How to use the Output window with a console application...........................18
How to work with two or more projects.........................................................20
How to use NetBeans to develop new projects.................. 22
How to create a new project........................................................................... 22
How to set the Java version for a project........................................................24
How to work with Java source code and file s................................................26
How to use the code completion feature........................................................28
How to detect and correct syntax errors.........................................................30
Perspective............................................................................. 32
Section 1 Essential Java skills

Introduction to Java
In 1996, Sun Microsystems released a new programming language called
Java. Although Oracle bought Sun in 2010, Java remains one of the most widely
used object-oriented programming languages.

Toolkits and platforms


Figure 1-1 describes all major releases of Java starting with version 1.0 and
ending with version 1.7. Throughout Java’s history, the terms Java Development
Kit (JDK) and Software Development Kit (SDK) have been used to describe the
Java toolkit. In this book, we’ll use the term JDK since it’s the most current and
commonly used term. In addition, different numbering schemes have been used
to indicate the version of Java. For example, Java 5.0 and Java 6 refer to ver­
sions 1.5 and 1.6 of Java. In this book, we’ll use the 1.x style of numbering
since this numbering is used by the documentation for Java.
With versions 1.2 through 1.5 of the JDK, the Standard Edition (SE) of Java
was known as Java 2 Platform, Standard Edition (J2SE), and the Enterprise
Edition (EE) was known as the Java 2 Platform, Enterprise Edition (J2EE).
Since version 1.6 of the JDK, the Standard Edition of Java has been known as
Java SE, and the Enterprise Edition is known as Java EE. This book shows how
to use Java SE 7, but it should also work for earlier and future versions of Java.
That includes Java SE 8, which is scheduled for release in late 2012.

How Java compares to C++ and C#


When Sun’s developers created Java, they tried to keep the syntax for Java
similar to the syntax for C++ so it would be easy for C++ programmers to learn
Java. In addition, they designed Java so its applications can be run on any
computer platform. In contrast, C++ needs to have a specific compiler for each
platform. Java was also designed to automatically handle many operations
involving the creation and destruction of memory. This is a key reason why it’s
easier to develop programs and write bug-free code with Java than with C++.
To provide these features, the developers of Java had to sacrifice some
speed (or performance) when compared to C++. For many types of applications,
however, Java’s relative slowness is not an issue.
Microsoft’s Visual C# language is similar to Java in many ways. Like Java,
C# uses a syntax that’s similar to C++ and that automatically handles memory
operations. However, in practice, C# code only runs on Windows. Because of
that, C# is a good choice for developing applications for a Windows-only
environment. However, Java is a better choice if you need to develop cross­
platform applications.
Chapter 1 How to get started with Java and NetBeans

Java timeline
Year Month Event
1996 January Sun releases Java Development Kit 1.0 (JDK 1.0).
1997 February Sun releases Java Development Kit 1.1 (JDK 1.1).
1998 December Sun releases the Java 2 Platform with version 1.2
of the Software Development Kit (SDK 1.2).
1999 August Sun releases Java 2 Platform, Standard Edition (J2SE).
December Sun releases Java 2 Platform, Enterprise Edition (J2EE).
2000 May Sun releases J2SE with version 1.3 of the SDK.
2002 February Sun releases J2SE with version 1.4 of the SDK.
2004 September Sun releases J2SE 5.0 with version 1.5 of the JDK.
2006 December Sun releases Java SE 6 with version 1.6 of the JDK.
2010 April Oracle buys Sun.
2011 July Oracle releases Java SE 7 with version 1.7 of the JDK.

Operating systems supported by Java


Windows (XP, Vista, 7)
Linux
Solaris
Macintosh OS X

Java compared to C++ and C#


Feature Description
Syntax Java syntax is similar to C++ and C# syntax.
Platforms Compiled Java code can be run on any platform that has a Java
interpreter. Similarly, compiled C# code (MSIL) can be run on any
system that has the appropriate interpreter. Currently, only
Windows has an interpreter for MSIL. C++ code must be compiled
once for each type of system that it is going to be run on.
Speed C++ and C# run faster than Java, but Java is getting faster with
each new version.
Memory Both Java and C# handle most memory operations automatically,
while C++ programmers must write code that manages memory.

Description
• Versions 1.2 through 1.4 of Java are called the Software Development Kit (SDK).
• Versions 1.5 through 1.7 of Java are called the Java Development Kit (JDK).

Note
• Java SE 8 with version 1.8 of the JDK is expected to be released late in 2012.

Figure 1-1 Introduction to Java


Section 1 Essential Java skills

Applications, applets, and servlets


Figure 1-2 describes the three types of programs that you can create with
Java. First, you can use Java to create applications that run directly on your
computer. These are also known as desktop applications.
When you create these desktop applications, you can use a graphical user
interface (GUI) to get user input and perform a calculation as shown at the top
left of this figure. In chapter 15, you’ll learn how to create these types of applica­
tions. Until then, you’ll learn how to create another type of desktop application
known as a console application. This type of application runs in the console, or
command prompt, that’s available from your operating system. An example of a
console application is shown at the top right of this figure.
One of the unique characteristics of Java is that you can use it to create a
special type of web-based application known as an applet. For instance, this
figure shows an applet that works the same way as the applications above it. The
main difference between an application and an applet is that an applet can be
stored in an HTML page and can run inside a Java-enabled browser. As a result,
you can distribute applets via the Internet or an intranet. In chapter 17, you’ll
learn how to create and deploy applets.
Although applets can be useful for creating a complex user interface within a
browser, they have their limitations. First, you usually need to install a plug-in on
each client machine, which isn’t ideal for some types of applications. Second,
since an applet runs within a browser on the client, it’s not ideal for working with
resources that run on the server, such as enterprise databases.
To provide access to enterprise databases, many developers use Java EE to
create applications that are based on servlets. A servlet is a special type of Java
application that runs on the server and can be called by a client, which is usually
a web browser. This is also illustrated in this figure. Here, you can see that the
servlet works much the same way as the applet. The main difference is that the
code for the application runs on the server.
When a web browser calls a servlet, the servlet performs its task and returns
the result to the browser, typically in the form of an HTML page. For example,
suppose a browser requests a servlet that displays all unprocessed invoices that
are stored in a database. Then, when the servlet is executed, it reads data from the
database, formats that data within an HTML page, and returns the HTML page to
the browser.
When you create a servlet-based application like the one shown here, all the
processing takes place on the server and only HTML is returned to the browser.
That means that anyone with an Internet or intranet connection, a web browser,
and adequate security clearance can access and run a servlet-based application.
Because of that, you don’t need to install any special software on the client.
To make it easy to store the results of a servlet within an HTML page, the
Java EE specification provides for JavaServer Pages (JSPs). Most developers use
JSPs together with servlets when developing server-side Java applications.
Although servlets and JSPs aren’t presented in this book, we cover this topic in a
companion book, Murach’s Java Servlets and JSP. For more information about
this book, please visit our web site at www.murach.com.
Chapter 1 How to get started with Java and NetBeans

A GUI application and a console application


A d m in is tr a to r : C o m m a n d P ro m p t - ja v a F u tu re V a lu e A p p

icrosoft Windows [Version 6.1.7600]


opyright Cc> 2009 Microsoft Corporation, fill right
I&-I Future Value Calculator C:\UsersSftnne.murach>cd \murach\jaua\classes

C:Smurach\jaua\classes>java Futurellalueflpp
Monthly Payment: 1100

Uelcome to the Future Value Calculator


Yearly Interest Rater 3
Enter monthly inuestment: 100
Number of Years: [3 nter yearly interest rate: 3
nter number of years: 3
Future Value: $3,771.46 Future ualue: $3,771.46

Continue? <y/n>:
Calculate Exit

An applet
M ike Murach and Associates - Publisher o f Professional Program m ing Books - M ozilla Firefox

r
File Edit View

- c
H isto ry .Bookmarks

& □
Tools Help

h tt p ://w w w , m u rach.c 0 m /fv /a pp Iet-'in d ex. h tm I

□ Mil
M ike Murach and Associates - Publish...
_L·

A servlet
M ike Murach and Associates - Publisher o f Professional Program m ing Books - M ozilla Firefox

File Edit View H isto iy jjo o km a rks Tools Help

e ’ G & □ http://w w w .m urach .com /servlet/m u ra ch.fv.F utu re V a lu eS e ivle t * | |ÎJ ’ Google P

□ M ike M urach and Associates - Publish... [ <■ |

Figure 1-2 Applications, applets, and servlets


Section 1 Essential Java skills

The code for the console version


of the Future Value application
To give you an idea of how the code for a Java application works, figure 1-3
presents the code for the console version of the Future Value application that
you saw in figure 1-2.
If you have experience with other programming languages, you may be able
to understand much of this code already. If not, don’t worry! You’ll learn how
all of this code works in the next few chapters. For now, here’s a brief explana­
tion of this code.
Most of the code for this application is stored in a class named
FutureValueApp. This class begins with an opening brace ({) and ends with a
closing brace (}). Within this class, two methods are defined. These methods
also begin with an opening brace and end with a closing brace, and they are
indented to clearly show that they are contained within the class.
The first method, named main, is the main method for the application. The
code within this method is executed automatically when you run the application.
In this case, the code displays the data the user sees on the console, accepts the
data the user enters at the console, and calculates the future value.
The second method is named calculateFutureValue. This method is called
from the main method and calculates the future value based on the data the user
enters.
Chapter 1 How to get started with Java and NetBeans

The code for the Future Value application


import java.util.Scanner;
import java.text.NumberFormat;

public class FutureValueApp


{
public static void main(String[] args)
{
Systern.out.println("\nWelcome to the Future Value Calculator\n");

Scanner sc = new Scanner(System.in);


String choice = "y";

while (choice.equalsIgnoreCase(■y"))
{
// get the input from the user
System.out.print("Enter monthly investment: ");
double monthlylnvestment = sc.nextDouble();
System.out.print("Enter yearly interest rate: ");
double interestRate = sc.nextDouble();
System.out.print("Enter number of years: ");
int years = sc.nextlnt();

// calculate the future value


double monthlylnterestRate = interestRate/12/100;
int months = years * 12;
double futureValue = calculateFutureValue(
monthlylnvestment, monthlylnterestRate, months);

// format and display the result


NumberFormat currency = NumberFormat.getCurrencylnstance();
System.out.printIn("Future value: " +
currency.format(futureValue) + "\n");

// see if the user wants to continue


System.out.print("Continue? (y/n): ");
choice = sc.next();
System.out.printlnO ;
}
}
private static double calculateFutureValue(double monthlylnvestment,
double monthlylnterestRate, int months)
{
double futureValue = 0 ;
for (int i = 1; i <= months; i++)
futureValue = (futureValue + monthlylnvestment) *
(1 + monthlylnterestRate);
return futureValue;
}
}

Figure 1-3 The code for the console version of the Future Value application
Section 1 Essential Java skills

How Java compiles and interprets code


When you develop a Java application, you create one or more classes. For
each class, you write the Java statements that direct the operation of the class.
Then, you use a Java tool to translate the Java statements into instructions that
can be run by the computer. This process is illustrated in figure 1-4.
To start, you enter and edit the Java source code for a class. These are the
Java statements like the ones you saw in figure 1-3 that tell the application what
to do. Then, you use the Java compiler to compile the source code into a format
known as Java bytecodes. At this point, the bytecodes can be run on any plat­
form that has a Java interpreter to interpret (or translate) the Java bytecodes
into code that can be understood by the underlying operating system.
Since Java interpreters are available for all major operating systems, you
can run Java on most platforms. This is what gives Java applications their
platform independence. In contrast, C++ requires a specific compiler for each
type of platform that its programs are going to run on. When a platform has a
Java interpreter installed on it, it can be considered an implementation of a Java
virtual machine (JVM).
In addition, most modem web browsers can be Java enabled. This allows
applets, which are bytecodes that are downloaded from the Internet or an
intranet, to run within a web browser. To make this work, Sun developed (and
Oracle now maintains) the Java Plug-in. This piece of software is similar to
other browser plug-ins such as Apple QuickTime. It allows the browser to run
the current version of the Java interpreter. You’ll learn more about this in
chapter 17.
Chapter 1 How to get started with Java and NetBeans

How Java compiles and interprets code

Java IDE
W source code
Text editor (*.java files)

Java c<>mpiler |

1r

Java virtual machine


(JVM)
1 Operating system |
Java interpreter

Description
• When you develop a Java application, you develop one or more classes.
• You can use a Java IDE or any text editor to create, edit, and save the source code
for a Java class. Source code files have the java extension.
• The Java compiler translates Java source code into a platform-independent format
known as Java bytecodes. Files that contain Java bytecodes have the class exten­
sion.
• The Java interpreter executes Java bytecodes. Since Java interpreters exist for all
major operating systems, Java bytecodes can be run on most platforms. A Java
interpreter is an implementation of a Java virtual machine (JVM).
• Most modem web browsers can be Java enabled. This lets applets run within these
browsers. Oracle provides a tool known as the Java Plug-in that allows you to
specify the version of the Java interpreter that you want to use.

Figure 1-4 How Java compiles and interprets code


Section 1 Essential Java skills

Introduction to Java IDEs


To develop Java applications, you typically use an Integrated Development
Environment (IDE). Although you can use a simple text editor, an IDE provides
features that can make developing Java applications considerably easier. Figure
1-5 describes some of the features of the most popular IDEs.
Note that all of the IDEs listed in this figure are either free or have a free
edition. That makes them particularly attractive to students as well as program­
mers who are learning on their own. Most of these IDEs also run on all modem
operating systems.
The first two IDEs listed in this figure, NetBeans and Eclipse, are arguably
the two most popular Java IDEs. Both of these IDEs provide all of the features
listed in this figure. For example, both of these IDEs help you complete your
code and notify you of potential compile-time errors. They both automatically
compile your code before you run it. And they both include a debugger that lets
you perform standard debugging functions like setting breakpoints, stepping
through code, and viewing the values of variables.
The default installation of NetBeans also provides a feature for building
graphical user interfaces (GUIs). To use this GUI builder, you can drag controls
onto a form on the design surface. Then, you can move, size, and align the
controls and set properties of the controls that determine how they look. As you
do this, the code that displays the GUI is automatically generated. Finally, you
can generate event handlers for the events that you want to handle and then
write the code that handles these events.
On the other hand, the default installation of Eclipse does not provide a GUI
builder. However, several free GUI builder plug-ins are available for Eclipse.
These GUI builders provide features similar to the GUI builder that’s provided
by NetBeans.
The last three IDEs listed in this figure aren’t as popular as NetBeans and
Eclipse. However, we have included them here to give you an idea of the wide
range of IDE choices that are available for Java. In addition, other Java IDEs are
available that aren’t included here.
For this book, we recommend using NetBeans because we think it’s more
intuitive and easier to use than Eclipse, especially for beginners. Once you’re
done with this book, you can switch to whatever IDE you prefer. Fortunately,
once you learn how to use one IDE, it’s fairly easy to learn to use another one.
Chapter 1 How to get started with Java and NetBeans

Popular Java IDEs


IDE Description
NetBeans A free, open-source IDE that runs on most modem operating systems.
Eclipse A free, open-source IDE that runs on most modem operating systems.
IntelUJ IDEA The Community Edition of this IDE is a free, open-source IDE that
runs on most modem operating systems.
JCreator LE The Lite Edition (LE) of this IDE is free, but the code is not open-
source, and it only runs on Windows.
BlueJ A free IDE that’s designed for teaching Java to first-year students and
runs on most modem operating systems.

Features provided by most IDEs


• A code editor with code completion and error detection.
• Automatic compilation of classes when you run the application.
• A debugger that lets you set breakpoints, step through code, and view the values of
active variables.
• A GUI builder that lets you create graphical user interfaces by dragging controls
onto a form, setting properties, and writing code that handles the events that are
triggered when a user interacts with the form.

Description
• To develop Java applications, you typically use an Integrated Development Envi­
ronment (IDE) like those listed above. All of these IDEs are either free or have free
editions.

Figure 1-5 Introduction to Java IDEs


Section 1 Essential Java skills

How to use NetBeans


to work with existing projects
Now that you have some background information about Java, you’re ready
to start working with existing NetBeans projects. In particular, you’re ready to
learn how to open and run any of the applications for this book. You can
download these applications from our web site as described in appendix A
(Windows) or appendix B (Mac OS X).

Introduction to Java projects


and the NetBeans IDE
Figure 1-6 shows the NetBeans IDE with an open Java project. In
NetBeans, a project is a folder that contains all the files for an application. In
this example, the project is named ch02_Invoice.
In the Projects window, you can see that the folder for the ch02_Invoice
project contains two subfolders. The first one, named Source Packages, contains
the source files for the application. The second one, named Libraries, contains
the Java libraries that are used by the application. In this case, the application
uses just the JDK 1.7 libraries, but you can add others.
Within the Source Packages folder, the source files can be organized into
packages. In this case, no package was specified for the project, so the default
package is used. When you develop simple applications like the one shown
here, that’s usually acceptable. For more complex applications, though, you’ll
want to use two or more packages as shown in chapter 10.
The application shown here consists of a single source file named
InvoiceApp.java. You can see part of this file in the NetBeans code editor. You’ll
learn more about working with this code editor later in this chapter. For now, I
just want to point out that this file defines a single class. Because this class
contains the main method for the application, it’s called the main class. When
you run an application, the main method in the main class is executed by
default.
Another Random Document on
Scribd Without Any Related Topics
ungovernable. The Mediterranean, Italy, Rome, blue skies and
classical cities,—what are they all to me?
Give me back one hour of Scotland;
Let me see it ere I die.

They conveyed him back by slow stages, seeing this and that
continental sight on his homeward-route, but hardly knowing what
he saw. He was in London again for a week or two in June and July
1832, attended medically in a hotel in Jermyn Street. Brought thence
by sea to Edinburgh, he passed a night, a day, and another night, in a
hotel in St. Andrew Square, in a state of utter unconsciousness; and
on the 11th of July they took him to Abbotsford. On their way thither
through the old familiar scenery he began to recognise places and
objects, and to mutter their names,—Gala Water, Buckholm,
Torwoodlee; and, when they approached Abbotsford itself, and he
caught sight of its towers, he sprang up in such a state of excitement
that they could hardly hold him in the carriage. “Ha! Willie Laidlaw!
O man, I have often thought of you,” were his first words, after his
old friend and amanuensis Laidlaw, who was waiting in the porch,
had assisted the rest in carrying him into the house, and seating him
in a chair in the dining-room. The return of consciousness which this
recognition signified became more and more marked, at least at
intervals, in the two months and ten days through which he still
lingered. He talked with those of his family who were about him,
could be shifted from room to room or even wheeled in a Bath chair
through parts of his grounds, and could listen to readings and seem
to take an interest in them. Once he insisted on being placed at his
writing-table, with paper, pens, and ink before him in the
accustomed order, and wanted to be left to himself; but, when the
pen had been put into his hand and his fingers refused to hold it,
tears trickled down his cheeks, and he gave up the attempt. There
were, as often in such cases of brain-paralysis, some days of almost
frantic vehemence, when it was painful to be near him; but these
were succeeded by a feeble quietude and a gradual ebbing-away of
life. On the 21st of September 1832, with the ripple of the Tweed
heard by those who stood round his bed, Sir Walter Scott, then only
in the sixty-second year of his age, breathed his last.
In the Diary itself the narrative of those closing years of Scott’s
life is broken short at the point where they were bringing him back
from Italy as a dying invalid. The last few months are a total blank in
the Diary; where, indeed, the entries for the later years of the
included seven are scantier and more intermittent than those for the
earlier. But it is not solely as an exact autobiographic record of the
incidents of so many memorable years of a memorable life that the
Diary is now of interest. Implicated in that main interest, and
catching the attention of the reader again and again as he advances
through the pages, are certain recurring particular informations as to
Scott’s character and ways which possess an independent interest,
and may be reverted to separately.
Bound up, for example, with the proofs furnished by the Diary of
Scott’s prodigious literary industry, there is plenty of minute
information as to his habits of composition and his rate of
composition. I do not like that word “composition” in any such
application, thinking it a miserable word for the description of the
process by which a great writer marshals the contents of his mind
and commits them to paper; but the word is current, and may serve
for the nonce. Well, Scott’s rate of composition was about the fastest
known in the history of literature. Of all his predecessors in the
literary history of the British Islands, Shakespeare seems to have
been the likest to him in this particular of fluent facility and swiftness
of production. “His mind and hand went together,” is the well-known
report concerning Shakespeare by his literary executors and editors:
“his mind and hand went together, and what he thought he uttered
with that easiness that we have scarce received from him a blot in his
papers.” One has an impression, however, that Shakespeare, with all
his facility when he had the pen in his hand, had it less constantly in
his hand, was less “eident” in the use of it (as our good northern
phrase goes), than Scott,—whether because he had less actual need
to be “eident,” or because verse, which was Shakespeare’s main
element, is intrinsically more difficult, takes more out of a man in a
given time, and so is less favourable to “eidency,” than the prose
element in which, latterly, Scott worked all but exclusively. At all
events, “eidency” and “facility” taken together, the result, in the mere
matter of quantity, was larger from Scott’s industry than from
Shakespeare’s. But it is with the “facility” that we are now concerned,
and with the proofs of this “facility” which are furnished by the
Journal in particular. The mere look of the handwriting is one of
these,—that rapid currente calamo look, without hesitation, and with
hardly an erasure, stoppage to point, or any such thing, and with the
words almost running into each other in their hurry, which is
familiar to all who have seen facsimile reproductions of any portions
of the copy of Scott’s novels, when they were written with his own
hand, and not dictated. That, however, is a characteristic common to
all his writings; and the specific interest of the Diary in this
connection is that it gives us definite information as to the amount of
writing per day which Scott usually got through in his currente
calamo style. In entry after entry there is note of the number of
pages he had prescribed to himself as a sufficient day’s “task” or
“darg,” with growls when for any reason he had fallen short of it, and
smiles of satisfaction when he had exceeded it; and from one entry
we ascertain that his maximum per day when he was in good vein
was eight pages of his own close manuscript, making forty pages of
the usual type in which his copy was set up by the printers. One can
compute the difference between that rate and any other rate of which
one may happen to have knowledge or experience; but there is no
need to conclude that Scott’s rate is to be passionately desired or
universally aimed at, or that, because it suited Scott, it would suit
others. On the contrary, one sees some disadvantages, even in Scott’s
own case, counterbalancing the advantages of such extreme rapidity.
He was aware of the fact himself; and he once quotes, with some
approbation, an admirable maxim of Chaucer on the subject:—
“There n’ is no werkman, whatsoever he be,
That may both werken well and hastily.”

That Scott was an exception,—that he was, like Shakespeare, one of


those workmen who could work both well and hastily,—was owing
doubtless to the fact that, in this also resembling Shakespeare, he
brought always to the act of writing a mind already full of matter,
and of the very kinds of matter required for his occasions. One has
but to recollect the extraordinary range and variety of his readings
from his earliest youth, the extraordinary range and variety also of
his observations of men and manners, and the extraordinary
retentiveness of his memory, to see that never since he had begun
authorship could he have had to spin, as so many have to do, the
threads of his ideas or imaginations out of a vacuum. At the same
time, and this notwithstanding, there is something more to be said,
when the comparison is between Scott as an exceptionally rapid
worker and Shakespeare as the same. Scott had a standard of the
kind of matter that would answer for the purposes of his literary
productions; and, though a very good standard, it was lower than
Shakespeare’s standard for his writings. When Shakespeare was in
the act of writing, or was meditating his themes by himself in the
solitude of his chamber, or in his walks over the fields, before he
proceeded to the act of writing, we see his mind rolling within itself,
like a great sea-wash that would rush through all the deeps and
caverns, and search through all the intricacies, of its prior structure
and acquisitions,—so ruled and commissioned, however, that what
the reflux should fetch back for use should not be any wreckage
whatsoever that might be commonly relevant and interesting, but
only things of gleaming worth and rarity, presentable indeed to all,
but appreciable in full only by kings and sages. Hear, on the other
hand, in Scott’s own words, the definition of what satisfied him in his
dealings with the public. “I am sensible,” he wrote, “that, if there be
anything good about my poetry, or prose either, it is a hurried
frankness of composition which pleases soldiers, sailors, and young
people of bold and active disposition.” That Scott was grossly unfair
to himself in this under-estimate will be the verdict now of universal
opinion; and I shall have to touch again upon that point presently.
Meanwhile there is one other difference to be noted between the two
men in respect of that very circumstance of their marked similarity
in one characteristic which has led us to view them together.
Shakespeare’s boundless ease and fluency in writing did not prevent
perfection in his literary execution. His grammar, with all its
impetuosity and lightness of spring, is logical and accurate to the
utmost demands of the most fastidious English scholarship; and,
though he would have repudiated with scorn the name “stylist,”
invented of late as a title of literary honour by some of our critics,
and it would be profane to think of him under that execrable and
disastrous appellation, he wrote always with the sure cunning of a
disciplined artist in verbal expression,—an artist so highly self-
disciplined that his art in such matters had become an instinct.
Scott’s habitual style, on the other hand,—his style when he is not
strongly moved either by vehement feeling or by high poetic
conception,—is a kind of homely and comfortable slipshod,
neglectful of any rule of extreme accuracy, and careless even of the
most obvious grammatical solecisms. It is not exactly with reference
to this difference between himself and Shakespeare that there occurs
in one passage in his Diary a protest against being compared with
Shakespeare at all. But the protest is worth quoting. “Like
Shakespeare!” he exclaims, noticing the already formed habit of this
perilous comparison among his most ardent admirers in his own
lifetime,—“like Shakespeare! Not fit to tie his brogues!” It was the
superlative of compliment on Scott’s side; but its very wording may
be construed into a certain significance in connection with that point
of dissimilarity between the two men to which I have just adverted.
Shakespeare never wore “brogues.” In our present metaphorical
sense, I mean; in the literal sense, I would not be sure but he may
have found such articles convenient quite as often as Scott did. There
were muddy roads about Stratford-on-Avon as well as about
Abbotsford.
It would be wrong not to mention, however briefly, the
confirmation furnished by the Journal of all our previous
impressions of Scott’s high excellence among his fellow-men, not
only in the general virtues of integrity, honour, courage, and
persevering industry, but also in all those virtues which constitute
what we call in a more particular sense goodness. “Great and good”
is one of our common alliterative phrases; and it is a phrase which
we seem to require when we would characterise the kind of human
being that is entitled to supreme admiration. We feel that either
adjective by itself would be inadequate in such a case, but that the
doubling suffices. Another of our alliterative phrases, nearly the
same in meaning at root, is “head and heart.” Only when there is a
conjunction in a human being of what we call “heart” with what we
call “intellect” are we quite satisfied even in cases of ordinary
experience; and only when there is the conjunction of “great heart”
with “great intellect” do we bow down with absolute veneration
before this man or that man of historical celebrity. Common and
simple though this word “heart” is, there is a world of unused
applicability in it yet in many directions. In the criticism of literature,
for example, it supplies a test that would make havoc with some high
reputations. There have been, and are, writers of the most
indubitable ability, and of every variety of ability, in whose writings,
if you search them through and through, though you may find
instruction in abundance, novelties of thought in abundance, and
amusement in abundance, you will find very little of real “heart.”
There is no such disappointment when you turn to Scott.
Benevolence, charitableness, tolerance, sympathy with those about
him in their joys and their sorrows, kindly readiness to serve others
when he could, utter absence of envy or real ill-will,—these are
qualities that shine out everywhere in his life and in the succession of
his writings, and that receive, though they hardly need, additional
and more intimate illustration in his Journal. Positively, when I
contemplate this richness of heart in Scott, and remember also how
free he was all through his life from those moral weaknesses which
sometimes accompany and disfigure an unusually rich endowment in
this species of excellence,—for, born though he was in an old Scottish
age of roughish habits and not over-squeamish speech, and carrying
though he did the strong Scottish build of that age, and somewhat of
its unabashed joviality, to the very last, his life was exemplary
throughout in most particulars of personal conduct,—positively, I
say, with all this in my mind, I can express my feeling about Scott no
otherwise than by declaring him to have been one of the very best
men that ever breathed.
Of the interest of the miscellaneous contents of the book, as
including individual incidents in Scott’s life, sketches of the
physiognomies and characters of his Edinburgh contemporaries and
London contemporaries, descriptions of scenes and places, curious
Scottish and other anecdotes, literary criticisms, and expressions of
Scott’s opinions on public questions and on men and things in
general, no adequate idea can be formed except from itself. As to
Scott’s opinions on all the various questions, public or private, on
which he had occasion to make up his mind and express what he felt,
we may venture on one general remark. They are shrewd opinions,
and often or generally just,—the judgments of a man of strong
natural sagacity, and mature business-experience, adhering in the
main to use and wont, but ready for an independent consideration of
exigencies as they arose, and for any clear and safe improvement.
Even in politics, though his partisanship in that department was
obdurate, avowed, unflinching, and sometimes uproarious, his
shrewdness in the forecast of what was possible, or his private
determination in favour of what he thought just and desirable, led
him sometimes,—especially where Scottish nationality was
concerned, and the Thistle seemed to be insulted,—into dissent from
his party, and the proclamation of opinions peculiarly his own. It is
when we leave the plain ground of such practical and everyday
questions, and either ascend to those higher levels, or descend to
those deeper, at which the human intellect finds its powers more
hardly tasked,—it is then that we observe what is usually reckoned a
defect in Scott in comparison with many who have been far inferior
to him in other intellectual respects. There was little in his mind of
what may be called the purely noetic organ, that faculty which
speculates, investigates, deals with difficult problems of science or
philosophy, and seeks in every subject for ultimate principles and a
resting-ground of final conclusions. He either refrained from such
exercises of mind entirely, or was content with proximate and easily
accessible axioms. Even in literary criticism, where he might be
supposed to have been most at home, it is sagacious extempore
judgments that he offers, honest expressions of his own immediate
likings or dislikings, rather than suggestions or deductions from any
code of reasoned principles. So in matters of higher and more
solemn concern. From that simpler kind of philosophy which has
been defined as a constant Meditation of Death Scott did not refrain,
because no good or serious man can. There is evidence in his Journal
that in his solitary hours he allowed himself often enough to lapse
into this profoundest of meditations, and rolled through his mind the
whole burthen of its everlasting mysteries. But the inscrutable for
Scott, in this subject as in others, began at a short distance from his
first cogitations or his inherited creed. “I would, if called upon, die a
martyr for the Christian Religion,” he writes once in his Diary; and
no one can doubt that the words were written with the most earnest
sincerity. But, when we interpret them duly by the light of other
passages, and of all that we know independently, it is as if we saw
Scott standing upright with flushed face and clenched hands, and
saying to those about him who might want to trouble him too much
on so sacred a subject,—“This is the faith that has been transmitted
to us from far-back generations; this is the faith in which millions of
abler men than I am, or than you are, have lived and died; I hold by
that faith, without seeking too curiously to define it or to discuss its
several tenets; and, if you come too near me, to pester me with your
doubts and questionings, and new inquiries and speculations, and all
the rest of your clever nineteenth-century metaphysics, I warn you
that the soul of all my fathers will rise in me, and I shall become
dangerous.” In plainer words, on this subject, as on others, it was in
Scott’s constitution to rest in that kind of wisdom which declines
thinking beyond a certain distance.
Here, again, and in a new connection, we come round to
Shakespeare. In him, no one needs to be reminded, the noetic faculty
existed in dimensions absolutely enormous, working wonderfully in
conjunction with his equally enormous faculty of imagination, and
yet with the incessant alertness, the universal aggressiveness, and
the self-enjoying mobility, of a separate mental organ. Hence those
glances from heaven to earth and to the underworld which earth
conceals, those shafts of reasoned insight into the roots of all things,
those lightning gleams of speculation to its last extreme, that wealth
of maxims of worldly prudence outrivalling and double-distilling the
essence of all that is in Bacon’s Essays, those hints and reaches
towards an ultimate philosophy both of nature and of human life,
which have made Shakespeare’s writings till now, and will make
them henceforth, a perennial amazement. Well, after what has just
been said of Scott, are we bound, on this account, to give up the
customary juxtaposition of the two men? Hardly so, I think; for there
is a consideration of some importance yet in reserve. I will introduce
it by a little anecdote taken from the Journal itself.
People are still alive who have had personal acquaintance with
Miss Stirling Graham,—the lady who died as recently as 1877 at the
venerable age of ninety-five years, and who, some fifty or sixty years
before that, was famous in Edinburgh society for what were called
her mystifications. These consisted in her power of assuming an
imaginary character (generally that of an old Scottish lady), dressing
up in that character, appearing so dressed up unexpectedly in any
large company in a drawing-room, or even in the private study of
some eminent lawyer or judge, and carrying on a long rigmarole
conversation in the assumed character with such bewildering effect
that her auditor or auditors were completely deceived, and supposed
the garrulous intruder to be some crazy eccentric from a country-
house or some escaped madwoman. It was on the 7th of March 1828
that Sir Walter Scott witnessed, in the house of Lord Gillies, after
dinner, one of those “mystifications” of Miss Stirling Graham; and he
describes it in his Journal thus:—“Miss Stirling Græme, a lady of the
Duntroon family, from whom Clavers was descended, looks like
thirty years old, and has a face of the Scottish cast, with a good
expression in point of good sense and good-humour. Her
conversation, so far as I have had the advantage of hearing it, is
shrewd and sensible, but noways brilliant. She dined with us, went
off as if to the play, and returned in the character of an old Scottish
lady. Her dress and behaviour were admirable, and her conversation
unique. I was in the secret, of course, and did my best to keep up the
ball; but she cut me out of all feather. The prosing account which she
gave of her son, the antiquary, who found an auld wig in a slate-
quarry, was extremely ludicrous; and she puzzled the Professor of
Agriculture with a merciless account of the succession of crops in the
parks around her old mansion-house. No person to whom the secret
was not entrusted had the least guess of an imposture, except one
shrewd young lady present, who observed the hand narrowly, and
saw that it was plumper than the age of the lady seemed to warrant.”
From a note appended to this entry by Mr. Douglas we learn what Sir
Walter said to Miss Stirling Graham on this occasion, by way of
complimenting her on her performance after it was over. “Awa’,
awa’!” he said; “the Deil’s ower grit wi’ you.” There was, he saw,
something supernatural in her when she was in the mood and
attitude of her one most congenial function. All the gifts that were
latent in the shrewd and sensible-looking, but noways brilliant lady,
flashed out upon others, and were revealed even to herself, in the act
of her personations.
With the lesson in our minds which this little story supplies, we
may return to the matter of Scott’s reputed deficiency in the
speculative or purely noetic faculty:—Noetic faculty! Noetic
fiddlestick! This faculty, with a score of others perhaps for which our
meagre science of mind has no names, you will find in Scott too, if
you know how to look for them. When and where would you have
looked for the noetic faculty in Nelson? Not, certainly, as he was to
be seen in common life, a little man of slouching gait, with his empty
right arm-sleeve pinned to his breast, and gravely propounding as an
unanswerable argument in his own experience for the immateriality
of the soul the fact that, though there was now an interval of half a
yard from the stump of his lost arm and the place where his fingers
had been, he could still sometimes feel twitches of rheumatism in
those merely spectral finger-tips. No! but see him on his own great
wooden three-decker, as he was taking her into action between the
enemy’s lines, when the battle-roar and the battle-flashes had
brought the electric shiver through his veins, and he stood among his
sailors transmuted into the real Nelson, seamanship incarnate and a
fighting demigod! So, with the necessary difference for the purpose
now in view, in the case of Scott. His various faculties of intellect
were involved inextricably somehow in that imaginative faculty
which he did possess, and also in enormous degree, in common with
Shakespeare. When Scott was engaged on any of his greater works,—
a Lay of the Last Minstrel, a Marmion, a Lady of the Lake, a
Waverley, a Guy Mannering, an Antiquary, an Old Mortality, a
Heart of Midlothian, an Ivanhoe, or a Redgauntlet,—when he was so
engaged, and when the poetic phrenzy had seized him strongly,—
then what happened? Why, then that imaginative faculty which
seemed to be the whole of him, or the best of him, revealed itself
somehow as not a single faculty, but a complex composition of
various faculties, some of them usually dormant. This it did by
visibly splitting itself, resolving itself, into the multiplicity of which it
was composed; and then the plain everyday man of the tall upright
head, sagacious face, and shaggy eyebrows, was transmuted, even to
his own surprise, into a wizard that could range and speculate,—
range and speculate incalculably. It was, I say, as if then there were
loosened within him, out of his one supposed faculty of phantasy, a
simultaneous leash of other faculties, a noetic faculty included, that
could spring to incredible distances from his ordinary self, each
pursuing its appropriate prey, finding it, seizing it, sporting with it,
and coiling it back obediently to the master’s feet. In some such way,
I think, must be explained the splendour of the actual achievements
of Scott’s genius, the moderate dimensions of his purely reasoning
energy in all ordinary circumstances notwithstanding. His reasoning
energy was locked up organically, let us say, in his marvellous
imagination. And so, remembering all that Scott has left us,—those
imperishable tales and romances which no subsequent successes in
the British literature of fiction have superseded, and by the glamour
of which his own little land of brown heath and shaggy wood,
formerly of small account in the world, has become a dream and
fascination for all the leisurely of all the nations,—need we cease,
after all, from thinking of him in juxtaposition, due interval allowed,
with England’s greatest man, the whole world’s greatest man, of the
literary order, or abandon the habit of speaking of Sir Walter Scott as
our Scottish Shakespeare?
CARLYLE’S EDINBURGH LIFE[9]

PART I.—1809–1818
Early in November 1809 two boys walked together from
Ecclefechan in Dumfriesshire to Edinburgh, to attend the classes in
the University there. The distance, as the crow flies, is about sixty
miles; and the boys took three days to it. The elder, who had been at
College in the previous session, and therefore acted as the guide,
generally stalked on a few paces ahead, whistling an Irish tune to
himself. The younger, who was not quite fourteen years of age, and
had never been out of Dumfriesshire before, followed rather wearily,
irritated by the eternal Irish tune in front of him, but mainly given up
to his own “bits of reflections in the silence of the moors and hills.”
The elder of the two boys was a Thomas Smail, afterwards of some
note as a Burgher minister in Galloway; the younger was Thomas
Carlyle.
Of the arrival of the two boys in Edinburgh on the 9th of
November 1809, after their third day’s walk of twenty miles, and of
Carlyle’s first stroll, that afternoon, under Smail’s convoy, through
some of the main streets, to see the sights, one may read in his own
Reminiscences. What he remembered best of that first stroll was the
look of the Old High Street, with St. Giles’s Kirk on one side and the
old Luckenbooths running up the middle in its broadest part, but
chiefly the amazing spectacle to which he was introduced when Smail
pushed open a door behind St. Giles’s Kirk, and he found himself in
the outer house of the Court of Session, amid the buzz of the lawyers
and others walking up and down, with the red-robed judges hearing
cases in their little throned enclosures.
Content with the description of that first stroll, he leaves us to
imagine how, in the first days and weeks of his residence in the city,
he gradually extended his acquaintance with it by further rambles,
and by inspection of this and that interesting to a young stranger.
The task is not difficult. The lodging which Smail and he had taken
between them was, he says, “a clean-looking, most cheap lodging,” in
the “poor locality” called Simon Square. The locality still survives
under that name, though hardly as a square any longer, but only a
poor street, at the back of Nicolson Street, on the left hand as one
goes southwards from the University, and accessible most directly by
an arched passage called Gibb’s Entry. From that obscure centre, by
walks from it in the mornings, and returns to it during the day and in
the evenings, we can see the little Dumfriesshire fellow gradually
conquering for himself some notion of the whole of that Edinburgh
into which he had come. It was the old Edinburgh, of less than
100,000 inhabitants, which we think of so fondly now as the
Edinburgh of Scott before his novels had been heard of and when his
fame depended chiefly on his poems, of Jeffrey in the early heyday of
his lawyership and editorship of the Edinburgh Review, and of the
other local celebrities, Whig and Tory, immortalised in tradition and
in Cockburn’s Memorials.
It was chiefly of the externals of the city that the boy was making
his notes; for the living celebrities, as he tells us, were hardly even
names to him then. Scott and Jeffrey, he says, may have been in the
peripatetic crowd of wigged and gowned lawyers he had seen in the
hall of the Parliament House on the day of his arrival; but the only
physiognomy he had marked there so as to know it again was that of
John Clerk of Eldin. A reminiscence which I have heard from his own
lips enables me, however, to connect his first days in Edinburgh with
the memory of at least one Edinburgh worthy of a still elder
generation. It was on the 18th of December 1809, or just six weeks
after Carlyle’s arrival in Edinburgh, that the well-known Dr. Adam,
Rector of the High School, died; and I have heard Carlyle tell how the
event impressed him, and how he went to see the funeral procession
of the old scholar start from the High School yard at the foot of
Infirmary Street. With a number of other boys, he said, he hung on
by the railings outside, looking in upon the gathered assemblage of
mourners. He seemed to remember the scene with peculiar
vividness; for, after picturing himself as a boy hanging on by the
High School railings, and watching the incidents within, he added,
“Ay me! that moment then, and this now, and nothing but the
rushing of Time’s wings between!”[10] He had a liking to the last for
old Dr. Adam. I have heard him say that any Scotsman who was at a
loss on the subject of shall and will would find the whole doctrine in
a nutshell in two or three lucid sentences of Dr. Adam’s Latin
Grammar; and I had an idea at the time that he had used this brief
precept of Dr. Adam’s little book in his own early practice of English.
At the date of Dr. Adam’s death Carlyle had been for six weeks a
student in the University, with pupils of Dr. Adam among his fellow-
students on the same benches. One can see his matriculation
signature, “Thomas Carlyle,” in his own hand,—a clear and good
boyish hand, differing considerably from that which he afterwards
wrote,—in the alphabetically arranged matriculation list of the Arts
Students of the session 1809–10. It is the sixth signature under the
letter C, the immediately preceding signature being that of a
Dumfries youth named “Irvine Carlyle” (spelt so, and not “Irving
Carlyle,”) of whom there is mention in the Reminiscences. It is clear
that the two Carlyles were drawn to each other by community of
name and county, if not by kin, and had gone up for matriculation
together.
The College of those days was not the present complete
quadrangle, but a chaotic jumble of inconvenient old class-rooms,
with only parts of the present building risen among them, and
finished and occupied. The classes which Carlyle attended in his first
session were the 1st Humanity Class, under Professor Alexander
Christison, and the 1st Greek Class, under Professor George Dunbar.
From an examination of the records I find that among his class-
fellows in both classes were the aforesaid Irving Carlyle, and Lord
Inverurie, afterwards seventh Earl of Kintore, and that among his
class-fellows in the 1st Greek Class was the late venerable Earl of
Wemyss, then Lord Elcho. Neither from the records nor from the
Reminiscences can anything be gathered of the history of the two
classes through the session, or of the place taken in each by the
young Dumfriesshire boy among the medley of his fellow-students,
from 150 to 200 in number. The Latin class-room, we do learn from
the Reminiscences, was a very dark room, so that Professor
Christison, having two students of the name of Carlyle, never
succeeded in distinguishing the one from the other; which was all the
harder, Carlyle thought, because the other Carlyle, Mr. Irving
Carlyle, was not only different physically, being “an older,
considerably bigger boy, with red hair, wild buck teeth, and scorched
complexion,” but was also the worst Latinist in the whole class.
Carlyle himself had been so well grounded in Latin at Annan School
that probably he could have held his own in the class even against
Dr. Adam’s pupils from the Edinburgh High School. To the end of his
life, at all events, he was a fair Latinist. To Greek he never in later life
made any pretence; and whatever Greek he did learn from Dunbar,—
which can have been but small in quantity,—must have faded
through disuse. He retained, however, a high admiration for the
Elementa Linguæ Græcæ of Dr. James Moor of Glasgow,—which
was, I suppose, the Greek grammar then used in Dunbar’s class,—
thinking it the very best grammar of any language for teaching
purposes he had ever seen.
While we know so little of Carlyle’s Greek and Latin studies in
his first University session, it is something to know that he was a
pretty diligent reader of books that session from the College Library.
Having examined a dusty old folio of the library receipts and
outgoings, which chances to have been preserved, I am able to report
that Carlyle had duly paid, before December 1809, his deposit or
security of one guinea, entitling him to take books out, and that, in
that month and the succeeding month of January 1810, he had out
the following books, in parcels or in succession, in the following
order:—Robertson’s History of Scotland, vol. ii.; Cook’s Voyages;
Byron’s Narrative, i.e. “the Hon. John Byron’s Narrative of the Great
Distresses suffered by Himself and his Companions on the Coast of
Patagonia, 1740–6”; the first volume of Gibbon; two volumes of
Shakespeare; a volume of the Arabian Nights; Congreve’s Works;
another volume of the Arabian Nights; two volumes of Hume’s
England; Gil Blas; a third volume of Shakespeare; and a volume of
the Spectator. This is a sufficiently remarkable series of volumes for
a boy of fourteen to have had out from the College library; and other
books from other libraries may have been lying at the same time on
the table in the small room in Simon Square which he shared with
Tom Smail. What is most remarkable is the run upon books of
voyages and travels, and on classic books of English literature, or
books of mere literary amusement, rather than on academic books.
Clearly there had been a great deal of previous and very
miscellaneous reading at Ecclefechan and Annan, with the already
formed result of a passion for reading, and very decided notions and
tastes as to the kinds of books that might be worth looking after. But
how, whether at Ecclefechan or in Annan, had the sedate boy been
attracted to Congreve?
At the close of Carlyle’s first college session in April 1810 he
returned to Ecclefechan. He was met on the road near the village, as
he tells us so touchingly in his Reminiscences, by his father, who had
walked out, “with a red plaid about him,” on the chance of seeing
Tom coming; and the whole of the vacation was spent by him at
home in his father’s house. It is not, therefore, till the beginning of
the session of 1810–11 that we again hear of him in Edinburgh. He
then duly matriculated for his second session, his signature again
standing in the alphabetical Arts matriculation-list immediately after
that of his namesake “Irving Carlyle” (now spelt so). His classes for
this session were the 1st Mathematical Class, under Professor John
Leslie, and the Logic Class, under Professor David Ritchie; and I
have found no note of his having gone back that year, or any other,
for a second course of Latin from Professor Christison. In the 1st
Mathematical Class, consisting of seventy students, he had again
Irving Carlyle on the benches with him; in the Logic Class, consisting
of 194 students, the same Irving Carlyle was one of his fellow-
students, and the late Earl of Wemyss was another. What he made of
the Logic Class we have not the least intimation; and it is only by
inference that we know that he must have distinguished himself in
the Mathematical Class and given evidences there of his unusual
mathematical ability. As before, however, he found variation, or
diversion, from his work for the classes by diligent reading in his
lodgings. Between Saturday the 1st December 1810 and Saturday 9th
March 1811, I find, he took from the University library the following
books in the following order:—Voyages and Travels, the 15th volume
of some collection under that name; a volume of Fielding’s works; a
volume of Smollett; Reid’s Inquiry into the Human Mind; a book
called Scotland Described; two more volumes of Fielding’s works;
Locke’s Essay in folio; another volume of Fielding; a volume of
Anacharsis, i.e., of an English Translation of the Abbé Barthélémy’s
Travels of Anacharsis the Younger in Greece during the middle of the
Fourth Century before the Christian Era; and a volume of some
translation of Don Quixote. His choice of books, it will be seen, is still
very independent. Reid’s Inquiry and Locke’s Essay connect
themselves with the work in the Logic Class; but the other volumes
were evidently for mere amusement. Whether it was still in the
lodging in Simon Square, and with Smail for his chum, that these
books were read, is uncertain. His comradeship with Smail
continued, indeed, he tells us, over two sessions; but the lodging may
have been changed. It was still, doubtless, somewhere near the
University.
For the session of 1811–12 the Matriculation Book is not
alphabetically in Faculties, but general or mixed for the three
Faculties of Arts, Law, and Medicine. There were 1475 students for
those three Faculties conjointly; and “Thomas Carlyle, Ecclefechan,”
appears among them, his matriculation number being 966. That
session, his third at the University, he attended the 2d Greek Class,
under Dunbar, the 2d Mathematical Class, under Leslie, and the
Moral Philosophy Class, under Dr. Thomas Brown. In the Greek
Class, which consisted of 189 students, he had among his class-
fellows the late venerable Sir Robert Christison, Sir Robert’s twin-
brother, Alexander Christison, the late Earl of Wemyss again, his
brother, the Honourable Walter Charteris, a Thomas Murray from
Kirkcudbrightshire, afterwards a well-known citizen of Edinburgh,
the inextinguishable Irving Carlyle, and an Andrew Combe, whom I
identify with the subsequently well-known Dr. Andrew Combe, the
brother of George Combe the phrenologist. In the Mathematical
Class, which numbered forty-six, there were several Dumfriesshire
students besides himself; and it was in this 2d Mathematical Class, if
the tradition is correct, that Carlyle took the first prize,—another
Dumfriesshire youth, who lived in the same lodging with him, taking
the second. I have turned with most interest, in this session, to the
“List of Students attending Dr. Thomas Brown’s Class,” preserved in
the peculiarly neat, small handwriting of Dr. Brown himself. It was
the second session of Brown’s full tenure of the Professorship of
Moral Philosophy in succession to Dugald Stewart, and the fame of
his lectures was at its highest. The class consisted of 151 students;
and among them, besides Carlyle and his inseparable Irving Carlyle,
and a Robert Mitchell and a Paulus Aemilius Irving, both from
Dumfriesshire, there were Duncan McNeill, afterwards Lord
Colonsay, his brother, John McNeill, Sir Andrew Agnew, David
Welsh, afterwards Dr. David Welsh and Professor of Church History,
and a James Bisset from Aberdeenshire, whom I identify with the
late Rev. Dr. Bisset of Bourtie. Some of these were outsiders, already
in the Divinity or Law Classes, who had returned to the Moral
Philosophy Class for the benefit of Dr. Brown’s brilliant lectures,—
notably young David Welsh, who had already attended the class for
two sessions, but was full of enthusiasm for Brown, whose
biographer and editor he was to be in time. Carlyle, I am sorry to say,
was not one of the admirers of the brilliant Brown. Over and over
again I have heard him speak of Brown, and always with mimicry
and contempt, as “a finical man they called Brown, or sometimes
Missy Brown, that used to spout poetry.” This can hardly have been
out of disregard for metaphysics as such, for he had much respect for
Dugald Stewart, the then retired professor. The dislike seems to have
been partly personal, partly to the new kind of highly ingenious
metaphysics which Brown was trying to substitute for the older and
more orthodox Scottish Philosophy of Reid and Stewart. At all
events, it is worthy of note that those brilliant lectures of Thomas
Brown, which James Mill and John Stuart Mill admired so much in
their published form, regarding them as an introduction to much
that is best in modern British Philosophy, had no effect, in their
actual delivery, on the hard-headed young Carlyle, but fell upon him
as mere dazzle and moonshine.
As Carlyle tells us incidentally that he was in Edinburgh in the
summer of 1812, it is to be supposed that he spent less of that
vacation than usual in his Dumfriesshire home. I find also that he
matriculated rather late in our books for the session of 1812–13, his
name not appearing in the first or main matriculation list, but only in
a supplementary list, and then as “Thomas Carlyle, Hoddam,
Dumfriesshire.” His father had by that time given up his trade of
mason, and had left Ecclefechan to try a small farm in the
neighbourhood. The number of students matriculated that year in
the three faculties of Arts, Law, and Medicine, was 1503; and
Carlyle’s matriculation number was 1403. The classes in which he
was enrolled for that session, his fourth and last in Arts, were Leslie’s
2d Mathematical Class (attended a second time, we may suppose, for
such higher instruction as might be fit for very advanced students),
and the Natural Philosophy Class, under Professor John Playfair. In
this last session, accordingly, as a student only of Mathematics and
Physics, with no distraction towards either Classics or Mental
Philosophy, Carlyle may be said to have been in his element. He
worked very hard in both classes, and distinguished himself in both.
My own impression, from talks with him on the subject, is that he
was, by acknowledgment of professors and fellow-students, easily
supreme in both. Leslie’s second class that year numbered but forty-
one students, and it was natural that his most distinguished student
in two previous sessions should now be familiar with him and receive
his especial notice. Certain it is that of all the Professors of
Edinburgh University in Carlyle’s time Leslie was the only one of
whom he spoke always with something of real gratitude and
affection. The affection was mixed, indeed, with a kind of laughing
remembrance of Leslie’s odd, corpulent figure, and odd rough ways;
and he would describe with particular gusto the occasional effects of
Leslie’s persistent habit of using hair-dyes, as when a streak of pink
or green would be observable amid the dark-brown or black on those
less accessible parts of his head where the chemicals had been too
liberally or too rashly applied. But he had a real esteem for Leslie’s
great abilities, and remembered him as a man to whose
mathematical instructions, and to whose private kindness, he owed
much.——A greater Hero with him in Pure Mathematics than even
Leslie, I may mention parenthetically, was the now totally-forgotten
John West, who had been assistant-teacher of Mathematics in the
University of St. Andrews for some time from about 1780 onwards,
and of whom Leslie, Ivory, and all the other ablest mathematicians
sent forth from that University, had been pupils. Of this man, whom
he knew of only by tradition, but whom he regarded as, after Robert
Simson of Glasgow, the most original geometrical genius there had
been in Scotland, I have heard him talk I know not how often. He
would sketch West’s life, from the time of his hard and little-
appreciated labours at St. Andrews to his death in the West Indies,
whither he had emigrated in despair for some chaplaincy or the like;
he would avow his belief that Leslie had derived some of his best
ideas from that poor man; and he expressed pleasure at finding I
knew something of West independently, and had a copy of West’s
rare Elements of Mathematics, published in 1784. That book,
obsolete now, was, I have no doubt, a manual with Carlyle while he
was studying Mathematics in Edinburgh University, as I chance to
know it had been with Dr. Chalmers at St. Andrews in his earlier
mathematical days.——Of Leslie’s colleague, the celebrated Playfair,
formerly in the Mathematical Chair, but since 1805 in that of Natural
Philosophy, Carlyle had a less affectionate recollection personally
than of Leslie. Sharing, I believe, the common opinion of Playfair’s
great merits, and minutely acquainted with the facts of his life, as
indeed he was with the biographies of all persons of any mark with
whom he had come into contact, he rather resented a piece of
injustice which he thought Playfair had done to himself. There were
131 students in the Natural Philosophy Class in 1812–13; and Carlyle,
as he assured me, was single in that whole number for having
performed and given in every one of all the prescribed exercises,
mathematical or other. Another Dumfriesshire student, who came
next to him, had failed in one, and that the most difficult. Naturally,
at the end of the session, he expected that his certificate would
correspond to his distinction in the class; and it was of some
consequence to him that it should. But, when he called at Playfair’s
house for the certificate, and it was delivered to him by a man-
servant, he was a good deal disappointed. The usual form of the
wording for a good student was to the effect that the Professor
certified that so-and-so had attended the class in such and such a
session and had “made good proficiency in his studies.” In Carlyle’s
case there was a certain deviation from this form, but only to the
effect that he had attended the class and that the Professor “had
reason to know that he had made good proficiency in his studies.” I
can remember Carlyle’s laugh as he told me of this delicate
distinction; and I have always treasured the anecdote as a lesson for
professors. They ought to be very careful not only in noting talent on
the benches before them, but also in signifying what they have
noted, if only because, as in Playfair’s case, they may be sometimes
entertaining an angel unawares, and some angels have severe
memories.
We have thus brought Carlyle to the summer of 1813, when he
had completed his Arts course in the University of Edinburgh, and
was in the eighteenth year of his age. Though qualified, according to
the present standard, for the degree of M.A., he did not take it; but in
that he was not in the least singular. In those days hardly any
Edinburgh student ever thought of taking a degree in Arts; as far as
Edinburgh University was concerned, the M.A. degree had fallen into
almost complete disuse; and not till within very recent memory has it

You might also like