Java 8
Programming
AWT Controls, Swing Controls,
File and I/O Handling, Threading, Networking,
Java Beans, JDBC, Security, Packages,
Annotations Lambda expressions,
NIO, Java DB, Java FX
Black Book
TM
Authored by:
DT Editorial
Services
Published by:
Copyright 2015 by Dreamtech Press, 19-A, Ansari Road, Daryaganj, New Delhi-110002
Black Book is a trademark of Paraglyph Press Inc., 2246 E. Myrtle Avenue, Phoenix Arizona 85202,
USA exclusively licensed in Indian, Asian and African continent to Dreamtech Press, India.
This book may not be duplicated in any way without the express written consent of the publisher,
except in the form of brief excerpts or quotations for the purposes of review. The information
contained herein is for the personal use of the reader and may not be incorporated in any
commercial programs, other books, databases, or any kind of software without written consent of
the publisher. Making copies of this book or any portion for any purpose other than your own is a
violation of copyright laws.
Limits of Liability/disclaimer of Warranty: The author and publisher have used their best
efforts in preparing this book. The author make no representation or warranties with respect to
the accuracy or completeness of the contents of this book, and specifically disclaim any implied
warranties of merchantability or fitness of any particular purpose. There are no warranties which
extend beyond the descriptions contained in this paragraph. No warranty may be created or
extended by sales representatives or written sales materials. The accuracy and completeness of
the information provided herein and the opinions stated herein are not guaranteed or warranted
to produce any particulars results, and the advice and strategies contained herein may not be
suitable for every individual. Neither Dreamtech Press nor author shall be liable for any loss of
profit or any other commercial damages, including but not limited to special, incidental,
consequential, or other damages.
Trademarks: All brand names and product names used in this book are trademarks, registered
trademarks, or trade names of their respective holders. Dreamtech Press is not associated with any
product or vendor mentioned in this book.
ISBN: 978-93-5119-758-4
ISBN: 978-93-5119-953-3 (ebk)
Edition: 2015
Printed at: Himal Impressions, Delhi
Contents at a Glance
Introduction .......................................................................................................................... xxxiii
Chapter 1: Essential Java ........................................................................................................... 1
Chapter 2: Variables, Arrays, and Strings ................................................................................ 31
Chapter 3: Operators, Conditionals, and Loops ...................................................................... 75
Chapter 4: Object-Oriented Programming ............................................................................. 105
Chapter 5: Inheritance, Inner Classes, and Interfaces ........................................................... 145
Chapter 6: AWTApplets, Applications, and Event Handling .............................................. 171
Chapter 7: AWTText Fields, Buttons, Checkboxes, Radio Buttons, and Layouts ............ 215
Chapter 8: AWTLists, Choices, Text Areas, Scroll bars, and Scroll Panes ....................... 245
Chapter 9: AWTGraphics, Images, Text, and Fonts ........................................................... 275
Chapter 10: AWTWindows, Menus, and Dialog Boxes ....................................................... 315
Chapter 11: SwingApplets, Applications, and Pluggable Look and Feel .......................... 351
Chapter 12: SwingText Fields, Buttons, Toggle Buttons, Checkboxes,
and Radio Buttons .............................................................................................. 395
Chapter 13: SwingViewports, Scrolling, Sliders, Lists, Tables, and Trees ....................... 443
Chapter 14: SwingCombo Boxes, Progress Bars, Tooltips,
Separators, and Choosers ................................................................................. 489
Chapter 15: SwingLayered Panes, Tabbed Panes, Split Panes, and Layouts................... 521
Contents at a Glance
Chapter 16: SwingMenus and Toolbars .............................................................................. 549
Chapter 17: SwingWindows, Desktop Panes, Inner Frames, and Dialog Boxes............... 579
Chapter 18: Working with Streams, Files, and I/O Handling ................................................. 615
Chapter 19: Working with Multiple Threads ........................................................................... 673
Chapter 20: Networking and Security with Java .................................................................... 725
Chapter 21: Collections........................................................................................................... 767
Chapter 22: Creating Packages, Interfaces, JAR Files, and Annotations ............................. 823
Chapter 23: Working with Java Beans ................................................................................... 845
Chapter 24: Introducing JDBC ................................................................................................ 875
Chapter 25: Images and Animation ........................................................................................ 927
Chapter 26: Java DB................................................................................................................ 951
Chapter 27: Java FX ................................................................................................................ 969
Glossary .................................................................................................................................. 993
Index ........................................................................................................................................ 997
Bonus chapters available with the book for Download
Chapter 1: Java and XMLUsing the Document Object Model ................................................ 1
Chapter 2: Java and XMLUsing the Simple API for XML ...................................................... 31
Chapter 3: Understanding RMI ................................................................................................. 57
Chapter 4: Working with Servlets 3.1 ....................................................................................... 83
Chapter 5: Dynamic Java Scripting ........................................................................................ 137
Chapter 6: Introduction to Groovy.......................................................................................... 159
Chapter 7: MXBeans and JMX ................................................................................................ 189
Chapter 8: Inclusion of Sound ................................................................................................ 213
Chapter 9: Filing and Printing Documents ............................................................................. 251
iv
Table of Contents
Introduction .......................................................................................................................... xxxiii
Chapter 1: Essential Java ........................................................................................................... 1
In Depth .................................................................................................................................. 2
All about Java ........................................................................................................................................................................ 2
Java Appears....................................................................................................................................................................... 3
All about Bytecodes ........................................................................................................................................................... 3
Features of Java .................................................................................................................................................................. 4
Java Environment .................................................................................................................................................................. 6
Java Development Kit........................................................................................................................................................ 6
Java Platforms..................................................................................................................................................................... 6
Java Virtual Machine ......................................................................................................................................................... 8
Java API ............................................................................................................................................................................... 8
Java Programs..................................................................................................................................................................... 9
What are Application Servers (Tomcat, JRun, WebSphere, WebLogic, etc.) ................................................................. 9
Program Design ................................................................................................................................................................... 11
Performance ...................................................................................................................................................................... 11
Maintainability ................................................................................................................................................................. 11
Extensibility ...................................................................................................................................................................... 12
Availability ....................................................................................................................................................................... 12
New Features of Java SE 8 .................................................................................................................................................. 12
Immediate Solutions ............................................................................................................ 15
Getting and Installing Java ................................................................................................................................................. 15
What about CLASSPATH? ............................................................................................................................................. 15
Subfolders Created by JDK ................................................................................................................................................ 16
Creating Source Files .......................................................................................................................................................... 16
Table of Contents
Knowing Javas Reserved Words ...................................................................................................................................... 17
Creating an Application ..................................................................................................................................................... 19
Line 1public class App ............................................................................................................................................... 19
Line 2public static void main(String[] args) ........................................................................................................... 19
Line 3System.out.println(Hello from Java!);....................................................................................................... 20
Compiling Code .................................................................................................................................................................. 20
Compiling Code: Using Command-Line Options ....................................................................................................... 21
Cross-Compilation Options ............................................................................................................................................ 22
Compiling Code: Checking for Deprecated Methods ................................................................................................. 23
Running Code ...................................................................................................................................................................... 23
Running Code: Using Command-Line Options .............................................................................................................. 25
Commenting Your Code .................................................................................................................................................... 26
Import Java Packages and Classes .................................................................................................................................... 27
Finding Java Classes with CLASSPATH ......................................................................................................................... 28
Summary .............................................................................................................................................................................. 30
Chapter 2: Variables, Arrays, and Strings ................................................................................ 31
In Depth ................................................................................................................................ 33
Variables ............................................................................................................................................................................... 33
Data Typing ......................................................................................................................................................................... 34
Arrays ................................................................................................................................................................................... 34
Strings ................................................................................................................................................................................... 36
Immediate Solutions ............................................................................................................ 37
What Data Types are Available? ....................................................................................................................................... 37
Creating Integer Literals ..................................................................................................................................................... 37
Creating Floating-Point Literals ........................................................................................................................................ 38
Creating Boolean Literals ................................................................................................................................................... 39
Creating Character Literals ................................................................................................................................................ 39
Creating String Literals....................................................................................................................................................... 40
Creating Binary Literals...................................................................................................................................................... 40
Using Underscores in Numeric Literals ........................................................................................................................... 41
Declaring Integer Variables................................................................................................................................................ 42
Declaring Floating-Point Variables ................................................................................................................................... 42
Declaring Character Variables ........................................................................................................................................... 43
Declaring Boolean Variables .............................................................................................................................................. 43
Initializing Variables Dynamically.................................................................................................................................... 44
vi
Table of Contents
Conversion between Data Types ....................................................................................................................................... 45
Automatic Conversions ................................................................................................................................................... 45
Casting to New Data Types ............................................................................................................................................ 46
Declaring One-Dimensional Arrays.................................................................................................................................. 47
Creating One-Dimensional Arrays ................................................................................................................................... 47
Initializing One-Dimensional Arrays ............................................................................................................................... 48
Declaring Multi-Dimensional Arrays ............................................................................................................................... 48
Creating Multi-Dimensional Arrays ................................................................................................................................. 48
Initializing Multi-Dimensional Arrays ............................................................................................................................. 49
Creating Irregular Multi-Dimensional Arrays ................................................................................................................ 50
Getting an the Length of an Array .................................................................................................................................... 51
Understanding General Form of Static Import ................................................................................................................ 51
Importing Static Members .................................................................................................................................................. 51
The String Class .................................................................................................................................................................. 52
Creating Strings ................................................................................................................................................................... 56
Getting String Length ......................................................................................................................................................... 57
Concatenating Strings ......................................................................................................................................................... 58
Getting Characters and Substrings ................................................................................................................................... 58
Searching For and Replacing Strings ................................................................................................................................ 59
Changing Case in Strings ................................................................................................................................................... 60
Checking for Empty String ................................................................................................................................................ 60
Formatting Numbers in Strings ......................................................................................................................................... 60
The StringBuffer Class ....................................................................................................................................................... 61
Creating StringBuffers ........................................................................................................................................................ 63
Getting and Setting StringBuffer Lengths and Capacities ............................................................................................. 64
Setting Characters in String Buffers .................................................................................................................................. 64
Appending and Inserting Using StringBuffers ................................................................................................................ 65
Deleting Text in StringBuffers ........................................................................................................................................... 65
Replacing Text in StringBuffer........................................................................................................................................... 65
Using the Wrapper Class ................................................................................................................................................... 66
Autoboxing and Unboxing of Primitive Types ............................................................................................................... 67
Learning the Fundamentals of Varargs Methods............................................................................................................ 69
Overloading Varargs Methods ....................................................................................................................................... 71
Learning the Ambiguity in Varargs Methods .............................................................................................................. 72
Using Non-Reifiable Formal Parameters ...................................................................................................................... 73
Summary .............................................................................................................................................................................. 74
vii
Table of Contents
Chapter 3: Operators, Conditionals, and Loops ...................................................................... 75
In Depth ................................................................................................................................ 77
Operators .............................................................................................................................................................................. 77
Conditionals ......................................................................................................................................................................... 78
Loops .................................................................................................................................................................................... 79
Immediate Solutions ............................................................................................................ 81
Operator Precedence ........................................................................................................................................................... 81
Incrementing and Decrementing (++ and --) ................................................................................................................... 82
Unary NOT (~ And !) ......................................................................................................................................................... 83
Multiplication and Division (* and /) .............................................................................................................................. 83
Modulus (%) ......................................................................................................................................................................... 83
Addition and Subtraction (+ and -) .................................................................................................................................. 84
Shift Operators (>>, >>>, and <<) ..................................................................................................................................... 84
Relational Operators (>, >=, <, <=, ==, and !=) ............................................................................................................... 85
Bitwise and Bitwise Logical AND, XOR, and OR (&, ^, and /) .................................................................................... 85
Logical (&& and ||) ........................................................................................................................................................... 87
The if-then-else Operator (?:)........................................................................................................................................... 87
Assignment Operators (= and [operator]=) ..................................................................................................................... 88
Using the Math Class.......................................................................................................................................................... 89
Changes in the Math Class ................................................................................................................................................ 90
Class StrictMath .................................................................................................................................................................. 90
Comparing Strings .............................................................................................................................................................. 91
The if Statement .................................................................................................................................................................. 92
The else Statement .............................................................................................................................................................. 92
Nested if Statement............................................................................................................................................................. 93
The if-else Ladders ............................................................................................................................................................. 93
The switch Statement ......................................................................................................................................................... 93
Using Strings in switch Statement .................................................................................................................................... 95
The while Loop ................................................................................................................................................................... 95
The do-while Loop ............................................................................................................................................................. 96
The for Loop ........................................................................................................................................................................ 97
The for-each Loop ............................................................................................................................................................... 99
Supporting for-each in Your Own Class ........................................................................................................................ 101
A (Poor) Solution ........................................................................................................................................................... 101
Significance of for-each ................................................................................................................................................. 101
Nested Loops ..................................................................................................................................................................... 102
viii
Table of Contents
Using the break Statement ............................................................................................................................................... 103
Using the continue Statement ......................................................................................................................................... 103
Summary ............................................................................................................................................................................ 104
Chapter 4: Object-Oriented Programming ............................................................................. 105
In Depth .............................................................................................................................. 107
Classes ................................................................................................................................................................................ 108
Objects ................................................................................................................................................................................ 108
Data Members .................................................................................................................................................................... 108
Methods .............................................................................................................................................................................. 108
Inheritance.......................................................................................................................................................................... 109
Exception Handling .......................................................................................................................................................... 109
Debugging .......................................................................................................................................................................... 110
Immediate Solutions .......................................................................................................... 111
Declaring and Defining Classes....................................................................................................................................... 111
Declaring and Creating Objects ....................................................................................................................................... 112
Creating Instance Variables ............................................................................................................................................. 114
Setting Variable Access ..................................................................................................................................................... 114
Creating Class Variables................................................................................................................................................... 115
Creating Methods .............................................................................................................................................................. 116
Setting Method Access ...................................................................................................................................................... 116
Passing Parameters to Methods....................................................................................................................................... 117
Command-Line Arguments Passed to main() method ................................................................................................ 118
Returning Values from Methods ..................................................................................................................................... 118
Creating Class Methods.................................................................................................................................................... 119
Creating Data Access Methods ........................................................................................................................................ 120
Creating Constructors ....................................................................................................................................................... 120
Passing Parameters to Constructors ............................................................................................................................... 121
A Full Class Example ........................................................................................................................................................ 121
Understanding Variable Scope ........................................................................................................................................ 122
Using Recursion ................................................................................................................................................................ 123
Garbage Collection and Memory Management ............................................................................................................ 123
Avoiding Circular References ...................................................................................................................................... 124
Garbage Collection and the finalize() Method.............................................................................................................. 125
Overloading Methods ....................................................................................................................................................... 125
Overloading Constructors ................................................................................................................................................ 126
Passing Objects to Methods ............................................................................................................................................. 126
ix
Table of Contents
Passing Arrays to Methods .............................................................................................................................................. 127
Using the this Keyword ................................................................................................................................................... 128
Returning Objects from Methods .................................................................................................................................... 129
Returning Arrays from Methods ..................................................................................................................................... 129
The ProcessBuilder and StringBuilder Classes .............................................................................................................. 129
The ProcessBuilder Class ............................................................................................................................................. 130
The StringBuilder Class ............................................................................................................................................... 131
Catching an Exception ...................................................................................................................................................... 132
Nesting the try Statements ............................................................................................................................................... 136
Using the finally Clause ................................................................................................................................................... 137
Throwing Exceptions ........................................................................................................................................................ 138
Creating a Custom Exception .......................................................................................................................................... 139
Catching Multiple Exception Types ................................................................................................................................ 139
Rethrowing Exceptions with Improved Type Checking .............................................................................................. 140
Debugging Java Programs ............................................................................................................................................... 141
Summary ............................................................................................................................................................................ 144
Chapter 5: Inheritance, Inner Classes, and Interfaces ........................................................... 145
In Depth .............................................................................................................................. 146
Why Inheritance? .............................................................................................................................................................. 146
Why Interfaces? ................................................................................................................................................................. 147
Why Inner Classes? ........................................................................................................................................................... 147
Lambda Expressions ......................................................................................................................................................... 148
Method References ........................................................................................................................................................ 148
Immediate Solutions .......................................................................................................... 150
Creating a Subclass ........................................................................................................................................................... 150
Access Specifiers and Inheritance ................................................................................................................................... 150
Calling Superclass Constructors ...................................................................................................................................... 151
Creating Multilevel Inheritance....................................................................................................................................... 153
Handling Multilevel Constructors .................................................................................................................................. 154
Overriding Methods ......................................................................................................................................................... 155
Accessing Overridden Members ..................................................................................................................................... 155
Using Superclass Variables with Subclassed Objects ................................................................................................... 156
Dynamic Method Dispatch (Runtime Polymorphism)................................................................................................. 157
Creating Abstract Classes ................................................................................................................................................. 158
Stopping Overriding with final ...................................................................................................................................... 159
Stopping Inheritance with final ...................................................................................................................................... 159
x
Table of Contents
Creating Constants with final ......................................................................................................................................... 160
Is-a vs. Has-a Relationships ............................................................................................................................................. 160
The Java Object Class ....................................................................................................................................................... 161
Using Interfaces for Multiple Inheritance ...................................................................................................................... 162
The Readable Interface ................................................................................................................................................. 163
The Appendable Interface ............................................................................................................................................ 164
The Iterable Interface .................................................................................................................................................... 164
Creating Iterable Objects ................................................................................................................................................. 166
Creating Inner Classes ...................................................................................................................................................... 168
Creating Anonymous Inner Classes ............................................................................................................................... 168
Using Lambda Expression ............................................................................................................................................... 169
Default Methods ............................................................................................................................................................ 169
Summary ............................................................................................................................................................................ 170
Chapter 6: AWTApplets, Applications, and Event Handling .............................................. 171
In Depth .............................................................................................................................. 172
The Abstract Windowing Toolkit .................................................................................................................................... 172
Applets ............................................................................................................................................................................... 173
Applications ....................................................................................................................................................................... 174
Handling Events ................................................................................................................................................................ 174
Immediate Solutions .......................................................................................................... 175
Using the Abstract Window Toolkit ............................................................................................................................... 175
Creating Applets ............................................................................................................................................................... 186
Using the <APPLET> HTML Tag ................................................................................................................................... 188
Handling Non-Java Browsers .......................................................................................................................................... 189
Embedding <APPLET> Tags in Code ............................................................................................................................ 189
Using the init, start, stop, destroy, paint, and update Methods .................................................................................. 190
Drawing Graphics in Applets .......................................................................................................................................... 191
Reading Parameters in Applets ....................................................................................................................................... 191
Using Java Consoles in Browsers .................................................................................................................................... 191
Adding Controls to Applets: Text Fields........................................................................................................................ 192
Adding Controls to Applets: Buttons ............................................................................................................................. 193
Handling Events ................................................................................................................................................................ 194
Standard Event Handling ............................................................................................................................................. 195
Using Delegated Classes ............................................................................................................................................... 197
Using Action Commands .............................................................................................................................................. 199
Handling Events the Old Way ..................................................................................................................................... 199
xi
Table of Contents
Extending Components ................................................................................................................................................. 200
Using Adapter Classes...................................................................................................................................................... 200
Using Anonymous Inner Adapter Classes ..................................................................................................................... 202
Creating Windowed Applications .................................................................................................................................. 202
Exiting an Application When Its Window Is Closed .................................................................................................... 206
Applications You Can Run as Applets ........................................................................................................................... 206
Setting Applet Security Policies....................................................................................................................................... 207
Other Facilities in the java.awt Package ......................................................................................................................... 209
System Tray .................................................................................................................................................................... 209
Splash Screen .................................................................................................................................................................. 211
Dialog Modality ............................................................................................................................................................. 213
Gif Writer ........................................................................................................................................................................ 213
Text Antialiasing ............................................................................................................................................................ 214
Summary ............................................................................................................................................................................ 214
Chapter 7: AWTText Fields, Buttons, Checkboxes, Radio Buttons, and Layouts ............ 215
In Depth .............................................................................................................................. 216
Text Fields .......................................................................................................................................................................... 216
Buttons ................................................................................................................................................................................ 216
Checkboxes ........................................................................................................................................................................ 216
Radio Buttons .................................................................................................................................................................... 216
Layouts ............................................................................................................................................................................... 216
Immediate Solutions .......................................................................................................... 218
Using Text Fields ............................................................................................................................................................... 218
Using Labels ....................................................................................................................................................................... 220
Using Buttons .................................................................................................................................................................... 221
Using Checkboxes ............................................................................................................................................................. 224
Using Radio Buttons ......................................................................................................................................................... 227
Layout Managers ............................................................................................................................................................... 228
Flow Layouts ..................................................................................................................................................................... 228
Grid Layouts ...................................................................................................................................................................... 231
Using Panels....................................................................................................................................................................... 232
Border Layouts .................................................................................................................................................................. 234
Card Layouts ..................................................................................................................................................................... 236
Grid Bag Layouts............................................................................................................................................................... 238
Using Insets and Padding ................................................................................................................................................ 243
xii
Table of Contents
Creating Your Own Layout Manager ............................................................................................................................. 244
Summary ............................................................................................................................................................................ 244
Chapter 8: AWTLists, Choices, Text Areas, Scroll bars, and Scroll Panes ....................... 245
In Depth .............................................................................................................................. 246
Lists ..................................................................................................................................................................................... 246
Choices................................................................................................................................................................................ 246
Text Areas .......................................................................................................................................................................... 246
Scroll bars ........................................................................................................................................................................... 246
Scroll Panes ........................................................................................................................................................................ 247
Immediate Solutions .......................................................................................................... 248
Using Text Areas ............................................................................................................................................................... 248
Replacing Text in Text Areas ........................................................................................................................................... 251
Searching and Selecting Text in Text Areas ................................................................................................................... 252
Using Lists .......................................................................................................................................................................... 253
Using Multiple-Selection Lists ......................................................................................................................................... 257
Using Choice Controls ...................................................................................................................................................... 260
Using Scroll bars ................................................................................................................................................................ 265
Scroll bars and Border Layouts ....................................................................................................................................... 269
Using Scroll Panes ............................................................................................................................................................. 272
Summary ............................................................................................................................................................................ 274
Chapter 9: AWTGraphics, Images, Text, and Fonts ........................................................... 275
In Depth .............................................................................................................................. 276
Graphics ............................................................................................................................................................................. 276
Images ................................................................................................................................................................................. 276
Text and Fonts ................................................................................................................................................................... 276
The Keyboard and Mouse ................................................................................................................................................ 276
Immediate Solutions .......................................................................................................... 277
Using the Mouse ................................................................................................................................................................ 277
Using the Keyboard .......................................................................................................................................................... 279
Using Fonts ........................................................................................................................................................................ 283
Using Images ..................................................................................................................................................................... 289
Resizing Images ................................................................................................................................................................. 291
Drawing Graphics ............................................................................................................................................................. 292
Drawing Lines ................................................................................................................................................................ 297
xiii
Table of Contents
Drawing Ovals ............................................................................................................................................................... 298
Drawing Rectangles ....................................................................................................................................................... 298
Drawing Rounded Rectangles ...................................................................................................................................... 299
Drawing Freehand ......................................................................................................................................................... 299
Drawing Arcs ................................................................................................................................................................. 299
Drawing Polygons ......................................................................................................................................................... 299
Setting Drawing Modes ................................................................................................................................................ 300
Selecting Colors ................................................................................................................................................................. 300
Using Canvases ................................................................................................................................................................. 303
Using the ImageObserver Interface ............................................................................................................................... 305
Using the MediaTracker Class ........................................................................................................................................ 306
Working Pixel by Pixel: The PixelGrabber and MemoryImageSource Classes....................................................... 308
Brightening Images ........................................................................................................................................................... 311
Converting Images to Grayscale ..................................................................................................................................... 312
Embossing Images............................................................................................................................................................. 313
Summary ............................................................................................................................................................................ 314
Chapter 10: AWTWindows, Menus, and Dialog Boxes ....................................................... 315
In Depth .............................................................................................................................. 316
Windows ............................................................................................................................................................................ 316
Menus ................................................................................................................................................................................. 316
Dialog Boxes ...................................................................................................................................................................... 316
Immediate Solutions .......................................................................................................... 318
Creating Frame Windows ................................................................................................................................................ 318
Showing and Hiding Windows ....................................................................................................................................... 319
Handling Window Events................................................................................................................................................ 320
Automatically Hiding Windows upon Closing ............................................................................................................ 323
Using the Window Class .................................................................................................................................................. 323
Creating Menus ................................................................................................................................................................. 330
Creating a MenuBar Object ............................................................................................................................................. 331
Creating Menu Objects ..................................................................................................................................................... 332
Creating MenuItem Objects ............................................................................................................................................ 333
Handling Menu Events..................................................................................................................................................... 335
More Menu Options .......................................................................................................................................................... 336
Adding Menu Separators ................................................................................................................................................. 338
Disabling Menu Items....................................................................................................................................................... 338
xiv
Table of Contents
Adding Checkboxes to Menus......................................................................................................................................... 339
Creating Submenus ........................................................................................................................................................... 341
Pop-Up Menus ................................................................................................................................................................... 342
Dialog Boxes ...................................................................................................................................................................... 344
File Dialog Boxes ............................................................................................................................................................... 348
Summary ............................................................................................................................................................................ 350
Chapter 11: SwingApplets, Applications, and Pluggable Look and Feel .......................... 351
In Depth .............................................................................................................................. 352
The Java Foundation Classes ........................................................................................................................................... 352
Swing .................................................................................................................................................................................. 353
Heavyweight versus Lightweight Components............................................................................................................ 354
Swing Features .................................................................................................................................................................. 355
Graphics Programming Using Panes .............................................................................................................................. 356
Model View Controller Architecture .............................................................................................................................. 356
Immediate Solutions .......................................................................................................... 358
Working with Swing ......................................................................................................................................................... 358
Preparing to Create a Swing Applet ............................................................................................................................... 364
Understanding Root Panes ........................................................................................................................................... 366
Understanding Layered Panes ..................................................................................................................................... 368
Understanding Content Panes ......................................................................................................................................... 370
Working with Content Panes ....................................................................................................................................... 370
Creating a Swing Applet .................................................................................................................................................. 372
Painting in Swing vs. AWT........................................................................................................................................... 372
Displaying Controls in Swing Vs AWT ...................................................................................................................... 372
Using the JPanel Class .................................................................................................................................................. 373
Creating a Swing Application.......................................................................................................................................... 374
Closing JFrame Windows ................................................................................................................................................ 377
Using Insets for Selecting Component Borders ............................................................................................................. 379
Using Insets .................................................................................................................................................................... 381
The Synth Skinnable Look and Feel ................................................................................................................................ 383
The Pluggable Look and Feel........................................................................................................................................... 386
The Pluggable Look and Feel for Components ............................................................................................................. 390
The Nimbus Look and Feel .............................................................................................................................................. 392
Summary ............................................................................................................................................................................ 394
xv
Table of Contents
Chapter 12: SwingText Fields, Buttons, Toggle Buttons, Checkboxes,
and Radio Buttons .............................................................................................. 395
In Depth .............................................................................................................................. 397
Labels and Text Fields ...................................................................................................................................................... 397
Password Field ............................................................................................................................................................... 397
Text Area ......................................................................................................................................................................... 397
Editor Pane ..................................................................................................................................................................... 397
Text Pane ......................................................................................................................................................................... 398
Text Component Printing ............................................................................................................................................. 398
Buttons ................................................................................................................................................................................ 398
Toggle Buttons ................................................................................................................................................................... 398
Checkboxes and Radio Buttons ....................................................................................................................................... 398
Immediate Solutions .......................................................................................................... 399
Using Labels ....................................................................................................................................................................... 399
Using Image Icons ............................................................................................................................................................. 401
Using Images in Labels ..................................................................................................................................................... 402
Using Text Fields ............................................................................................................................................................... 403
Setting Text Field Alignment ........................................................................................................................................... 405
Creating Password Field .................................................................................................................................................. 406
Creating Text Areas .......................................................................................................................................................... 407
Customizing a Text Area .............................................................................................................................................. 409
Creating Editor Panes ....................................................................................................................................................... 409
Using HTML in Editor Panes........................................................................................................................................... 411
Using RTF Files in Editor Panes ...................................................................................................................................... 412
Creating Text Panes .......................................................................................................................................................... 412
Inserting Images and Controls into Text Panes.......................................................................................................... 412
Setting Text Pane Text Attributes .................................................................................................................................... 414
Working with Sound in Applets ..................................................................................................................................... 416
Working with Sound in Application .............................................................................................................................. 417
Abstract Button: The Foundation of Swing Buttons ..................................................................................................... 417
Using Buttons .................................................................................................................................................................... 421
Displaying Images in Buttons .......................................................................................................................................... 424
Using Rollover and Disabled Images ............................................................................................................................. 426
Default Buttons and Mnemonics ..................................................................................................................................... 427
Using Toggle Buttons ....................................................................................................................................................... 430
Creating Toggle Button Groups ...................................................................................................................................... 432
xvi
Table of Contents
Using Checkboxes ............................................................................................................................................................. 433
Using Radio Buttons ......................................................................................................................................................... 436
Using Checkbox and Radio Button Images ................................................................................................................... 440
Getting and Setting the State of Checkboxes and Radio Buttons ................................................................................ 441
Summary ............................................................................................................................................................................ 442
Chapter 13: SwingViewports, Scrolling, Sliders, Lists, Tables, and Trees ....................... 443
In Depth .............................................................................................................................. 445
Viewports ........................................................................................................................................................................... 445
Scroll Panes ........................................................................................................................................................................ 445
Sliders ................................................................................................................................................................................. 445
Scrollbars ............................................................................................................................................................................ 445
Lists ..................................................................................................................................................................................... 445
Tables .................................................................................................................................................................................. 445
Trees .................................................................................................................................................................................... 446
Immediate Solutions .......................................................................................................... 447
Handling Viewports ......................................................................................................................................................... 447
Creating Scroll Panes ........................................................................................................................................................ 450
Creating Scroll Pane Headers and Borders .................................................................................................................... 454
Scrolling Images ................................................................................................................................................................ 455
Creating Sliders ................................................................................................................................................................. 456
Filling a Slider .................................................................................................................................................................... 459
Painting Slider Tick Marks ............................................................................................................................................... 460
Painting Slider Labels ....................................................................................................................................................... 460
Setting the Slider Extent ................................................................................................................................................... 461
Creating Scrollbars ............................................................................................................................................................ 462
Creating Lists ..................................................................................................................................................................... 465
Handling Multiple List Selections ................................................................................................................................... 469
List Selection Modes ...................................................................................................................................................... 469
Displaying Images in Lists ............................................................................................................................................... 470
Creating a Custom List Model ......................................................................................................................................... 471
Creating a Custom List Cell Renderer ............................................................................................................................ 472
Handling Double Clicks in Lists...................................................................................................................................... 472
Drag and Drop Support.................................................................................................................................................... 473
Creating a Table................................................................................................................................................................. 476
Table Sorting and Filtering............................................................................................................................................... 478
Sorting Rows................................................................................................................................................................... 478
xvii
Table of Contents
Filtering Table Rows ...................................................................................................................................................... 480
Adding Rows and Columns to Tables at Runtime........................................................................................................ 482
Creating Trees .................................................................................................................................................................... 483
Adding Data to Trees ........................................................................................................................................................ 484
Handling Tree Events ....................................................................................................................................................... 486
Summary ............................................................................................................................................................................ 488
Chapter 14: SwingCombo Boxes, Progress Bars, Tooltips,
Separators, and Choosers ................................................................................. 489
In Depth .............................................................................................................................. 490
Combo Boxes ..................................................................................................................................................................... 490
Progress Bars...................................................................................................................................................................... 490
Choosers ............................................................................................................................................................................. 490
Tooltips ............................................................................................................................................................................... 490
Separators ........................................................................................................................................................................... 491
Immediate Solutions .......................................................................................................... 492
Creating Combo Boxes ..................................................................................................................................................... 492
Handling Combo Box Selection Events .......................................................................................................................... 496
Creating Editable Combo Boxes ...................................................................................................................................... 497
Adding Images to Combo Boxes ..................................................................................................................................... 499
Creating a Combo Box Model.......................................................................................................................................... 500
Creating a Combo Box Custom Renderer ...................................................................................................................... 500
Creating Progress Bars...................................................................................................................................................... 500
Updating Progress Bars .................................................................................................................................................... 503
Handling Progress Bar Events ......................................................................................................................................... 504
Creating Tooltips ............................................................................................................................................................... 505
Creating Separators ........................................................................................................................................................... 507
Resizing Separators Automatically ................................................................................................................................. 508
Creating Color Choosers .................................................................................................................................................. 510
Creating File Choosers ...................................................................................................................................................... 512
Creating File Chooser Filters ........................................................................................................................................... 518
Summary ............................................................................................................................................................................ 520
Chapter 15: SwingLayered Panes, Tabbed Panes, Split Panes, and Layouts................... 521
In Depth .............................................................................................................................. 522
Layered Panes .................................................................................................................................................................... 522
Tabbed Panes ..................................................................................................................................................................... 522
xviii
Table of Contents
Split Panes .......................................................................................................................................................................... 522
Layouts ............................................................................................................................................................................... 522
Immediate Solutions .......................................................................................................... 523
Understanding Swing Components and Z-order ......................................................................................................... 523
Making Swing Components Transparent ...................................................................................................................... 524
Using Layered Panes ........................................................................................................................................................ 525
Creating Tabbed Panes ..................................................................................................................................................... 527
Specifying Tab Placement in the Tabbed Panes ............................................................................................................ 532
Using Split Panes ............................................................................................................................................................... 535
Making Split Panes One-Touch Expandable ................................................................................................................. 538
Setting Split Pane Orientation.......................................................................................................................................... 539
Setting Split Pane Divider Size ........................................................................................................................................ 540
Using the Box Layout Manager ....................................................................................................................................... 541
Using the Box Class .......................................................................................................................................................... 543
Using the Overlay Layout Manager ............................................................................................................................... 547
Summary ............................................................................................................................................................................ 548
Chapter 16: SwingMenus and Toolbars .............................................................................. 549
In Depth .............................................................................................................................. 550
Menus ................................................................................................................................................................................. 550
Toolbars .............................................................................................................................................................................. 550
Immediate Solutions .......................................................................................................... 551
Creating a Menu Bar ......................................................................................................................................................... 551
Creating a Menu ................................................................................................................................................................ 552
Creating a Menu Item ....................................................................................................................................................... 555
Creating a Basic Menu System ........................................................................................................................................ 557
Adding Images to Menu Items ........................................................................................................................................ 559
Creating Checkbox Menu Items ...................................................................................................................................... 560
Creating Radio Button Menu Items ................................................................................................................................ 562
Creating Submenus ........................................................................................................................................................... 564
Creating Menu Accelerators ............................................................................................................................................ 565
Enabling/Disabling and Changing Menu Items at Runtime....................................................................................... 567
Adding and Removing Menu Items at Runtime ........................................................................................................... 568
Adding Buttons and Other Controls to Menus ............................................................................................................. 569
Creating Pop-Up Menus................................................................................................................................................... 570
Creating Toolbars .............................................................................................................................................................. 574
xix
Table of Contents
Adding Combo Boxes and Other Controls to Toolbars................................................................................................ 576
Summary ............................................................................................................................................................................ 578
Chapter 17: SwingWindows, Desktop Panes, Inner Frames, and Dialog Boxes............... 579
In Depth .............................................................................................................................. 580
Windows ............................................................................................................................................................................ 580
Dialog Boxes ...................................................................................................................................................................... 580
Immediate Solutions .......................................................................................................... 581
Creating a Window ........................................................................................................................................................... 581
Designing Shaped and Translucent Windows .............................................................................................................. 583
Creating Translucent Windows ................................................................................................................................... 583
Creating Different Shaped Windows .......................................................................................................................... 587
Creating a Frame Window ............................................................................................................................................... 588
Creating a Desktop Pane .................................................................................................................................................. 589
Creating Internal Frames .................................................................................................................................................. 591
Using JOptionPane to Create Dialog Boxes ................................................................................................................... 598
Creating Option Pane Confirmation Dialog Boxes ....................................................................................................... 604
Creating Option Pane Message Dialog Boxes................................................................................................................ 605
Creating Option Pane Text Field Input Dialog Boxes................................................................................................... 606
Creating Option Pane Combo Box Input Dialog Boxes ................................................................................................ 608
Creating Option Pane Internal Frame Dialog Boxes ..................................................................................................... 609
Creating Dialog Boxes with JDialog ............................................................................................................................... 609
Getting Input from Dialog Boxes Created with JDialog ............................................................................................... 613
Summary ............................................................................................................................................................................ 614
Chapter 18: Working with Streams, Files, and I/O Handling ................................................. 615
In Depth .............................................................................................................................. 616
Streams, Readers, and Writers ......................................................................................................................................... 616
NIO...................................................................................................................................................................................... 616
Essentials in NIO ............................................................................................................................................................... 616
Buffers ............................................................................................................................................................................. 617
Charsets and Selectors ................................................................................................................................................... 620
Enhancements in NIO with Java 8 .................................................................................................................................. 620
The Path Interface .......................................................................................................................................................... 620
The Files Class................................................................................................................................................................ 622
The Paths Class .............................................................................................................................................................. 624
The File Attribute Interfaces ......................................................................................................................................... 625
xx
Table of Contents
The FileSystem Class .................................................................................................................................................... 626
The FileSystems Class .................................................................................................................................................. 627
The FileStore Class ........................................................................................................................................................ 628
Prospects of NIO ............................................................................................................................................................... 629
Immediate Solutions .......................................................................................................... 630
Working with Streams ...................................................................................................................................................... 630
The InputStream Class ................................................................................................................................................. 630
The OutputStream Class .............................................................................................................................................. 631
The ByteArrayInputStream Class ............................................................................................................................... 631
The ByteArrayOutputStream Class ............................................................................................................................ 633
The BufferedInputStream Class ................................................................................................................................. 635
The BufferedOutputStream Class .............................................................................................................................. 636
The FileInputStream Class........................................................................................................................................... 637
The FileOutputStream Class........................................................................................................................................ 638
Working with the Reader Class ...................................................................................................................................... 640
Working with the Writer Class........................................................................................................................................ 641
Accepting Input from the Keyboard with the InputStreamReader Class ................................................................. 641
Working with the OutputStreamWriter Class .............................................................................................................. 643
Working with Files ............................................................................................................................................................ 643
Using the File Class ....................................................................................................................................................... 643
Using the FileReader Class .......................................................................................................................................... 647
Using the FileWriter Class............................................................................................................................................ 648
Working with the RandomAccessFile Class ................................................................................................................. 649
Working with Character Arrays ...................................................................................................................................... 651
Using the CharArrayReader Class .............................................................................................................................. 651
Using the CharArrayWriter Class ............................................................................................................................... 653
Working with Buffers ....................................................................................................................................................... 654
Using the BufferedReader Class ................................................................................................................................. 654
Using the BufferedWriter Class .................................................................................................................................. 656
Working with the PushbackReader Class ..................................................................................................................... 656
Working with the PrintWriter Class............................................................................................................................... 657
Working with the StreamTokenizer Class .................................................................................................................... 659
Implementing the Serializable Interface ....................................................................................................................... 661
Working with the Console Class .................................................................................................................................... 665
Working with the Clipboard ............................................................................................................................................ 667
Working with the Printer ................................................................................................................................................. 667
xxi
Table of Contents
Printing with the Formatter Class ................................................................................................................................... 668
Using the System.out.printf() Method ....................................................................................................................... 668
Using the String.format() Method ............................................................................................................................... 669
Formatting Dates Using the String.format() Method ............................................................................................... 669
Using the java.util.Formatter Class ............................................................................................................................. 670
Scanning Input with the Scanner class ........................................................................................................................... 671
Summary ............................................................................................................................................................................ 672
Chapter 19: Working with Multiple Threads ........................................................................... 673
In Depth .............................................................................................................................. 674
Using Threads in Java ....................................................................................................................................................... 674
Life Cycle of a Thread ....................................................................................................................................................... 675
Synchronization of Threads ............................................................................................................................................. 676
Multithreaded Custom Class Loader.............................................................................................................................. 677
Immediate Solutions .......................................................................................................... 678
Getting the Main Thread .................................................................................................................................................. 678
Naming a Thread .............................................................................................................................................................. 678
Pausing a Thread ............................................................................................................................................................... 679
Creating a Thread with the Runnable Interface ........................................................................................................... 681
Creating a Thread with the Thread Class ...................................................................................................................... 684
Creating Multiple Threads ............................................................................................................................................... 686
Joining Threads.................................................................................................................................................................. 688
Checking if a Thread Is Alive .......................................................................................................................................... 689
Setting Thread Priority and Stopping Threads.............................................................................................................. 690
Synchronizing .................................................................................................................................................................... 692
Synchronizing Code Blocks .......................................................................................................................................... 693
Synchronizing Methods ................................................................................................................................................ 694
Synchronizing Classes ................................................................................................................................................... 696
Communicating between Threads .................................................................................................................................. 704
Suspending and Resuming Threads ............................................................................................................................... 705
Creating Graphics Animation with Threads ................................................................................................................. 707
Eliminating Flicker in Graphics Animation Created Using Threads .......................................................................... 710
Suspending and Resuming Graphics Animation .......................................................................................................... 711
Using Double Buffering .................................................................................................................................................... 713
Simplifying Producer-Consumer with the Queue Interface........................................................................................ 715
Implementing Concurrent Programming ...................................................................................................................... 717
Limitations of Synchronization Previous to J2SE 5.................................................................................................... 718
xxii
Table of Contents
Simplifying Servers Using the Concurrency Utilities ................................................................................................... 718
Knowing Various Concurrency Utilities ........................................................................................................................ 719
Learning about the java.util.concurrent Package ......................................................................................................... 719
Learning about the java.util.concurrent.locks Package .............................................................................................. 721
Reader/Writer Locks ..................................................................................................................................................... 721
Learning about the java.util.concurrent.atomic Package ............................................................................................ 722
Summary ............................................................................................................................................................................ 724
Chapter 20: Networking and Security with Java .................................................................... 725
In Depth .............................................................................................................................. 726
Basics of Networking ........................................................................................................................................................ 726
Networking Enhancements in Java SE 8 ..................................................................................................................... 727
JDK 8 Security Enhancements ...................................................................................................................................... 727
Sockets in Java ................................................................................................................................................................... 728
Client-Server Networking ................................................................................................................................................ 729
Proxy Servers ..................................................................................................................................................................... 729
Internet Addressing .......................................................................................................................................................... 730
Domain Name Service ...................................................................................................................................................... 730
Inet4Addresses and Inet6Addresses ............................................................................................................................... 730
The URL Class ................................................................................................................................................................... 731
The URI Class .................................................................................................................................................................... 731
URI Syntax and Components .......................................................................................................................................... 732
TCP/IP and Datagram ..................................................................................................................................................... 732
Blackboard Assignment Retrieval Transaction ............................................................................................................. 732
Immediate Solutions .......................................................................................................... 734
Understanding Networking Interfaces and Classes in the java.net Package............................................................. 734
The Networking Interfaces and Classes ...................................................................................................................... 734
Understanding the InetAddresses.................................................................................................................................. 736
IP Addresses Scope ........................................................................................................................................................ 736
Host Name Resolution .................................................................................................................................................. 736
Caching InetAddress ........................................................................................................................................................ 736
Factory() Method ........................................................................................................................................................... 739
Instance() Method .......................................................................................................................................................... 740
Creating and Using Sockets ............................................................................................................................................. 740
Creating TCP Clients and Servers ................................................................................................................................... 743
TCP/IP Client Sockets ................................................................................................................................................... 744
xxiii
Table of Contents
Understanding the Whois Example................................................................................................................................ 746
TCP/IP Server Sockets .................................................................................................................................................. 746
Submitting an HTML Form from a Java Program ........................................................................................................ 748
Handling URL ................................................................................................................................................................... 749
Using the URLConnection Objects ................................................................................................................................. 752
Working with Datagrams ................................................................................................................................................. 756
DatagramPacket ............................................................................................................................................................. 756
Datagrams Server and Client ........................................................................................................................................... 758
Working with BART ......................................................................................................................................................... 759
Learning about the java.security Package ..................................................................................................................... 761
The Permission Class ..................................................................................................................................................... 764
The Policy Class ............................................................................................................................................................. 764
Summary ............................................................................................................................................................................ 766
Chapter 21: Collections........................................................................................................... 767
In Depth .............................................................................................................................. 768
The Collection Interfaces .................................................................................................................................................. 768
The Collection Classes ...................................................................................................................................................... 768
The Map Interfaces ........................................................................................................................................................... 769
The Map Classes................................................................................................................................................................ 769
Collections Framework Enhancements in Java SE 8 ..................................................................................................... 769
Support for Lambda Expressions, Streams, and Aggregate Operations ................................................................ 770
Performance Improvement for HashMaps with Key Collisions .............................................................................. 774
Improved Type Inference.............................................................................................................................................. 774
Immediate Solutions .......................................................................................................... 776
Using the Collection Interface ......................................................................................................................................... 776
The Queue Interface ......................................................................................................................................................... 777
The List Interface ............................................................................................................................................................... 777
The Set Interface ................................................................................................................................................................ 778
The SortedSet Interface .................................................................................................................................................... 779
Using the Collection Classes ........................................................................................................................................... 779
The AbstractCollection Class ...................................................................................................................................... 779
The AbstractList Class .................................................................................................................................................. 780
The AbstractSequentialList Class ............................................................................................................................... 781
The ArrayList Class ....................................................................................................................................................... 782
The ArrayDeque Class .................................................................................................................................................. 784
The LinkedList Class .................................................................................................................................................... 786
xxiv
Table of Contents
The Generic Class .......................................................................................................................................................... 788
The HashSet Class ......................................................................................................................................................... 789
The TreeSet Class .......................................................................................................................................................... 790
Using the Comparator Interface ...................................................................................................................................... 792
Using the Iterator Interface .............................................................................................................................................. 793
Using the ListIterator Interface ....................................................................................................................................... 793
Using the AbstractMap Class .......................................................................................................................................... 795
Using the HashMap Class................................................................................................................................................ 796
Using the TreeMap Class ................................................................................................................................................. 799
Using the Arrays Class ..................................................................................................................................................... 801
Learning the Fundamentals of Enumerations ............................................................................................................... 804
The values() and valueOf() Methods .......................................................................................................................... 806
Java Enumeration as a Class Type ............................................................................................................................... 807
Enumeration Inheriting Enum ..................................................................................................................................... 808
The Enumeration Interface ........................................................................................................................................... 810
The Legacy Classes and Interfaces .................................................................................................................................. 810
The Vector Class ............................................................................................................................................................ 811
The Stack Class .............................................................................................................................................................. 813
The Dictionary Class ..................................................................................................................................................... 814
The Hashtable Class ...................................................................................................................................................... 815
The Properties Class ...................................................................................................................................................... 817
Using the Aggregate Operations ..................................................................................................................................... 818
Using the java.util.function Package ............................................................................................................................. 819
Summary ............................................................................................................................................................................ 822
Chapter 22: Creating Packages, Interfaces, JAR Files, and Annotations ............................. 823
In Depth .............................................................................................................................. 824
Packages and Interfaces .................................................................................................................................................... 824
JAR Files ............................................................................................................................................................................. 824
The Core Java API Package .............................................................................................................................................. 824
The java.lang Package ....................................................................................................................................................... 826
The java.lang.annotation Subpackage ........................................................................................................................ 826
The java.lang.instrument Subpackage ....................................................................................................................... 826
The java.lang.management Subpackage .................................................................................................................... 826
The java.lang.reflect Subpackage ................................................................................................................................ 826
The java.lang.invoke Subpackage ............................................................................................................................... 827
The java.lang.ref Subpackage ...................................................................................................................................... 827
xxv
Table of Contents
Basics of Annotation ......................................................................................................................................................... 827
Other Built-In Annotations .............................................................................................................................................. 828
@Retention Annotation ................................................................................................................................................. 828
@Documented Annotation............................................................................................................................................ 828
@Target Annotation ....................................................................................................................................................... 828
@Native Annotation ...................................................................................................................................................... 829
@Repeatable Annotation ............................................................................................................................................... 829
@Retention Annotation ................................................................................................................................................. 829
@Inherited Annotation .................................................................................................................................................. 829
@Override Annotation .................................................................................................................................................. 829
@Deprecated Annotation .............................................................................................................................................. 830
@SuppressWarnings Annotation ................................................................................................................................. 830
@FunctionalInterface ..................................................................................................................................................... 830
@ SafeVarargs ................................................................................................................................................................. 830
Type Annotations and Pluggable Type Systems ....................................................................................................... 831
Repeating Annotations .................................................................................................................................................. 831
Retrieving Annotations ................................................................................................................................................. 831
Immediate Solutions .......................................................................................................... 832
Creating a Package ............................................................................................................................................................ 832
Creating Packages that have Subpackages .................................................................................................................... 832
Creating an Interface ......................................................................................................................................................... 833
Implementing an Interface ............................................................................................................................................... 834
Extending an Interface ...................................................................................................................................................... 835
Using Interfaces for Callbacks ......................................................................................................................................... 835
Performing Operations on a JAR File ............................................................................................................................. 836
Creating a JAR File......................................................................................................................................................... 837
Getting the Contents of a JAR File ............................................................................................................................... 838
Extracting Files from a JAR File ................................................................................................................................... 838
Updating JAR Files ........................................................................................................................................................ 838
Reading from JAR Files in Code .................................................................................................................................. 838
Using javac to Get Classes from a JAR File ................................................................................................................ 841
Letting Applets Get Classes from JAR Files ............................................................................................................... 841
Marker Annotations .......................................................................................................................................................... 842
Single Member Annotations ............................................................................................................................................ 843
Summary ............................................................................................................................................................................ 844
xxvi
Table of Contents
Chapter 23: Working with Java Beans ................................................................................... 845
In Depth .............................................................................................................................. 846
What is Java Bean? ............................................................................................................................................................ 846
Advantages of Java Bean .................................................................................................................................................. 847
Introspection ...................................................................................................................................................................... 847
Design Patterns for Properties...................................................................................................................................... 847
Design Patterns for Events ............................................................................................................................................ 848
Methods and Design Patterns ...................................................................................................................................... 849
Using the BeanInfo Interface ........................................................................................................................................ 849
Persistence .......................................................................................................................................................................... 849
Customizers ....................................................................................................................................................................... 849
Immediate Solutions .......................................................................................................... 850
Understanding Java Beans ............................................................................................................................................... 850
Designing Programs Using Java Beans .......................................................................................................................... 850
Creating Applets that Use Java Beans ............................................................................................................................ 853
Creating a Java Bean ......................................................................................................................................................... 853
Creating a Bean Manifest File .......................................................................................................................................... 855
Creating a Bean JAR File .................................................................................................................................................. 855
Creating a New Bean ........................................................................................................................................................ 855
Adding Controls to Beans ................................................................................................................................................ 855
Giving a Bean Properties .................................................................................................................................................. 856
Design Patterns for Properties ......................................................................................................................................... 862
Using Simple Properties ................................................................................................................................................... 862
Adding a Color Property to SimpleBean .................................................................................................................... 862
Using Indexed Properties ............................................................................................................................................. 864
Using Boolean Properties .............................................................................................................................................. 864
Designing Patterns for Events ......................................................................................................................................... 864
Learning Methods and Design Patterns ......................................................................................................................... 865
Using the BeanInfo Interface ........................................................................................................................................ 865
Using Feature Descriptors ............................................................................................................................................ 865
Creating Bound Properties ............................................................................................................................................... 865
Giving a Bean Methods .................................................................................................................................................... 866
Giving a Bean an Icon ....................................................................................................................................................... 867
Creating a BeanInfo Class ............................................................................................................................................... 867
Setting Bound and Constrained Properties.................................................................................................................... 868
xxvii
Table of Contents
Implementing Persistence ................................................................................................................................................ 870
Using the Java Beans API ................................................................................................................................................. 870
Learning the Basics of an Event ....................................................................................................................................... 872
Using the Java Beans Conventions .................................................................................................................................. 873
Using the Remote Notification and Distributed Notification ...................................................................................... 873
Using Beans with JSP ........................................................................................................................................................ 873
Summary ............................................................................................................................................................................ 874
Chapter 24: Introducing JDBC ................................................................................................ 875
In Depth .............................................................................................................................. 876
What does JDBC Do? ........................................................................................................................................................ 876
Components of JDBC..................................................................................................................................................... 876
JDBC Specification ......................................................................................................................................................... 877
JDBC Architecture.......................................................................................................................................................... 877
The JDBC Package ............................................................................................................................................................. 878
The java.sql Package ..................................................................................................................................................... 879
The javax.sql Package ................................................................................................................................................... 881
JDBC versus ODBC and Other APIs ............................................................................................................................... 883
Relation between JDBC and ODBC................................................................................................................................. 883
Various Kinds of JDBC Drivers ....................................................................................................................................... 884
Describing the Type-1 Driver ....................................................................................................................................... 884
Describing the Type-2 Driver (Java to Native API) ................................................................................................... 885
Describing the Type-3 Driver (Java to Network Protocol/All Java Driver) ........................................................... 886
Describing the Type-4 Driver (Java to Database Protocol) ....................................................................................... 888
The JavaSoft Framework .................................................................................................................................................. 888
Two-Tier and Three-Tier Models .................................................................................................................................... 889
The Structured Query Language (SQL) .......................................................................................................................... 890
Immediate Solutions .......................................................................................................... 892
Learning about the Driver Interface................................................................................................................................ 892
Learning about the DriverManager Class ...................................................................................................................... 892
The Connection Interface ................................................................................................................................................. 893
The Statement Interface .................................................................................................................................................... 896
The PreparedStatement Interface .................................................................................................................................... 899
Comparing the Execution Control of the Statement and PreparedStatement........................................................ 899
Describing the setXXX() Methods of the PreparedStatement Interface .................................................................. 901
Advantages and Disadvantages of Using a PreparedStatement Object ................................................................. 902
xxviii
Table of Contents
Using the PreparedStatement Interface .......................................................................................................................... 902
Create a PreparedStatement Object ............................................................................................................................. 903
Provide the Values of the PreparedStatement Parameters ....................................................................................... 903
Execute the SQL Statements ......................................................................................................................................... 903
The ResultSet Interface ..................................................................................................................................................... 904
Describing the Methods of ResultSet........................................................................................................................... 904
Using ResultSet .................................................................................................................................................................. 907
Moving the Cursor Position ......................................................................................................................................... 908
Reading the Column Values ......................................................................................................................................... 908
The ResultSetMetaData Interface .................................................................................................................................... 908
Describing the ResultSetMetaData Interface .............................................................................................................. 909
Using the ResultSetMetaData Interface .......................................................................................................................... 910
Implementing JDBC Processes with java.sql Package ................................................................................................. 911
Understanding the Basic JDBC Steps .......................................................................................................................... 912
Processing the ResultSet ................................................................................................................................................... 914
Using the ResultSet Object to Update Data ................................................................................................................ 919
Using the ResultSet Object to Delete a Row ............................................................................................................... 920
Using a ResultSet Object to Insert a Row .................................................................................................................... 922
Closing the Statement ....................................................................................................................................................... 923
Closing the Connection .................................................................................................................................................... 923
Using a Loop to Set Values in PreparedStatement Object ........................................................................................... 924
Returning Values for the executeUpdate() Method................................................................................................... 924
Using the Interactive SQL Tool ....................................................................................................................................... 926
Summary ............................................................................................................................................................................ 926
Chapter 25: Images and Animation ........................................................................................ 927
In Depth .............................................................................................................................. 928
Images ................................................................................................................................................................................. 928
Different Formats of Images ............................................................................................................................................ 928
The ImageIcon Class ........................................................................................................................................................ 928
The java.awt.geom Package............................................................................................................................................. 928
Immediate Solutions .......................................................................................................... 930
Using the Image Class ...................................................................................................................................................... 930
Creating an Image .......................................................................................................................................................... 930
Loading an Image .......................................................................................................................................................... 930
Displaying an Image ...................................................................................................................................................... 930
Drawing an Image Object ............................................................................................................................................. 931
xxix
Table of Contents
Loading an Image Object Using the ImageObserver Interface ............................................................................... 935
Using the MediaTracker Class ........................................................................................................................................ 937
Using the ImageIcon Class in an Applet ....................................................................................................................... 938
Getting Images ............................................................................................................................................................... 939
Drawing Images ............................................................................................................................................................. 940
Using ImageObserver Interface ...................................................................................................................................... 942
Creating a Game Using the java.awt.geom Package .................................................................................................... 943
Collecting the Images .................................................................................................................................................... 943
Organizing and Loading the Images in the Applet ................................................................................................... 944
Animating the Images ................................................................................................................................................... 945
Finishing Up ................................................................................................................................................................... 947
Summary ............................................................................................................................................................................ 950
Chapter 26: Java DB................................................................................................................ 951
In Depth .............................................................................................................................. 952
Evolution of Java DB ......................................................................................................................................................... 952
Comparisons between Java DB and MySQL ................................................................................................................. 953
Architecture of Java DB .................................................................................................................................................... 954
Embedded Architecture ................................................................................................................................................ 954
Client/Server Architecture ........................................................................................................................................... 954
Compilation of SQL into Java Bytecode ...................................................................................................................... 955
Drivers of Java DB ............................................................................................................................................................. 955
Java DB URLs..................................................................................................................................................................... 956
Java DB Product Documentation .................................................................................................................................... 956
Derby Tools and Utilities ................................................................................................................................................. 957
Installing and Configuring Java DB on Windows......................................................................................................... 957
Immediate Solutions .......................................................................................................... 958
Configure Environment Variables .................................................................................................................................. 958
DERBY_HOME .............................................................................................................................................................. 958
PATH ............................................................................................................................................................................... 958
JAVA_HOME ................................................................................................................................................................. 958
Java DB Directory Structure ............................................................................................................................................. 959
Creating Database in Java DB Using ij-Tool .................................................................................................................. 959
Creating a New Database in Embedded Mode .......................................................................................................... 959
Creating a New Database in Network Mode ............................................................................................................. 961
Connecting with a Database ............................................................................................................................................ 963
Connecting with a Database in Embedded Mode ..................................................................................................... 963
xxx
Table of Contents
Connecting with a Database in Network Mode ......................................................................................................... 963
Disconnecting from a Database ....................................................................................................................................... 964
Adding Tables in an Existing Database .......................................................................................................................... 964
Deleting Tables from an Existing Database ................................................................................................................... 964
Adding Data into a Table ................................................................................................................................................. 965
Displaying Content of a Table ......................................................................................................................................... 965
Java DB Database Encryption .......................................................................................................................................... 966
Using Java DB with Java Application ............................................................................................................................. 966
Summary ............................................................................................................................................................................ 968
Chapter 27: Java FX ................................................................................................................ 969
In Depth .............................................................................................................................. 970
Working with JavaFX........................................................................................................................................................ 970
JavaFX Applications ...................................................................................................................................................... 970
JavaFX Availability ........................................................................................................................................................ 970
Key Features of JavaFX ................................................................................................................................................. 971
Application Development Scope of JavaFX ................................................................................................................... 972
JavaFX Ensemble8 .......................................................................................................................................................... 972
Modena ........................................................................................................................................................................... 973
3DViewer ........................................................................................................................................................................ 973
JavaFX Architecture ....................................................................................................................................................... 974
Scene Graph in JavaFX .................................................................................................................................................. 974
Java Public APIs for JavaFX Features .......................................................................................................................... 975
Graphics System............................................................................................................................................................. 975
Glass Windowing Toolkit ............................................................................................................................................. 976
Threads ............................................................................................................................................................................ 976
Pulse ................................................................................................................................................................................ 976
Media and Images .......................................................................................................................................................... 977
Web Component ............................................................................................................................................................ 977
CSS ................................................................................................................................................................................... 977
UI Controls ..................................................................................................................................................................... 978
Layout.............................................................................................................................................................................. 978
2-D and 3-D Transformations ....................................................................................................................................... 979
Visual Effects .................................................................................................................................................................. 979
Introducing Scene Builder in JavaFX .............................................................................................................................. 979
Intended Audience ........................................................................................................................................................ 980
Key Features of JavaFX Scene Builder ......................................................................................................................... 980
xxxi
Table of Contents
Immediate Solutions .......................................................................................................... 981
Creating Simple JavaFX Application .............................................................................................................................. 981
Creating JavaFX Application on NetBeans IDE ............................................................................................................ 981
Using the UI Controls ....................................................................................................................................................... 989
Using Visual Effects .......................................................................................................................................................... 989
Using Canvas API ............................................................................................................................................................. 990
Summary ............................................................................................................................................................................ 992
Glossary .................................................................................................................................. 993
Index ........................................................................................................................................ 997
Bonus chapters available with the book for Download
Chapter 1: Java and XMLUsing the Document Object Model ................................................ 1
Chapter 2: Java and XMLUsing the Simple API for XML ...................................................... 31
Chapter 3: Understanding RMI ................................................................................................. 57
Chapter 4: Working with Servlets 3.1 ....................................................................................... 83
Chapter 5: Dynamic Java Scripting ........................................................................................ 137
Chapter 6: Introduction to Groovy.......................................................................................... 159
Chapter 7: MXBeans and JMX ................................................................................................ 189
Chapter 8: Inclusion of Sound ................................................................................................ 213
Chapter 9: Filing and Printing Documents ............................................................................. 251
xxxii
Introduction
Thanks for buying the Java 8 Programming Black Book. The book covers Java 8 a 2014-released Java version in
a comprehensive and accessible manner.
Java is a programming language that all novice programmers are willing to learn for building applications. Here
this book helps by offering simple to complex Java programming concepts along with various programming
examples. You will find programs on all Java concepts, which are meant for easy assimilation of a concept.
With the evolution of Java 8, various new concepts emerged, which are also part of this book. Its each chapter
has been divided into In Depth and Immediate Solutions sections: where the In Depth section is about the
theoretical understanding of one concept, the Immediate Solutions section is about the practical implementation of
the same.
The most important feature of Java programming language is that it offers security; therefore, it is preferred over
other programming languages. As most system applications are written in this language, it is only better that
programmers be well versed with Java programming language.
About this Book
Java 8 Programming Black Book encompasses syntax to declare variables, as well as advanced object-oriented
concepts. The book also deals with the programming implementation of the concepts explained. Using Java with
XML, setting security permissions for applets, using the Java browser plugin, creating client/server connections
over the Internet, creating Java Beans, connecting to databases, and multithreading have also been covered.
The book is divided into hundreds of topics topics that are well spaced, easily accessible, each addressing a
different programming issue, and each with an example showing just how it works. Here are just a few of those
topics:
Full Java 8 version 1.8 syntax
Inheritance and inner classes
Object-Oriented Programming (OOP)
Abstract Windowing Toolkit (AWT)
Generics
Metadata
Enumeration
Autoboxing and Unboxing
Buttons, checkboxes, and radio buttons
Choosers, lists, and combo boxes
Graphics, images, text, and fonts
Menus, dialog boxes, and windows
Progress bars, sliders, separators, and scrolling
Image processing and tracking
Introduction
Java Swing
Swings pluggable look and feel
All Swing components
Swing text components
Java collections
Multithreading
I/O Streams
File handling
Networking and sockets
Split panes, editor panes, text panes, and more
Trees and tables
Java Beans
MXBeans
Packages, interfaces, and JAR files
Java Server Pages (JSP)
Reading applets from JAR files
Security issues
Java Database Connectivity (JDBC)
Servlets
Java DB
Java FX
You will also come to know of some good online resources. In addition, there are some bonus chapters in the
book on the topics like Java and XML, Groovy, Sounds in Java, and many more.
How to Make Use of This Book
In the book, since we are using Java 8, version 1.8, the given codes must be run in the same version; or else, you
might get some strange errors. You can get this version of Java for you from the
http://www.oracle.com/technetwork/java/javase/downloads/index.html URL.
Youll also need some way of creating Java programs. Such programs are just plain text files filled with Java
statements and declarations. To create a Java program, you should have an editor program that can save files in
a plain text format. See the topic Writing Code: Creating Code Files in Chapter 1 for details.
The JDK has all you need to create standard Java applets and applications, and also has an appletviewer for
displaying applets at work.
Besides, we will also be using Beans Development Kit (BDK) and Java Servlet Development Kit (JSDK). There is
also Java Server Pages (JSP) in the book, for which you will need a web-server-supporting JSP. If you want to
work with the database programming of this book, you will need to create an ODBC data source on your
machine. All the codes, images, and files used in the book can also be found online not to mention a great
number of other tools.
Conventions
There are a few conventions in the book that you should know in the first place. Some of them are as follows:
When some code is new and needs to be pointed out, itll appear shaded like this:
setLayout(null);
text1 = new TextField(20);
text1.setSize(200, 50);
text1.setLocation(20, 20);
add(text1);
xxxiv
Introduction
The book also gives many tips throughout for you to have more insight into the subject. Ex:
An untrusted applet is not allowed to read and write files at all. So unless you make specific security arrangements, you should
not try to read or write files from applets. Therefore, for the sake of convenience, all the programs in this chapter are
applications.
You will also see notes for some additional information on the subject. Ex:
It should be clear that there are situations where the Refresh response header can come in handy. Even though it is not a
standard HTTP 1.1 header, it is something that can be considered a de facto standard.
Every figure has a caption to maintain clarity. Ex:
Figure 32.1: Showing Client/Server communication.
The tables follow right below their reference. Ex:
Table 7.1: Constructors of the TextField class
Constructor Does this
TextField() It constructs a new text field.
TextField(int columns) It constructs a new, empty text field with the indicated number of columns.
TextField(String text) It constructs a new text field with the indicated text.
TextField(String text, int It constructs a new text field initialized with the indicated text and with the
columns) indicated number of columns.
Other Resources
Java comes with an immense amount of documentation equal to and worth hundreds of books! This
documentation is stored in linked HTML pages, and you must have a web browser to view and work with it.
There are also many, many webpages out there on Java (a random Web search on Java turns up about
239,000,000 pages; in fact, searching for Java tutorial alone will turn up about 35,700,000 pages). Here are some
other useful resources:
The Java home page at http://www.oracle.com/technetwork/java/index.html
The Sun Java tutorial at http://docs.oracle.com/javase/tutorial/
The Java 8, version 1.8 documentation at http://docs.oracle.com/javase/8/docs/
xxxv
Introduction
The Black Book Philosophy
Written by experienced professionals, Black Books provide immediate solutions to global programming and
administrative challenges, helping you to complete specific tasks, especially critical ones, which are not well
documented in other books. Black Books help you understand a concept and then implement it practically by
developing codes and applications based on that concept. The unique format of Black Books is structured to help
you build your knowledge to solve problems and quickly master complex technical issues to become an expert.
The discussion of complex topics has been split over many subheadings, each dealing with a particular aspect of
that topic, enabling an easy and quick understanding.
Written and edited by the Content and Editorial teams at Dreamtech Press, this book is conceptualized to give
you everything you need to know about Java 8.
xxxvi
1
Essential Java
If you need an immediate solution to: See page:
Getting and Installing Java 15
Subfolders Created by JDK 16
Creating Source Files 16
Knowing Javas Reserved Words 17
Creating an Application 19
Compiling Code 20
Running Code 23
Running Code: Using Command-Line Options 25
Commenting Your Code 26
Import Java Packages and Classes 27
Finding Java Classes with CLASSPATH 28
1
Chapter 1: Essential Java
In Depth
Welcome to our big book of Java programming. Herein, well cover as much Java programming as can be
crammed into one bookin depth and in detail. We wont turn away from the more difficult issues because the
aim of this book is to lay out all of Java for you, making it ready for use. If you are like us and have a few
programming packages, youll enjoy working with Java more than with others. And, we would like to presume
that Java would be your choice for programming platform as you finish the book.
This first chapter covers the fundamental Java skills that youll rely on in the coming chapters. In the next few
chapters, you are going to see a large amount of Java syntax at work, but none will be of any use unless you can
get Java running and create programs with it. That fundamental set of skillscreating and running Java
programsis the topic of this chapter, and you can put this information to work in the following chapters for
testing the Java syntax well develop.
In this chapter, we are going to work through the mechanics of creating Java programsfrom installation issues
to writing Java code and from making sure your Java program can find what it needs to displaying simple
output. These skills are the ones you can use in the coming chapters. The material in those chapters is all about
the internals of writing a Java code, and this chapter is all about the rest of the process that makes the code run.
You might already be knowing much of the material in this chapter, in which case it will provide a good review
(some of the material is bound to be newafter all, very few people know what all the Java compiler command-
line switches do). If youve already got a working installation of Java and can write and run basic Java programs,
you are already familiar with most of what youll see in this chapter. Therefore, you can just skim through the
following pages and continue with Chapter 2, where we start digging into Java syntaxthe internals that really
make Java work. Otherwise, you can work through the material in this chapter because it provides the
foundation for the next several chapters to come. Here, well also make you familiar with the Application
servers, Deployers, and various methods and constructors.
All about Java
Where did Java come from, and why is it so popular? Like other programming languages, Java filled a specific
need of its time. For example, before Java appeared, C was an extremely popular language among programmers,
and it seemed that C was the perfect one combining the best elements of low-level assembly language and high
level languages into a programming language that fits into computer architecture well and that programmers
liked.
However, C too had its limitations like the earlier programming languages had before it. As programs grew
longer, C programs became more unwieldy, because there was no easy way to cut up a long C program into self-
contained compartments. This meant that the code in the first line of a long program could interfere with the
code in the last line, and the programmer had to keep the whole code in mind while programming.
To cut long programs into semi-autonomous units, Object-Oriented Programming became popular. With this,
the motto was divide and conquer. In other words, you could divide a program into easily conceptualized
parts. For example, if you have a complex system that you use to keep food cold, you might watch the
temperature of the food using a thermometer; and when the temperature gets high enough, you throw a switch
to start the compressor for making the valves work so that the coolant circulates; then, you start a fan to blow air
over the cooling vanes, and so on. Thats one way to do it. However, another is to connect all those operations
for making them automatic, wrapping the whole into an easily conceptualized unita refrigerator. Now, all the
internals are hidden from your view, and all you have to do is put food in it or take it out of the refrigerator.
Thats the way objects work; They hide the programming details from the rest of the program, reducing all the
interdependencies that spring up in a long C program by setting up a well-defined and controllable interface
that handles the connection between the object and the rest of the code. Now, you can think of the object in an
easy wayfor example, you might have an object that handles all the interaction with the screen, an object you
call Screen. You can use that object in ways youll see throughout this book to manipulate what it is intended to
work on (in this case, the screen display). After creating the object, you know that the screen is handled by that
2
In Depth
object and can put it out of your mindno longer does every part of the code has to set up its own screen
handling; you can just use the Screen object instead.
When Object-Oriented Programming was added to C, it became C++, and the programmers had a new darling.
C++ let programmers deal with longer programs and object-oriented code, which helped to solve many other
problems as well. For example, supporting objects made it easier for the manufacturers that supply software to
provide you with lots of prewritten code, ready to use. To create an object, you use a class, which acts like a
template or cookie cutter for that object, that is, a class is to an object what a cookie cutter is to a cookie. In other
words, you can think of a class as an objects type, much like a variables type might be the integer type.
Because C++ supported classes, the software manufacturers could provide you with huge readymade libraries of
classes, ready for you to start creating objects from. For example, one of the most popular libraries of C++ classes
is the Microsoft Foundation Class (MFC) library that comes with Microsofts Visual C++. Earlier, you wrote a
Windows program in C, you needed about five pages of solid code just to display a blank window. However,
using a class in the MFC library, you could simply create an object of the kind of window you wanted to use
with a border, without a border, as a dialog box, and so on. The object already had built-in functionality of the
kind of window you wanted to create, so all it took to create that window was one line of codejust the line
where you create the new window object from the class you selected.
Even more impressive was the fact that you could use an MFC class as a base class for your own classes, adding
the functionality you want to that class through a process called inheritance in Object-Oriented Programming. For
example, suppose you want your window to display a menu bar. You can derive your own class from a plain
MFC window, adding a menu bar to that class to create a new class. In this way, you can build your own class
just by adding a few lines of code to what the Microsoft programmers have already done. (Note that youll see
how Object-Oriented Programming works in depth in this book.)
All this seemed great to programmers, and C++s star rose high. It appeared to many that the perfect
programming language had arrived. What could be better? However, the programming environment itself was
about to undergo a great change with the popularization of what amounted to an immense new programming
environmentthe Internet. And, thats what made Java so popular.
Java Appears
Java was not originally created for the Internet. The first version of Java appeared in 1991 and was written in 18
months at Sun Microsystems. In fact, it wasnt even called Java in those days; it was called Oak and was used
internally at Sun.
The original idea of Oak was to create a platform-independent, object-oriented language. Many programmers
were confining themselves to programming for the IBM PC at that time, but the corporate environment can
include all kinds of programming platformsfrom PC to huge mainframes. The driving inspiration behind Oak
was to create something that could be used on all those computers (and now that Java has been popularized by
the Internet, a huge and increasing number of corporations are adopting it internally instead of C++ for just that
reasonin fact, some versions of C++, such as Microsofts C#, are now being modeled after Java). The other
motivation behind the introduction of Oak was to bring a language in the picture that could be used in consumer
electronics.
Oak was renamed Java in 1995, when it was released for public consumption, and it was almost an immediate
hit. By that time, Java had adopted a model that made it perfect for the Internetthe bytecode model. At
present, Sun has been taken over by Oracle; therefore, the platforms of Java are the products of Oracle now.
All about Bytecodes
A Microsoft Visual C++ program is large, typically starting off at a minimum of 5 MB for a full MFC program
and that doesnt even count the Dynamic Link Libraries (DLLs) that the Windows platform needs to run Visual
C++ programs. In other words, C++ programs are fully executable on your computer as they stand, which
means they have to be large in size. Imagine how cumbersome it would be to download all that as part of a Web
page for letting that page do something interactive on your computer.
Java programs, on the other hand, are constructed differently. Java itself is implemented as the Java Virtual
Machine (JVM), which is the application that actually runs your Java program. When JVM is installed on a
3
Chapter 1: Essential Java
computer, it can run Java programs. Java programs, therefore, dont need to be self-sufficient, and they dont
have to include all the machine-level code that actually runs on the computer. Instead, they are compiled into
compact bytecodes, and its these bytecodes that JVM reads and interprets to run your program. When you
download a Java applet from the Internet, you are actually downloading a bytecode file.
In this way, your Java program can be very small, because all the machine-level code to run your program is
already on the target computer and doesnt have to be downloaded. To host Java on a great variety of
computers, Sun only had to rewrite JVM for wording on those computers. Because your program is stored in a
bytecode file, it will run on any computer on which the JVM is installed.
As Java programs were originally supposed to be interpreted by the JVM, that is, they were executed bytecode
by bytecode, interpretation was a slow process. For that reason, Java introduced the Just-In-Time (JIT) compiler,
which is built into JVM. The JIT compiler reads sections of the bytecode and compiles them dynamically into a
machine-level code. Java performs runtime checks on different code sections; therefore, the whole program is not
compiled at once, resulting in the a faster execution of the programs.
Using bytecodes means that the Java programs are very compact, making them ideal for downloading over the
Internet. Moreover, running such programs with the JVM rather than downloading full programs provides
security.
Features of Java
Java is a simple, robust, platform-independent, and portable programming language. It is designed to meet the
real-world requirements with its following features:
Simple
Secure
Portable
Robust
Multithreading
Platform independent
Distributed
Dynamic
Simple
Java is simple to learn and use. In Java, it is easy to write and debug programs because Java does not use
pointers. Moreover, it provides bug free system because to strong memory management and also has automatic
memory allocation and de-allocation system. Unlike other programming languages, which provide dozens of
complicated ways to perform a simple task, Java provides a simple and clear approach to achieve a given task. If
a programmer understands the basic concepts of OOP, it becomes easier for him/her to learn Java.
Secure
In todays world, everybody needs safety and security. Because of to the threat of hackers, people feel unsafe
while performing commerce over the Internet. To overcome such fears, Java provides safety and security
features.
While using Java-compatible browser, everyone can safely download Java applets by relaxing their minds from
the fear of virtual infection or malicious intent. The Java programs are confined to the Java runtime environment,
they can access only that part of your computer that is required for program execution. The data outside Java
runtime environment cannot be accessed by them and therefore, downloading a Java application through the
Internet will not harm your computer. Thats why Java is a secure language.
When Java executes a program, the JVM can strictly monitor what goes on, which makes it great for the Internet
applications. You are already aware that security has become an extremely important issue on the Internet, and
Java rises to the task of taking care of the same. JVM can watch all that a program does; and if it does something
questionable, such as trying to write a file, it can prevent that operation. That alone makes Java more attractive
than C++, which has no such restrictions, for the Internet.
4
In Depth
You can also tailor Java security the way you like it, which offers a very flexible solution. As youll see in this
book, you can now specify, on a program-by-program basis, just what privileges you want to give to the
downloaded code. You can now also sign your Java code in a way that shows it comes from you without any
malicious modifications. Well take a look at all this and more in this book.
In a nutshell, Java has a winning combination for the InternetJava programs are small, secure, platform-
independent, object-oriented, and powerful. They also implement other features that programmers like. Java
programs are often simple to write compared to C++. The end result is that you can write your Java program
once, and it can be easily downloaded and run on all kinds of machinesthe perfect recipe for the Internet!
Thats the reason Java has soared so high.
Portable
In the distributed world of the Internet, an application developed with the help of a programming language
might be accessed on various computers having different kinds of operating system. But, its not guaranteed that
the application is portable, that is, it runs successfully on all operating systems. To overcome this portability
issue, Java introduces a concept of what is known as bytecode.
Bytecode is a set of instructions generated by the Java compiler while compiling a Java program. In other
programming languages, a program is compiled into an executable code; but in Java, a program gets compiled
into an intermediate code called bytecode. This bytecode then gets executed by Java runtime system called the
JVM. So, in order to run your Java program, you should have only JVM installed. It is also considered to be the
interpreter of bytecode. In this way, Java has solved the problem of portability.
Robust
Generally, programs fail because of the following two reasons:
Memory ManagementLack of memory management for allocating and de-allocating memory for objects
Exceptional ConditionsOccurrence of unexpected exceptions
Considering these reasons, Java was designed to provide the ability to create robust programs. Therefore, Java
compels the programmers to resolve mistakes during compilation. Moreover, it also frees the programmer from
the worries of common causes of programming errors as the program code is verified during compilation.
Java also eradicates the problem of memory management by performing automatic garbage collection. It
manages the memory allocation and de-allocation for unused objects.
Multithreading
Java is a programming language that is designed for the distributed environment of the Internet; and for that,
the concept of multithreading is implemented. This feature helps you write interactive programs, wherein
multiple tasks can be performed simultaneously, thus making Java a robust programming language.
Java is inherently multi threaded as there can be multiple executing threads in a single Java program. For
example, a Java programmer can run three Java applets on the same page, provided that each applet gets equal
time from the CPU.
The multi threaded feature of Java makes it very responsive and robust. It is very important to note that as Java
is highly multi threaded, it is difficult to port it to architectures, such as Windows 3.1 or PowerMac, which do
not natively support multithreading.
Platform-Independent
It is one of the most important features of Java as it is the first programming language that is not bound to any
specific operating system. In other words, Java programs can be executed anywhere on any system. Before the
evolution of Java, no other programming language was platform-independent, and it can therefore be said that
Java is a revolutionary technology. Apart from cross-platform in source form, Java is also platform-independent
in complied binary form.
A Java program does not execute natively on the host machine; instead, a Java interpreter reads the bytecode
and executes the corresponding native machine instructions. The Java interpreter is a special naive program that
reads the bytecode, an intermediate form after compilation. Therefore, in order to port a Java program to a new
5
Chapter 1: Essential Java
platform, you need the interpreter and some of the library routines. Moreover, the Java compiler is also written
in Java, and the bytecodes are precisely defined, which remain the same on all platforms.
Distributed
Java is a distributed language as it can be used to create applications for communicating over the network. Java
can communicate over the network because it supports TCP/IP (Transmission Control Protocol/Internet
Protocol). The TCP/IP protocol is a set of network communication protocols.
Dynamic
During the runtime of a Java program, the relevant information that is used to verify and resolve access to
objects is required. This concept of providing runtime information is referred to as dynamically linking the code.
This feature of Java adds strength to the applet environment, in which small fragments of bytecode are
dynamically updated on a running system.
Java Environment
The Java environment comprises numerous development tools, classes, and methods. The development tools for
Java are provided as a part of the system known as Java Development Kit (JDK). Moreover, the Application
Programming Interface (API) comprises the classes and interfaces used in Java programming. In this section, we
discuss the following:
Java Development Kit
Java Platforms
Java Virtual Machine
Java API
Java Programs
Java Development Kit
Keeping in mind the developers, Sun introduced JDK originally, which is now an Oracle product. JDK provides
a collection of the Java tools, which are used while developing and running Java programs. The kit comprises the
following development tools:
javaServes as a Java interpreter used to run Java applets and applications by reading and interpreting
bytecode files
javacServes as a Java compiler used to translate Java source code into bytecode files
javacdocCreates HyperText Markup Language (HTML) documentation for Java source code files
javapServes as a Java disassemble used to convert bytecode files into a Java program description
jdbServes as a Java debugger used to find errors in Java programs
appletviewerFacilitates to run Java applets
jarServes as an archive used to package related class libraries into a single executable JAR file and also
helps to manage the JAR files
javahServes as the C header and stub generator used to write native methods
Java Platforms
Oracle provides various Java editions to develop and run Java programs. The Java platform is not bound to any
one processor or operating system, but the execution engine (virtual machine) and a compiler can run identically
on any operating system. The following subsections are the different editions of the Java platform.
What is Java Standard Edition (Java SE)?
The Java SE Edition of Java is the most commonly used among the three Java editions. It is used for developing
desktop and console-based applications. It consists of:
A runtime environment
6
In Depth
Sets of APIs to build a wide variety of applications, comprising standalone applications that can run on
various operating systems, such as Microsoft Windows, Linux, and Solaris
What is Java Enterprise Edition (Java EE)?
Java EE is a platform primarily used for building server-side applications by using its convenient component-
based approach. It is a platform-independent, Java-centric environment from Oracle, which is meant for the
development and online deployment of Web-based Enterprise applications. The Java EE platform consists of a
set of serviceAPIs and protocols. These services provide the functionality for developing multi tiered, Web-
based applications.
Java EE is a Java-based, runtime platform created by Sun. It is now owned by Oracle after the acquisition of Sun
by Oracle on January 27, 2010. Java EE is used for developing, deploying, and managing multi tier server-centric
applications on an enterprise-wide scale. It builds on the features of Java SE and adds distributed
communication, threading control, scalable architecture, and transaction management. A strong competitor to
the Microsofts .NET Framework, Java EE is a Java platform designed for the mainframe-scale computing,
typical of large enterprises. For the simplification of application development in a thin client-tiered environment,
Sun designed Java EE in collaboration with partners such as IBM.
Some of the key features and services of Java EE are as follows:
At the client tier, it supports pure HTML as well as Java applets or applications. It relies on Java Server
Pages and Servlet code to create HTML or other formatted data for the client.
Enterprise JavaBeans (EJB) provides a layer for storing the platforms logic. The EJB server provides
functions such as threading, concurrency, security, and memory management. These services are
transparent to the author.
Java Database Connectivity (JDBC), which is the Java equivalent to Open Database Connectivity (ODBC), is
the standard interface for Java databases.
The Java Servlet API increases consistency for developers without the need of a Graphical User Interface (GUI).
What is Java Micro Edition (Java ME)?
It enables you to build Java applications for micro-devices, which include handheld devices, such as cell phones
and Personal Digital Assistants (PDAs), and other similar devices with limited display and memory support. It is
a competitor to Microsofts .NET Compact Framework.
The devices that you use nowadays, such as cell phones, PDAs, televisions, and set-top boxes, are often powered
by Java ME. This is because Java ME provides a robust and flexible environment to enable the applications
meant to run on devices that are low on resources, such as processor and memory. The Java Community Process,
which comprises the experts from the leading device manufacturers, defined the standard set of Java APIs that
are part of the Java ME environment along with the JVM. The same sets of APIs along with the JVM are also
included in the other Java platforms that include Java SE, Java EE, and Java Card environments.
The strength and advantages of the Java technology can be provided to the end user of the embedded consumer
devices by using Java ME in such devices. The inclusion of a flexible user interface, a robust security model, a
variety of built-in network protocols, and an extensive support for networked and offline applications that are
automatically downloadable makes Java ME a versatile platform for a wide range of consumer devices. The
applications written for the Java ME specifications are also inherently platform-independent and can therefore
be used on a variety of devices even though written for one.
The Java ME architecture includes various configurations, profiles, and optional packages for the developers to
choose from. The chosen packages and configurations can be combined to build a complete Java runtime
environment to go in rhyme with the target device and the target market. The selection is optimized for the
processing power, memory, and I/O capabilities of any related category of devices. This eventually results in a
common platform that benefits from each category of devices by providing an engaging user experience.
The Java ME configuration includes a JVM and a set of class libraries. The number of libraries is kept to a bare
minimum because it is meant to be executed on a device with a modest hardware configuration. They then
provide the basic functionality for a particular category of devices having common characteristics. There are two
7
Chapter 1: Essential Java
Java ME configurations: the Connected Limited Device Configuration (CLDC) and the Connected Device
Configuration (CDC).
Java Virtual Machine
In all programming languages, a compiler translates source code into machine code for a specific computer. In
Java, a compiler translates the Java source code into an intermediate code known as bytecode for a virtual
machine, known as JVM. Bytecode is the machine language for JVM and is not machine-specific. Instead, the
machine-specific code is generated by the Java interpreter, which serves as a mediator between virtual machine
and real machine. Figure 1.1 shows the process of compilation and conversion of bytecode into machine code:
Figure 1.1: Displaying the Process of Compilation and Execution in Java
In order to run a Java program on a different computer, you need a Java interpreter for Java bytecode. Although
Java bytecode interpreter is required depending upon the type of operating system in use, once a computer has
an interpreter, it can run a Java bytecode. In other words, the most important feature of Java is that the same
compiled program can run on any operating system, as shown in Figure 1.2:
Figure 1.2: Displaying the Process of Running a Program on Any Operating System
Java API
It is a collection of classes, interfaces, and methods provided in the form of Java packages. In other words, it is a
large collection of already created classes and interfaces, which provide many useful capabilities, such as
Graphical User Interface (GUI), date, time, and calendar capabilities. The categorization of Java API in the form
of Java packages is as follows:
Application Programming Packages
java.langProvides classes that are fundamental to the design of the Java programming language
java.utilProvides legacy collection classes, event model, collection framework, date and time
capabilities, internationalization, and other utility classes, such as string tokenizer
java.ioProvides classes for system input and output through data streams, serialization, and the file
system
Applet and Network Programming Packages
java.awtProvides classes for creating user interface and painting graphics and images
java.appletProvides classes that are necessary for creating an applet and those that are used to
communicate with its applet context
java.netProvides classes that are used for implementing networking in Java programs
8
In Depth
Java Programs
A Java programmer can create either a Java application or a Java applet depending upon the requirement. In
Java, you create the following types of program:
Applications
Applets
Well use the term program in this book to refer to both applets and applications. Now, lets discuss each of them
in detail.
Applications
A Java application is a program that is created by using Java programming language. Java applications are
console-based, Character User Interface (CUI)-based, and GUI-based standalone applications. Once you become
used to creating applications, you will find that creating an application by using Java is also as simple as creating
an application with any other programming language. In order to execute a Java application, you need to
perform the following steps:
Compile the Java source code by using javac compiler to translate the source code into bytecode
Execute the bytecode by using the Java interpreter
Apart from applications, you can also create applets in Java.
Applets
An applet is a program written in the Java programming language that can be included in an HTML page in the
same way as an image is included. An applet can be used in both static and dynamic web pages to either
display content or share information through the pages. You need to import the java.applet package that
provides classes to either create an applet or allow an applet to communicate with its applet context.
The applet context is an application that is responsible for loading and running applets. For example, the applet
context could be a web browser or an applet development environment. In other words, an applet is a Java
application designed to be transmitted over the Internet and is executed by a Java-compatible web browser.
After understanding the types of Java program, lets create a simple Java program. But to do this, you need to
create a source code file by using a text editor first. After creating the Java program, you need to compile it by
using the Java compiler javac and execute by using the Java interpreter java. The compiler generates a .class
file by translating the source code into bytecode, which is then executed by the Java interpreter.
What are Application Servers (Tomcat, JRun, WebSphere,
WebLogic, etc.)
An Application server is a server program running on a computer in a distributed network that provides the
business logic for an application program. Frequently viewed as part of a three-tier application, this server
consists of a GUI server, an application (business logic) server, and a database and transaction server. The server
encapsulates the Java program code that executes within an Evolution account. Application servers are provided
by third-party software vendors and are integrated into the myEvolution hosting control center.
In addition to the application logic, it contains the services that access the resource manager, such as a database.
Clients or other services that may or may not reside on the same physical machine call the services. There are a
number of Application servers used by various Java applications. Some examples are as follows:
TomcatThe Tomcat server is a Java-based Web application container that was created to run Servlets and
Java Server Pages in Web applications. Tomcat is the Servlet container that is used in the official Reference
Implementation for the Java Servlets and Java Server Pages technologies. The Java Servlets and Java Server
Pages specifications were developed by Sun under the Java Community Process. It is developed in an open
and participatory environment and released under the Apache Software License. The Tomcat is intended to
be a group of the best-of-the-best developers from around the world.
9
Chapter 1: Essential Java
JRunJRun is an Application server of Adobe that is based on Oracles Java Enterprise Edition. It consists
of Java Server Pages, Java Servlets, Enterprise Java Beans, Java Transaction Service (JTS), and Java
Messaging Service (JMS).
JRun works with the most popular web servers, including Apache, Microsofts Internet Information Server
(IIS), and any other web server that supports Internet Server Application Program Interface (ISAPI) or the
Webs Common Gateway Interface (CGI).
JRun comes in four editionsDeveloper edition, Professional edition, Advanced edition, and Enterprise
edition. The Developer edition consists of the full JRun package, but it is meant for development use only
and is limited to three concurrent connections. The Advanced edition is designed to deploy JSP and Servlet
applications in a clustered-server environment. Corporates that host Servlet and JSP-based Web
applications from a single server use the Professional edition. Companies that build and deploy e-commerce
Java applications use the Enterprise edition.
WebLogicThe WebLogic Platform delivers application infrastructure technology in a single, unified,
easy-to-use platform for application development, deployment, and management. The Oracle WebLogic
Platform increases productivity and lowers total cost of ownership for IT organizations as it provides a
unified, simplified, and extensible platform for application development, deployment, and management.
WebLogic is the first platform to address the need for asynchronous Web services, which is a critical aspect
of application-to-application communication.
WebLogic gives developers the tools necessary to integrate different applications and platforms for
providing full leverage to organization in terms of data and software investments. It also provides an
enterprise class framework that ensures reliable, scalable, available, and secure applications.
To integrate different applications and platforms, the developers require Deployers for deploying Web and
EJB applications in the server environment.
DeployersThe Deployers are responsible for deploying EJB applications and Web applications into the
server environment. They are not responsible for deploying an Application client archive or a resource
adapter archive but may be responsible for additional configuration of these components.
Packaged as a part of Java EE EAR files, these archives are not considered when the Enterprise applications
are deployed. These are a part of Java EE applications but do not follow the runtime activation process that
Web application and EJB containers go through during deployment.
The Application client archives operate within the content of a Java EE container and are not deployed into
an Application server. The Application client program runs standalone, and the Deployers are not
responsible for configuring the container environment for these programs.
The resource adapter archives are the simple libraries that are dropped into a valid JCA implementation.
The Deployers produce container-ready EJB applications, Web applications, applets, and Application clients
that have been customized for target environment of the Application server. Some of the commonly used
Deployers are Ant, Junit, Cactus, and Maven.
AntApache Ant is a Deployer, which is a Java-based tool. Ant is like Make but without Makes
wrinkles. Unlike Make, Ant uses Java classes instead of writing shell commands.
JUnitDeveloped by Erich Gamma and Kent Beck, JUnit is an open source softwarea testing
framework. The developer who implements unit tests in Java uses it. It is a simple framework to write
the repeatable tests. JUnit is an instance of xUnit architecture for unit testing framework.
Cactus and MavenThe Apache Cactus and Maven, used as Deployers, are Java-based applications
that automatically start containers, run tests, and stop the containers.
Cactus is a simple framework for testing server-side Java code. Its purpose is to lower the cost of
writing tests for server side codes.
Maven is based on the concept of Project Object Model (POM), which provides a well-defined project
structure, well-defined development process, and cohesive body of documentation that keep the
developer updated regarding the project progress.
10
In Depth
Program Design
Program design in Java is not necessarily an easy task. Good programming design involves a number of overall
aspects, and its worth taking a look at some of them in this chapter before we start digging into Java syntax in
depth.
In fact, one of the most important aspects of creating a new application is designing that application. Poor
choices can end up hampering your application through many revisions of the product. Many books are
available on program design.
Microsoft, which should know something about it, breaks the process into four areas:
PerformanceThe responsiveness and overall optimization of speed and resource use
MaintainabilityThe ability of the application to be easily maintained
ExtensibilityThe ability of the application to be extended in well-defined ways
AvailabilityHow robust the implementation of the application is and how available it is for use
Lets take a quick look at these four areas now.
Performance
Performance is a design issue thats hard to argue with. If the users arent getting what they want from your
application, thats clearly a problem. In general, performance depends on the users needs. For some people,
speed is essential; for others, robustness or efficient use of resources is what they are looking for. Overall, the
performance of an application is an indication of how well it responds to the users needs. Here are some general
aspects of performance that you should consider while writing Java programs:
Algorithm efficiency
CPU speed
Efficient database design and normalization
Limiting external accesses
Network speed
Security issues
Speed issues
Use of resources
Web access speed
Well get to more specifics of performance throughout the book.
Maintainability
Maintainability is the measure of how easily you can adapt your application to future needs. This issue comes
down to using good programming practices, which well talk about throughout the book. Much of this is
common sensesimply keeping future coding needs in mind as you write your code. Some major issues in the
best programming arsenal include the following:
Avoid deep nesting of loops and conditionals
Avoid passing global variables to procedures
Be modular when you write code
Break code into packages
Document program changes
Give each procedure only one purpose
Make sure that your application can scale well for large tasks and large number of users
Plan for code reuse
Program defensively
11
Chapter 1: Essential Java
Use access procedures for sensitive data
Use comments
Use consistent variable names
Use constants instead of magic numbers
Extensibility
Extensibility is the ability of your application to be extended in a well-defined and relatively easy way. It is
usually a concern only with larger applications, and it often involves an entire interface specially designed for
extension modules. In fact, Java itself is designed to be extended by using the Java Extension Framework.
Availability
Availability is the measure of how much time your application can be used for in comparison to the time users
want to use it for. This includes everything, from the application not freezing up when performing a long task (at
the least, giving the user some feedback of the operations status) to working with techniques and methods not
likely to hang, to making backups of crucial data, and to planning for alternate resource useif possiblewhen
access to a desired resource is blocked.
Overall, the design process is one that involves quite a bit of time. In fact, the whole development cycle is the
subject of quite a few studiesyou may be surprised to learn that when field testing, in-house testing, planning,
designing, and user interface testing are added up, some studies allocate as little as 15 percent of total project
time to the actual coding.
So much has been written about the development cycle of software that we wont go into more details here. But,
its worth noting that programmers shouldnt short-change the crucial design steps because it can lead to more
problems in the long run than time saved in the short run.
New Features of Java SE 8
Java SE 8 is a major release that brought many new features and enhancements in Java programming language.
Lets have a brief introduction of some noteworthy features of Java SE 8.
Java programming language Following are new changes in Java programming language:
Lambda expressions are introduced as a new language feature. They allow you to pass functions as a
method argument or treat code as data.
Following is the syntax of lambda expression:
view sourceprint?1 (argtype arg...) -> { return some expression.. probably using these
arguments }
Method references help in reading lambda expressions for methods that already have a name.
Default methods enable new functionality to be added to the interfaces of libraries and ensure binary
compatibility with code written in older versions of those interfaces.
Repeated use of annotations enables you to apply the same annotation type more than once to the same
type of declaration.
A new method, String.join(), is added to join the strings. For example:
String abc= String.join("String1 ", "Java", "8");
The preceding code will be evaluated as:
String1 Java 8
Java compilerThere is a new feature of using the -parameters option with javac command to store
formal parameter names and enable the Reflection API to retrieve them. Lets create the following class:
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
public class ParameterNames {
public static void main(String[] args) throws Exception {
Method m = ParameterNames.class.getMethod( "main", String[].class );
12
In Depth
for( final Parameter parameter: m.getParameters() ) {
System.out.println( "Parameter: " + parameter.getName() );
}
If you compile the previous class without using parameters argument and then run this program, you will
see the output as:
Parameter: arg0
However, if you compile the previous class with the parameters argument and then run this program, you
will see the output with the actual name of parameter that you have passed.
Parameter: args
Java libraries Following changes have taken place in Java libraries features:
Streams A new package, java.util.stream, provides a Stream API to support functional-style
operations on streams of elements. Stream API can be integrated with Collections API to perform bulk
operations on collections, such as sequential or parallel map-reduce transformations.
Date/Time API (JSR 310) Java 8 provides a new Date-Time API (JSR 310), which provides a new
package, called java.time. This package contains all the classes for date, time, date/time, time zones,
instants, duration, and clocks manipulation. Some examples of classes contained in this package are
Clock, LocaleDate, LocalTime, and Duration. The Clock class provides the access to the current instant,
date and time using a time zone. It can be used in place of using the System.currentTimeMillis()
and TimeZone.getDefault() methods. The LocaleDate class holds only the date part and the
LocaleTime class holds only the time part without a time-zone in the ISO-8601 calendar system. The
Duration class, finally, provides an amount of time in terms of seconds and nanoseconds.
Nashorn JavaScript engine Java 8 provides a new Nashorn JavaScript engine that allows you to
develop and execute certain kinds of JavaScript application on JVM. The engine works like
javax.script.ScriptEngine and permits Java and JavaScript interoperability.
Parallel Arrays Java 8 provides various new methods allowing parallel arrays processing. For
example, the parallelSort() method significantly speeds up the sorting on multicore machines.
Concurrency Java 8 adds new methods to the java.util.concurrent.ConcurrentHashMap
class that support aggregate operations on the basis of the newly added streams facility and lambda
expressions. A new class, java.util.concurrent.locks.StampedLock, has been added to
provide a capability-based lock with three modes for controlling read/write access. In addition, some
classes are added to the java.util.concurrent.atomic package, which includes
DoubleAccumulator, DoubleAdder, LongAccumulator, and LongAdder.
Java tools Java 8 provides a new set of command line tools, which include Nashorn engine (jjs command)
and class dependency analyzer (jdeps command). The role of these tools is described as follows:
Nashorn engine The jjs command accepts a list of JavaScript source code files as arguments and runs
them. For example, if a file, myfunc.js, is created with the following content:
function demofunc() {
return 1;
};
print( demofunc() + 1 );
Now, the jjs command is used to execute the myfunc.js file:
jjs myfunc.js
The output of the preceding code will be:
2
13
Chapter 1: Essential Java
Class dependency analyzer The jdeps command is used to show the package-level or class-level
dependencies of Java class files. It accepts .class file, a directory, or JAR file as an input, and displays
the dependencies to the console.
Java runtime (JVM) The PermGen space has been replaced with Metaspace (JEP 122). The JVM
options,XX:PermSize and -XX:MaxPermSize, are replaced with -XX:MetaSpaceSize and
XX:MaxMetaspaceSize, respectively.
JDBC The JDBC-ODBC Bridge has been removed. In addition, JDBC 4.2 has been introduced with
various new features. Some of these are as follows:
Addition of REF_CURSOR support
Addition of java.sql.DriverAction interface
Addition of security check on deregisterDriver method in the DriverManager class
Addition of the java.sql.SQLType interface
Addition of the java.sql.JDBCType enum
You would learn about these features of Java SE 8 in detail with their implementation in other chapters of the book.
14
Immediate Solutions
Immediate Solutions
Getting and Installing Java
The Big Boss (BB) gives you a callas usual at the last minute. You have 20 minutes to write a new Web page
that gives users an overview of your companys products. What are you going to do? Knowing how well Java
works in cases like this, you select Java as your language of choice to get the task done. Of course, youve got to
make sure you have it before you can use it.
Its time to download and install Java, which means downloading the Java Software Development Kit (SDK).
Currently, you can find it at http://www.oracle.com/technetwork/java/javase/downloads/jdk8-
downloads-2133151.html. The kit gets downloaded in the form of an executable application file. Next, you
can follow the instructions on the Oracles website in order to install JDK 1.8. Wed love to be able to provide the
actual installation instructions here, but thats one of the biggest pitfalls a Java book can fall into, even the one
thats designed to be as complete as possible. We have been writing about Java ever since it first came out, and it
turns out that the actual installation instructions are often very volatile. As these instructions are changed quite
frequently, the ones we have provided in the previous books instantly became obsolete. For that reason, the
absolutely best thing you can do is to see how Sun wants you to install the SDK; therefore, you should refer to
the installation instructions as posted on the Java site. The installation process has been getting easier with every
version and beta of Java, and now, it typically involves only running the file youve downloaded.
One thing you should be sure to do, as indicated in the Sun installation instructions, is to ensure your machine
can find the Java tools, including the Java compiler itself. To do that, verify that the Java bin directory is in your
computers path. For example, in Windows, usually the bin directory path is C:\Program
Files\Java\jdk1.8\bin for SDK 1.8.
The Java Software Development Kit was called the Java Development Kit, JDK, in earlier Java versions. In fact, Oracle often
seems to be of two minds heresometimes, youll see references to the SDK and sometimes, youll see references to JDK.
This is one of those timesalthough the kit is now called the SDK, its installed by default into a directory named \jdk1.8.
In Windows 7, you can follow these steps to configure Java 8 on your system:
Click the Windows icon on the taskbar, right click the Computer, and select the Properties option. You can
also reach the same location by opening the Control Panel| System and Security| System.
Click the Advanced system settings option in the System Properties window. This opens the System
Properties dialog box.
Click the Environment Variables button to open the Environment Variables dialog box.
Edit the PATH variable, setting the way you want. You may append the new path to the already existing
PATH variable or create a new PATH variable. Finally, click OK. Note that if you are appending the PATH
variable, the different paths must be separated by semicolons (;).
You can also set the PATH variable temporarily with the help of the command line. The path shall remain set
only till the command line is open; once you exit from the command line, the PATH variable set also gets erased.
The following command is used to temporarily set the PATH variable:
SET PATH= C:\Program Files\Java\jdk1.8\bin;
When the bin directory is in the path, youll be able to use the Java tools directly from the command line, instead
of having to preface them with a pathname each time you want to use them on the command line.
What about CLASSPATH?
Java veterans will wonder about the environment variable named CLASSPATH when they install Java SDK. The
CLASSPATH variable, as youll soon see in this chapter, tells Java where to find compiled bytecode filesboth the
ones you create and the ones required by the system that come with the SDK itself. CLASSPATH has been the focus
of a great deal of confusion when working with Java, and we are glad to say that Sun has made things easier.
15
Chapter 1: Essential Java
When you install the SDK, you dont have to worry about setting the CLASSPATH now because the SDK will
know where to find its own installed libraries. However, if you want to search other custom bytecode files when
compiling a file, youll have to set the CLASSPATH yourself. Youll see how to do this when we will discuss
compiling programs in this chapter. (There are two ways to indicate to the Java compiler where to find bytecode
files you particularly want to searchby setting the CLASSPATH environment variable and by using the -
CLASSPATH compiler switch.)
The current version of the SDK does not require CLASSPATH to be defined; and if it has been defined by some
other Java version or system, it is likely to create problems. If you want to keep the CLASSPATH environment
variable for any reason, you need to use the command line option to define the CLASSPATH temporarily.
Subfolders Created by JDK
After installing JDK, several folders get created on your hard drive. The location of these folders formed depends
on the particular system; however, in general, the JDK folder is formed under Program Files\Java on your boot
drive. The name of the JDK root folder also includes the version you have installed. The different subfolders
created under the JDK root folder and additional files are described in Tables 1.1 and 1.2, respectively:
Table 1.1: The different subfolders created in the JDK root folder
Folder Description
bin The compiler and other Java development tools
demo Demo programs from which you can learn various Java features
include Files required to integrate Java with other languages
jre Runtime Environment files
lib Library files, including the Java API class library
sample Samples, with source code, of programming for certain Java API's
db Oracles distribution of the Apache Derby relational database
Table 1.2: Additional files in the JDK root folder
File Description
README.html The Java readme file in the HTML format
THIRDPARTYLICENSEREADME.txt A license file for third parties, regarding usage and redistribution of JDK
LICENSE The Java license that you agreed to when you downloaded JDK
COPYRIGHT The copyright notice about all the copyright and export laws applied by
Sun
register.html For free register of the JDK installed with Oracle
release It contains details such as Java version, OS name, and OS version
register_ja.html and These HTML files are, respectively, the Japanese and Chinese versions of
register_zh_CN register.html
Src A .zip file that contains the code for Java API classes
Creating Source Files
The Design Team Coordinator (DTC) calls to congratulate you on getting Java installed. You accept the accolades
gracefully. So, what programs have you been writing? the DTC asks. Hmm! you think. Programs?
Java programs are just plain text files made up of Java statements and declarations, and well start investigating
them in the next solution. To create a Java program, you should have a text editor or word processor that can
save files in plain text format.
Saving text in plain text format is a simple achievement thats beyond many fancy word processors. You might
have trouble with word processors, such as Microsoft Word, although you can save plain text files with Word
16
Immediate Solutions
using the File | Save As dialog box. The general rule is that if you can type the file out at the command line (note
that thats DOS on DOS- and Windows-based computers) and dont see any odd, non-alphanumeric characters,
its a plain text file. The real test, of course, is whether the Java compiler, which translates your program into a
bytecode file, can read and interpret your program.
In addition, your programs should be stored in files that have the extension .java. For example, if you are
writing an application named App, you should store the actual Java program in a file named App.java. You
pass this file to the Java compiler to create the actual bytecode file, as youll see in the next few pages.
So far, so goodwe have done the selection of the editor or word processor down. Now, how about writing
some code?
Knowing Javas Reserved Words
A Novice Programmer (NP) appears and says, Java is acting all funnyI want to name a variable public,
but its giving me all kinds of problem. Thats because public is one of the keywords that Java reserves for
itself as part of the Java language, you say. Rats, says the NP.
When you are writing a Java code, you should know that Java reserves certain words for itself as a part of the
Java language. Some of the reserve words are as follows (well cover these keywords throughout the book):
abstractIt specifies that a class or method will be implemented later in a subclass
assertIt signifies an assertion statement
booleanIt is a data type that can hold True and False values only
breakIt is a control statement for breaking out of loops
byteIt is a data type that can hold 8-bit data values
byvalueIt is reserved for future use
caseIt is used in the switch statements to mark blocks of text
cast It is reserved for future use
catchIt catches exceptions generated by the try statements
charIt is a data type that can hold unsigned 16-bit Unicode characters
classIt declares a new class
constIt is reserved for future use
continueIt sends control back outside a loop
defaultIt specifies the default block of code in a switch statement
doIt starts a do-while loop
doubleIt is a data type that can hold 64-bit floating-point numbers
elseIt indicates alternative branches in an if statement
enum It declares enumerated type variables
extendsIt indicates that a class is derived from another class or an interface is derived from another
interface
false It indicates one of the two permissible values for a boolean variable
finalIt indicates that a variable holds a constant value or that a method will not be overridden
finallyIt indicates a block of code in a try-catch structure that will always be executed
floatIt is a data type that holds a 32-bit floating-point number
forIt is used to start a for loop
futureIt is reserved for future use
genericIt is reserved for future use
gotoIt is reserved for future use
17
Chapter 1: Essential Java
ifIt tests a true/false expression and branches accordingly
implementsIt specifies that a class implements an interface
importIt references other classes
innerIt is reserved for future use
instanceofIt indicates whether an object is an instance of a specific class or implements a specific
interface
intIt is a data type that can hold a 32-bit signed integer
interfaceIt declares an interface
longIt is a data type that holds a 64-bit integer
nativeIt specifies that a method is implemented with native (platform-specific) code
newIt creates new objects
nullIt indicates that a reference does not refer to anything
operatorIt is reserved for future use
outerIt is reserved for future use
packageIt declares a Java package
privateIt is an access specifier indicating that a method or variable may be accessed only in the class its
declared in
protectedIt is an access specifier indicating that a method or variable may only be accessed in the class
it has declared (or a subclass of the class it has declared in or other classes in the same package)
publicIt is an access specifier used for classes, interfaces, methods, and variables indicating that an item
is accessible throughout the application (or where the class that defines it is accessible)
rest It is reserved for future use
returnIt sends control and possibly a return value back from a called method
shortIt is a data type that can hold a 16-bit integer
staticIt indicates that a variable or method is a class method (rather than being limited to one particular
object)
strictfpIt restricts the precision and rounding of floating-point numbers
superIt refers to a classs base class (used in a method or class constructor)
switchIt is a statement that executes code on the basis of a test value
synchronizedIt specifies critical sections or methods in a multithreaded code
thisIt refers to the current object in a method or constructor
throwIt creates an exception
throwsIt indicates what exceptions may be thrown by a method
transientIt specifies that a variable is not a part of an objects persistent state
tryIt starts a block of code that will be tested for exceptions
true It indicates one of the two permissible values for a boolean variable
varIt is reserved for future use
voidIt specifies that a method does not have a return value
volatileIt indicates that a variable may change asynchronously
whileIt starts a while loop
18
Immediate Solutions
Creating an Application
The Big Boss arrives and says, So now you can write Java! Give me a demonstration! You turn to your terminal
and immediately your mind goes blank. What will you write?
Heres a sample Java application that well develop over the next few sections, all the way through the compiling
and running stages. Place this code in a file named App.java:
public class App {
public static void main(String[] args) {
System.out.println("Hello from Java!"); }
}
If you are new to Java, this might look strange to you. The idea here is that this application will print the text
Hello from Java! when you compile and run it. For example, heres how it looks in a DOS window under
Windows:
c:\>java App
Hello from Java!
Not the most significant of programs but a good one to get us started. Lets take this program apart line by line.
Line 1public class App
Heres the first line in App.java:
public class App { . . . }
This line indicates that we are creating a new Java class named App. After we translate this class into bytecodes,
the JVM will be able to create objects of this class and run them. Youll learn all about classes in depth in Chapter
4; this code is just to get us started with Java programming.
Note the keyword public in the preceding code. This keyword is an access specifier, which youll learn more
about in Chapters 4 and 5. The public access specifier indicates that this class is available anywhere in a
program that makes use of it.
Also note that if you make a class public, Java insists that you name the file after it. That is, you can only have
one public class in a .java file. The reason for this is that the Java compiler will translate the .java file into a
bytecode file with the extension .class, which means that App.java will be translated into App.class;
and if the JVM needs the App class, itll know to look in the App.class file. Because JVM uses the name of the
file to determine what public classes are in the file, you can only have one public class in a file. For that reason,
the code for the App class must be in a file named App.java (note that Java is pretty particular about this, and
capitalization counts here, even in Windows that normally doesnt pay any attention to capitalization). The
actual implementation of the class we are defining here will go between the curly braces:
public class App { . . . }
Java always encloses blocks of code within curly braces, that is, { and }.Youll see in Chapter 4 that the code
inside the block has its own scope (its visibility to the rest of the program). Right now, lets continue building our
application by continuing with the next line of the code.
Line 2public static void main(String[] args)
Heres the next line of code in our application:
public class App { public static void main(String[] args) { . . . } }
Whats happening here is that we are creating a method in the App class. A method in OOP is like a function or
subroutine in standard programmingits a block of code that you can pass control to and that can return a
value. Methods provide handy ways of wrapping code into a single functional unit; when you call a method,
JVM executes the code in the method.
Youll be introduced to methods formally in Chapter 4, but here, the idea is that we are creating a method named
main, which is the method that the JVM will look for when it starts an application (applets do not have a main
method). When it finds the main method, the JVM passes control to it, and well place the code we want to
execute in this methods code block.
There are a few things to note before continuing. The main method must be declared with the public access
specifier, which means it may be called outside its class. It must be declared static as well, which means that
19
Chapter 1: Essential Java
main is a class method, not an object method (youll see in Chapter 4). It must not return a value when its
finished executing, which is why we use the keyword void in this code (in other words, a return value of type
void means that there actually is no return value). Finally, note the argument in the parentheses following the
word main: String[] args. You place an argument list in the parentheses of a method declaration like this
to indicate what values are passed to the method and can be used by the code in the method. In this case, we are
indicating that main has passed an array of string values called args. These string values hold the values
passed from the command line when you start the application; for example, if you type java app Hello
there, Hello and there would be the two strings in the args array. The full details appear in Chapter 4.
Because we wont use any command-line arguments in this application, we wont use args in the code for the
main method.
This line of code then starts the main method. The whole job of this method is to print out the text Hello from
Java! which is done in the next line of code.
Line 3System.out.println(Hello from Java!);
The main method has one line of code in it:
System.out.println("Hello from Java!"); }
}
This is the actual line of code that does the work of printing the statement. In this case, we are using some of the
code that the programmers at Sun have already created to display the text Hello from Java! In particular, the
java.lang packages System class is used here. Libraries of classes are called packages in Java, and the
java.lang package is built into every Java program, which means you dont have to take special steps to make
use of it, as you do with other Java packages. The java.lang packages System class includes a field (that is, a
data member of the class) called out, and this field in turn has a method named println, which does the actual
displaying of text.
To refer to the System classs out field, we use the terminology System.out. To use the out fields println
method (which stands for print line), we use the terminology System.out.println. To print the text Hello
from Java! we pass that text to System.out.println by enclosing it in quotes.
Also note that this line of code ends with a semicolon. This end-of-statement convention is something that Java
has inherited from C and C++ (in fact, Java has inherited a lot from C and C++), and you end nearly all
statements in Java with a semicolon. If this isnt something you are used to, youll pick it up pretty quickly
because the Java compiler refuses to translate your code into bytecodes until the semicolons are in place.
Thats it, thenyouve created your new application and stored it in a file named App.java. Whats the next
step? To get it actually run, take a look at the next solution.
Compiling Code
The Big Boss is chomping a cigar while standing right behind you as you enter your new Java application into a
file. Hmm, says the Big Boss, clearly not impressed. Whats next? Now, you say, we have to compile the
program and then we can run it. OK, the Big Boss says. Amaze me.
To translate a Java program into a bytecode file that the JVM can use, you use the Java compiler javac (for
example, on Windows machines, this program will be called javac.exe, which is in the Java bin directory).
Heres how you use javac in general:
javac [options] [sourcefiles] [@files]
The arguments to javac are:
optionsCommand-line options
sourcefilesOne or more source files to be compiled (such as App.java)
@filesOne or more files that list source files
To compile App.java, use the following command:
C:\>javac App.java
Note that to make sure javac can find App.java, you should first make sure the current directory is the one
that has App.java in it. For example, in Windows, if youve stored App.java in C:\Nancy, to compile
20
Immediate Solutions
App.java, first make sure C:\Nancy is the current directory (you can use the change directory command, cd,
like this: cd C:\Nancy). Then, run javac like this: C:\Nancy>javac App.java. Alternatively, you can
specify the path of App.java like this: C:\>javac C:\Nancy\App.java.
In addition, note that in this book, well use the generic prompt C:\> for the command line, but this
actually stands for the current working directory, whatever that may be in your casefor
example, C:\Bertie\Development>, C:\Programs>, Unix prompts, such as %,
/home/Nancy/programs:, and so on. That is to say C:\> is just going to be a placeholder for the actual
prompt on your machine for the current directory you are in.
The Java compiler javac takes the file App.java(assuming there are no errors), compiles it, translates it, and
then creates a new file called App.class. If errors occur, the Java compiler will tell you what they are, including
what line of code is wrongin this case, we have forgotten the println method and tried to use the one called
printline:
C:\>javac App.java
App.java:3: error: cannot find symbol
System.out.printline(Hello from Java!); }
^
symbol: method printline(String)
location: variable out of type PrintStream
1 error
When App.java is successfully compiled to bytecode, the new file, App.class, contains all that JVM will need
to create objects from the App class. So, we have created App.class. Now, how do you actually run it in JVM?
See the next solution.
Compiling Code: Using Command-Line Options
Hmm, says the NP, I have got a problem. I like to keep all my .class files in the same directory, but
sometimes, I forget to copy the new versions of those files to that directory. You say, Theres a compiler option
thats perfect for you. Its called the -d option. Using that option, you can have the compiler place bytecode files
into any target directory you want. Well, says the NP. Now, if I can only remember to use that option
There are quite a number of optionsthat is, command-line directivesyou can use with javac. For example,
heres how you can use the -d option to have javac place the file App.class in an existing directory called
temp, which, in this case, is a sub-directory of the current directory:
javac -d temp App.java
The following is the list of javac options; note that the options that start with -X (called non-standard options) are
marked that way by Sun because they may change in the future:
-classpath classpathIt sets the user class path, overriding the user class path in the CLASSPATH
environment variable. If neither CLASSPATH nor -classpath is specified, the user class path will be the
current directory. Note that if the -sourcepath option is not used, the user class path is searched for
source files as well as class files.
-d directoryIt sets the destination directory for .class files. For readers who know what
Java packages are, if a class is a part of a package, javac puts the .class file in a sub-directory
that reflects the package name, creating directories as needed. For example, if you specify -d c:\classes
and the class is called com.package1.Class1, the class file is called
c:\classes\com\package1\Class1.class. If -d is not specified, javac puts the class file in the same
directory as the source file. Note that the directory specified by -d is not automatically added to your user
class path.
-deprecationIt shows a description of each use or override of a deprecated member or class. (Without -
deprecation, javac only shows the names of source files that use or override deprecated members or
classes.)
-encodingIt sets the source file encoding name. If -encoding is not specified, the platform default
converter is used.
21
Chapter 1: Essential Java
-gIt generates all debugging information, including local variables. By default, only line number and
source file information are generated.
-g:noneIt makes the compiler unable to generate any debugging information.
-g:{keyword list} It generates only some kinds of debugging information, specified by a comma-
separated list of keywords. The valid keywords are source (source file debugging information), lines
(line number debugging information), and vars (local variable debugging information).
-nowarn It disables all warning messages.
-OIt optimizes code for performance in terms of the quickest execution time. Note that using the -O
option may slow down compilation, produce larger class files, and make the program difficult to debug.
Note that before version 1.2, the -g and -O options of javac could not be used together.
As of version 1.2, you could combine the -g and O options, but you might get odd results, such as missing
variables and relocated or missing code. The -O option no longer automatically turns on -depend or turns
off g.
-sourcepathIt specifies the source code path to search for class or interface definitions. As with the user
class path, source path entries are separated by semicolons (;) and can be directories, .jar (Java Archive)
files or zip files. If you use packages, the local pathname within the directory or archive must reflect the
package name, as youll see later. Note that classes found through the class path are subject to automatic
recompilation if their source code files are found.
-verboseIt creates verbose output. This includes information about each class loaded and each source
file compiled.
-XIt displays information about non-standard options and quits.
-XdependIt searches all reachable classes for more recent source files to recompile. This option will more
reliably discover classes that need to be recompiled, but it can slow down the compilation process
dramatically.
-XstdoutIt sends compiler messages to System.out. By default, the compiler messages go to
System.err, which youll learn more about later.
-XverbosepathIt describes how paths and standard extensions were searched to find source and
class files.
-JoptionYou use this option to pass an option to the Java launcher called by javac. For example, -J-
Xms64m sets the start-up memory to 64 MB. Although this option does not begin with -X, its not a standard
option of javac. Its a common convention for -J to pass options to the underlying JVM executing
applications written in Java.
Cross-Compilation Options
Cross-compilation options are considered an advanced topic; javac supports cross-compiling, where classes are
compiled with the bootstrap (default) and extension classes of a different Java platform implementation. You
must use -bootclasspath and -extdirs when cross-compiling. Here are the cross-compilation options:
-target versionIt generates class files that will work on JVMs with the specified version.
-bootclasspath bootclasspathIt cross-compiles against the specified set of boot classes. As with the
user class path, boot class path entries are separated by semicolons (;) and can be directories, .jar files or
.zip files.
-extdirs directoriesIt cross-compiles against the specified extension directories; directories is
a semicolon-separated list of directories. Each .jar file in the specified directories is automatically searched
for class files.
22
Immediate Solutions
Compiling Code: Checking for Deprecated Methods
Good Lord! says the NP, How can I keep all the deprecated methods in Java straight? Now that Im
upgrading to Java SE 8, I dont know whats obsolete and whats not! Thats an easy one, you say. The Java
compiler javac will now tell you if you are using a method thats been deprecated, which it does not use unless
you specifically asked it to. Even better, you can use the -deprecation option to make sure you get all the
details
The -deprecation option is a good one, and its the standard option we use to make sure we avoid deprecated
methods. Suppose you have a program that uses addItem (a deprecated method) of the List class, and
when you try to compile it, javac gives you the following result:
C:\>javac App.java
Note: App.java uses or overrides a deprecated API.
Note: Recompile with Xlint:deprecation for details.
Thats not much help. However, using the -deprecation option, you can pinpoint the exact problem:
C:\>javac -deprecation App.java
App.java:7: warning: [deprecation] addItem(String) in List has been deprecated
list.addItem(Kogent);
^
1 warning
You can also use Xlint compiler option to pinpoint the warning point in the program.
Running Code
The Big Boss is getting impatient. Youve written a new application and compiled it without errors for the first
time (which you can feel proud of), but nothing has really happened that the BB can see. Its time to run the new
application.
You run Java applications with the program named Java (in Windows, for example, this is the java.exe file in
the Java bin file). The Java program, called the java tool, is what actually runs JVM. Heres how you can use
the java tool:
java [options] class [argument ...]
java [options] -jar file.jar [argument ...]
The parameters used in the preceding lines are explained as follows:
optionsCommand-line options, which well cover in a topic coming right up.
classThe name of the class to be invoked.
file.jarThe name of the Java Archive (JAR) file to be invoked. This is used only with -jar. JAR files
are covered in Chapter 27.
argumentA command-line argument passed to the main method.
For example, to run the application named app, which is in the file App.class, you could execute the following
command at the command line (note that you omit the .class part of App.class here):
C:\>java App
The result appears immediately:
C:\>java App
Hello from Java!
To make sure the java tool can find App.class in this example, you should first make sure the current directory is the one that
has App.class in it. For example, in Windows, if youve stored App.class in C:\Nancy, to run it, first make sure C:\Nancy is the
current directory (you can use the change directory command, cd, like this: cd C:\Nancy). Then, run Java like this:
C:\Nancy>java App. Alternatively, you can specify the path of App.class like this: C:\>java classpath C:\Nancy App.
23
Chapter 1: Essential Java
You can see how this works in a DOS window under Windows in Figure 1.3:
Figure 1.3: Running an Application in a DOS Window
Thats all it takesnow youve written, compiled, and run your first application. Congratulations!
Note that if your application isnt responding or if you want to stop it for some reason, you can type Ctrl+C. If
that doesnt work, try the Esc key.
Youll also see how to create windowed applications in this book, and when you run one of these applications
with the java tool, you get the results as shown in Figure 1.4 below.
Theres one thing to note about Figure 1.4the console window (a DOS window here) hangs around in the
background and waits for the application to finish before continuing (that is, before the DOS prompt reappears
in this case). If you dont want a console window associated with your windowed application, you can use the
javaw tool like this:
C:\>javaw App
Heres how you use javaw in generaljust like the java tool:
javaw [options] class [argument ...]
javaw [options] -jar file.jar [argument ...]
The parameters used by javaw are as follows:
optionsCommand-line options, which well cover later in the chapter.
classThe name of the class to be invoked.
file.jarThe name of the Java Archive (JAR) files to be invoked. This is used only with -jar. JAR files
are covered in Chapter 27.
argumentA command-line argument passed to the main method.
Figure 1.4: Running a Windowed Application
24
Immediate Solutions
When you launch a Java windowed application like this, the console window does not wait for the application to
finish; if you are running in DOS, the windowed application appears and the DOS prompt reappears in the DOS
window. This gives a more professional feel to those applications that you release for general use.
While we are discussing compiling and running code, theres another detail we should coverthe command-
line options you can use with the javac and java commands. Well take a look at them in the next two topics.
Running Code: Using Command-Line Options
Well, says the NP, I have another problem. I have stored all my .class files in one directory, but I dont
want to keep switching to that directory to run them. Another easy problem to solve, you say. You can use
the java tools -classpath option or set the CLASSPATH environment variable so that the Java compiler will
search for your classes correctly
For more on CLASSPATH, an important topic in Java programming, see the upcoming solution Finding Java Classes with
CLASSPATH.
Well take a look at using the command-line options in this solution; you use these options with the java and
javaw tools as follows (for a discussion of these tools, see the solution Running Code, earlier in this chapter):
java [options] class [argument ...]
java [options] -jar file.jar [argument ...]
javaw [options] class [argument ...]
javaw [options] -jar file.jar [argument ...]
The command-line options you can use with these tools are as follows (note that non-standard options, which
means they might not be supported in the future, begin with an X):
-classpath classpath or -cp classpathIt specifies a list of directories, .jar files or .zip files to
search for class files. You separate class path entries with semicolons (;). Note that specifying -classpath
or -cp overrides any setting of the CLASSPATH environment variable. Used with java or javaw, -
classpath or -cp only specifies the class path for user classes. If -classpath and -cp are not used and
CLASSPATH is not set, the user class path is limited to the current directory, which is referred to with a dot
(.). See the topic Finding Java Classes with CLASSPATH later in this chapter for more information.
-Dproperty=valueIt sets a system property value.
-jarIt executes a program encapsulated in a JAR file. The first argument is the name of a JAR file instead
of a start-up class name. When you use this option, the JAR file is the source of all user classes, and the other
user class path settings are ignored.
-verbose or -verbose:classIt displays information about each class loaded.
-verbose:gcIt reports on each garbage collection event. Garbage collection involves automatic memory
management in Java.
-verbose:jniIt reports information about the use of native (that is, platform-specific) methods and other
Java Native Interface activity.
-versionIt displays version information and exits.
-? or -helpIt displays usage information and exits.
-XIt displays information about non-standard options and exits.
-Xbootclasspath:bootclasspathIt specifies a semicolon-separated list of directories, .jar files or
.zip files to search for boot class files. Note that these will be used in place of the boot class files included
with Java itself.
-XdebugIt starts with the debugger enabled.
-XnoclassgcIt disables class garbage collection.
25
Chapter 1: Essential Java
-XmsnIt indicates the initial size of the memory pool you want to use (this value must be greater than
1000). To multiply the value by 1000, append the letter k. To multiply the value by 1 million, append the
letter m. The default value is 1m.
-XmxnIt specifies the maximum size of the memory pool (this value must be greater than 1000). To
multiply the value by 1000, append the letter k. To multiply the value by 1 million, append the letter m. The
default value is 64m.
-Xrunhprof[:help][:<suboption>=<value>,...]It enables CPU, heap, or monitor profiling. This
option is usually followed by a list of comma-separated pairs of the form <suboption>=<value>.
-XrsIt reduces the use of operating system signals.
-Xcheck:jniIt performs additional checks for Java Native Interface (JNI) functions.
-XfutureIt performs strict class-file format checks.
Commenting Your Code
The Programming Correctness Czar (PCC) comes in and looks at you reprovingly. Whats wrong, PCC? you
ask. Its your code, the PCC says. I cant make heads or tails of whats going on in it. I guess I forgot to
comment it, you say. I guess you did, the PCC says. Fix it.
Sometimes, a code can be very cryptic and hard to decipher. For that reason, Java lets you place descriptive
comments in your code to let you explain to anyone who reads that code how the program works and what it
does. As an example, lets add comments to the application we have already developed in the previous topics:
public class App { public static void main(String[] args) {
System.out.println("Hello from Java!"); }
}
Java supports three types of comment, two of which are taken from C++. You can surround a comment of any
length with the characters /* and */ as follows:
/* This application prints out "Hello from Java!" */
public class App { public static void main(String[] args) {
System.out.println("Hello from Java!"); }
}
The Java compiler will ignore all the text between the /* and */ markers. You can split comments between these
markers across multiple lines as follows:
/* This application prints out "Hello from Java!"
Created by: G. Whiz, 1/1/00 */
public class App {
public static void main(String[] args) {
System.out.println("Hello from Java!"); }
}
In fact, in many corporate environments, you are expected to use a standard comment header, created with the
/* and */ forms of comment, for all new code. It might look something as follows:
/*****************************************************
* This application prints out "Hello from Java!" *
* *
* Author: G. Whiz *
* Imports: None *
* Parameters: Command-line arguments *
* Returns: None *
* Assumptions: None *
* Creation date: 1/1/00 *
* Last Update: 1/1/01 *
******************************************************/
public class App {
public static void main(String[] args) {
System.out.println("Hello from Java!"); }
}
26
Immediate Solutions
Java also supports a one-line comment using a double slash (//). The Java compiler will ignore everything on a
line after the // marker, so you can create whole lines that are comments or just add a comment to an individual
line as follows:
/* This application prints out "Hello from Java!" */
public class App { //Create the App class
//Create main(), the entry point for the application.
public static void main(String[] args) {
//Print out the message with
System.out.println("Hello from Java!"); }
}
Finally, Java also supports a documentation comment, which starts with /** and ends with */.This
comment is designed to be used with the javadoc tool, which can create documentation for you nearly
automatically. An example of using /** and */ is as follows:
/** This application prints out "Hello from Java!" */
public class App {
public static void main(String[] args) {
System.out.println("Hello from Java!"); }
}
Commenting your code can be invaluable in team environments where you share your code source files with
others. Its also handy if someone else is going to take over a project that you have been working on.
Import Java Packages and Classes
Hmm, says the NP. I have got a problem. The Design Team Coordinator told me to use the Date class for
printingout the current date in my application, but Java doesnt seem to have ever heard of the Date classI get
an error every time I try to use it. Thats because the Date class is part of the java.util package, and you
have to import that package before you can use it. Import it? the NP asks.
The classes that Sun has created for you to use are stored in class libraries called packages. To make a class in a
package available to your code, you have to import the package, which means the compiler will search that
package for classes. You can also import individual classes that are not part of a package. By default, only the
basic Java statements are available to you in an application, that is, the ones in the core java.lang package. The
compiler automatically imports the java.lang package for you, but to use the rest of the classes that come with
Java, youll have to do your own importing with the import statement. Heres how you use that statement:
import [package1[.package2...].](classname|*);
Note that you put a dot (.) between the package and the class names to keep them separate. The standard Java
packages themselves are stored in a large package called java, so the util package is really called the
java.util package (there are other large packages like the java package available; for example, the extensive
swing package is stored in the javax package). You can refer to the Date class in java.util as
java.util.Date. Heres how to import that class into a program:
import java.util.Date;
public class App { . . .
}
Note that if you are going to use import statements for importing classes into a program, the import
statements should be at the top of the code. Now, we are free to use the Date class as follows (note that we are
creating an object from the Date class by using the Java new operator, which youll learn more about in
Chapter 4):
import java.util.Date;
public class App {
public static void main(String[] args) {
System.out.println("Today = " + new Date()); }
}
When you run this application, youll see the current date displayed as follows:
C:\>java App
Today = Tue July 17 14:05:15 IST 2012
You can see that by studying the general form of the preceding import statement, theres also a shorthand
technique that loads in all the classes in a packageyou can use an asterisk (*) as a wildcard to stand for all the
27
Chapter 1: Essential Java
classes in a particular package. Heres how that would look if you wanted to import all the classes in the
java.util package at once:
import java.util.*;
public class App {
public static void main(String[] args) {
System.out.println("Today = " + new Date()); }
}
Importing packages and classes only indicates to the compiler where to look for the code it needsit does not increase the size
of your code. For that reason, the bytecode file App.class will be of the same size regardless of whether you use the import
java.util.Date; statement or the import java.util.*; statement.
This is fine if you stick with importing the Sun-provided classes because Java knows where to look for the
classes it was installed with. But what if you want to import your own classes or ones provided by a third party?
Heres an example. Suppose you have a user-defined package named printer, having a class named Printer
in a file named Printer.java, and that class has one method named print:
package printer;
public class Printer {
public void print() { System.out.println("Hello from Java!"); }
}
You might want to make use of the print method in other classes. In this case, we are creating a new object of
the Printer class using the new operator and using that objects print method in an application named App:
public class App {
public static void main(String[] args) { (new Printer()).print(); }
}
To do this, you can import the Printer class as follows (note that you can also place the code for the Printer
class in the same file as the App class, in which case you wouldnt have to import the Printer class):
import printer.*;
public class App {
public static void main(String[] args) { (new Printer()).print(); }
}
Here, we have learned how to import a Java built-in and a user-created class in our Java program. To learn about
the implementation part and how to actually create and import packages in our classes, refer Chapter 27.
However, suppose you want to store all your classes in a directory named, say, c:\classes. How will the Java
compiler find Printer.class there? To answer that question, take a look at the next solution on CLASSPATH.
Finding Java Classes with CLASSPATH
That Johnson! the NP says. He gave me a new Java class file, johnson.class, to work with, and its
supposed to solve my problems with that spreadsheet. But, Java claims it cant find johnson.class! Where
are you keeping that file? you ask. In a special directory I made for it, the NP says, called darnjohnson.
Thats your problem, you say. You have to include the darnjohnson directory in your class path.
By default, Java will be able to find its bootstrap classes (the ones it comes with), extension classes (those that use
the Java Extension Framework), and classes in the current directory (that is, where you are compiling your
program). Classes can be stored in the .class files, .jar files, and .zip files. Java can search all these types
of files.
Bootstrap classes are the classes that come by default with JDK, and Extension classes are the classes that use the Java
Extension Framework. But, what if you want to have Java search for classes in another directory or in a .jar file supplied by a
third party? You can do that with the CLASSPATH environment variable because Java uses this variable to determine where
you want to search for classes.
28
Immediate Solutions
Heres an example that was first introduced in the previous solution. Say that you have a class named Printer
in a file named Printer.java and that class has one method named print:
public class Printer {
public void print() { System.out.println("Hello from Java!"); }
}
In the previous solution, you want to use the print method in another classas in this case where we are
creating a new object of the Printer class by using the new operator and using that objects print method in
an application named App:
import printer.*;
public class App {
public static void main(String[] args) { (new Printer()).print(); }
}
This works if Printer.class is in the same directory in which you are compiling this application, because the
Java compiler will search the current directory by default. But, suppose you want to store all your classes in a
directory named c:\classes. How will the Java compiler find Printer.class there?
To make the Java compiler search c:\classes, you can set the CLASSPATH environment variable to include
that directory. By default, there are no paths or directories in CLASSPATH, but you can add a semicolon-
separated list to CLASSPATH, like this (note that its important here not to have any spaces around the equals
sign):
SET CLASSPATH=c:\classes;c:\newclasses
You can also determine the current CLASSPATH setting by typing the SET CLASSPATH at the command line and
pressing Enter. To permanently set the classpath in Windows 7, follow these steps:
1. Click the Windows icon on the taskbar, right-click the Computer, and select the Properties option. You can
also reach the same location by opening the Control Panel| System and Security| System.
2. Click the Advanced system settings option in the System Properties window. This opens up the System
Properties dialog box.
3. Click the Environment Variables button to open the Environment Variables dialog box.
4. Edit the CLASSPATH setting the way you want.
5. You may append the new classpath to the already existing CLASSPATH variable or create a new
CLASSPATH variable.
6. Finally, click OK.
Note that if you are appending the CLASSPATH variable, the different paths must be separated by
semicolons (;).
Now, the Java compiler (and other Java tools, such as the java tool) will know enough to search c:\classes
and c:\newclasses automatically. This means that the following code will now work if Printer.class is
in c:\classes because that directory is in CLASSPATH:
import printer.*;
public class App {
public static void main(String[] args) { (new Printer()).print(); }
}
You can append the current settings in CLASSPATH to a new setting, like this:
SET CLASSPATH=c:\classes;c:\newclasses;%CLASSPATH%
Note that you can also search .jar and .zip files for classes, as shown here:
SET CLASSPATH=server.jar;classes.zip;%CLASSPATH%
Originally, CLASSPATH was a big headache for beginners in Java programming because no classes were
considered bootstrap classes, which meant that you had to set up and understand CLASSPATH before you could
use Java at all. Thats been fixed with the concept of bootstrap classes, which are the classes that come with Java
(and are searched automatically). However, if you want to use non-standard packages or store your own classes
in other directories, its important to know how to set CLASSPATH.
29
Chapter 1: Essential Java
Summary
In this chapter, you got familiar with Java 8, its environment, and designing of programs. The chapter
introduced you to Swings and Utilities. In addition, it discussed the enhancements in JDBC and provided a brief
description of garbage collector. You also learned how to install Java. Toward the end, you developed simple
Java programs with the introduction of how to import the packages.
In the next chapter, you will learn about the variables, arrays, and strings.
30
Chapter 2: Variables, Arrays, and Strings
2
Variables, Arrays,
and Strings
If you need an immediate solution to: See page:
What Data Types are Available? 37
Creating Integer Literals 37
Creating Floating-Point Literals 38
Creating Boolean Literals 39
Creating Character Literals 39
Creating String Literals 40
Creating Binary Literals 40
Using Underscores in Numeric Literals 41
Declaring Integer Variables 42
Declaring Floating-Point Variables 42
Declaring Character Variables 43
Declaring Boolean Variables 43
Initializing Variables Dynamically 44
Conversion between Data Types 45
Declaring One-Dimensional Arrays 47
Creating One-Dimensional Arrays 47
Initializing One-Dimensional Arrays 48
Declaring Multi-Dimensional Arrays 48
Creating Multi-Dimensional Arrays 48
Initializing Multi-Dimensional Arrays 49
Creating Irregular Multi-Dimensional Arrays 50
Getting an the Length of an Array 51
31
Chapter 2: Variables, Arrays, and Strings
If you need an immediate solution to: See page:
Understanding General Form of Static Import 51
Importing Static Members 51
The String Class 52
Creating Strings 56
Getting String Length 57
Concatenating Strings 58
Getting Characters and Substrings 58
Searching For and Replacing Strings 59
Changing Case in Strings 60
Checking for Empty String 60
Formatting Numbers in Strings 60
The StringBuffer Class 61
Creating StringBuffers 63
Getting and Setting StringBuffer Lengths and Capacities 64
Setting Characters in String Buffers 64
Appending and Inserting Using StringBuffers 65
Deleting Text in StringBuffers 65
Replacing Text in StringBuffer 65
Using the Wrapper Class 66
Autoboxing and Unboxing of Primitive Types 67
Learning the Fundamentals of Varargs Methods 69
32
In Depth
In Depth
This chapter begins our discussion of Java syntax, and youll see a great deal of syntax usage in this chapter. We
are going to cover how Java stores and retrieves data in variables, arrays, and strings. Working with data is a
fundamental part of any significant program, and the information in this chapter is essential for any Java
programmer. Even if you are familiar with Java and have already been programming in it, take a look at the
material in this chapter because theres a lot coming up.
Variables
There are various kinds of variable that serve as containers for storing data in the memory. Different kinds of
variable store data in different formats, and the selection of variable should be made depending upon the data
that they will be storing and the memory that will be required to be kept aside for storing it. For example, an
integer variable type, the int type, can store up to 4 bytes (or 32 bits) and contain only integer values between
2,147,483,648 and 2,147,483,647. There are some more variables that Java provides such as floating-point
numbers, short, long, byte, and char, and all of them will be explained in this chapter.
Before you use a variable in Java, you must declare it, specifying its data type. Heres how you declare variables
in Java:
type name [= value][, name [= value]...];
Heres an example showing how to declare a variable of the int type, which means a numeric value will be
stored in it (the variable is named days):
public class App {
public static void main(String[] args) {
int days;
. . . }
}
This code allocates 32 bits of storage in memory and labels the location of that storage, as far as the Java compiler
is concerned, as days, which means you can now refer to that name in code. Heres how to store a numeric
value 365 in the days variable using the Java assignment operator (=):
public class App {
public static void main(String[] args) {
int days;
days = 365;
. . . }
}
Here, the value 365 is an integer literal, which means a literal value that you place directly in your code. Well
take a look at what kinds of literal Java allows throughout this chapter. To verify that days now hold 365, you
can print it out on the console:
public class App {
public static void main(String[] args) {
int days;
days = 365;
System.out.println("Number of days = " + days); }
}
Heres the result of this code:
C:\>java App
Number of days = 365
As you can see, we have created a variable, stored data in it, and fetched the same data to print it on the screen.
Thats how it works.
Theres also a convenient shortcut that lets you initialize a variable when you declare it. Here, days are declared
and initialized to 365 in one step:
public class App {
public static void main(String[] args) {
int days = 365;
33
Chapter 2: Variables, Arrays, and Strings
System.out.println("Number of days = " + days); }
}
The int type is only one kind of simple variable you can use. Mentioned below are the various possibilities:
IntegersRefer to the types byte, short, int, and long that hold signed, whole-value numbers.
Floating-point numbersRefer to the types float and double that hold signed floating-point numbers.
CharacterRefers to the char type that holds characters such as letters and numbers.
BooleanRefers to the type that holds only two types of values: true and false.
Well take a closer look at all these in the Immediate Solutions section, including what range of values each can
hold. Together, these types make up what are called simple data types in Java. Each of these types represents a
single data value, not a compound data value (as opposed to an array, which is also discussed in this chapter).
You can store one data item in a variable made up of any simple data type, and that data item must fit in the
range allowed for that data type.
Data Typing
Java puts considerable emphasis on its data types. Its a strongly-typed language, which means it insists that the
simple variables you declare and use must fit in the listed types.
Every simple variable must have a type (and in fact, every expressionevery combination of terms that Java can
evaluate to get a valuehas a type as well). Also, Java is very particular about maintaining the integrity of those
types, especially if you try to assign a value of one type to a variable of another type. In fact, Java is more
strongly typed than a language such as C++. In C++, for example, you can assign a floating-point number to an
integer, and C++ will handle the type conversion for you, but you cannot do that in Java. You can, however,
convert between certain data types in Java such as between the integer types. Well take a look at that later in this
chapter.
When working with variables, you might find the Java compiler issuing a lot of errors and warnings about data types, which can
take some time getting used to; bear in mind that the inspiration for making Java very particular about adhering to data types
and not mixing them easily is to prevent errors in your code.
Thats an overview of whats going on in Java with simple data types and variables; its now time to take a look
at compound data storage in depth, which as far as this chapter is concerned means arrays.
Arrays
Simple types are good only for storing single data items. However, sometimes the data that needs to be stored is
a lot more complex. For instance, you want to start a new bank, say, JP Bank (short for Java Programming Bank)
and keep a track of the amount in each account indexed by account number. This situation presents the need to
work with compound data. The usage of arrays is appropriate in such a scenario.
An array allows grouping of simple data to form a compound data structure that can be referred to by using a
single name. Every data item stored in that compound data structure is stored at a particular position in the
array and can be referred by the numeric index (or position) of the data in the data structure. It is vital to store
the data in indexed form with the index sorted numerically because computers perform millions of operations
in a second and data stored in indexed form can be referenced using the numerical value. This way the entire
data structure can be traversed by simply incrementing the indexs value, and the values can be accessed with
ease.
Heres an example. In this case, well start the Java Programming Bank out with 100 new accounts, and each one
will have its own entry in an array named accounts[]. The square braces at the end of the accounts[]
represent that it is an array and the value of the index can be placed enclosed in those braces to refer to the value
stored at a particular position. Heres how we create the accounts[] array, making each entry in it of the
floating-point type double for extra precision. First, we declare the array; then, we create it with the new
operator, which is what Java uses to actually allocate memory:
public class App {
34
In Depth
public static void main(String[] args) {
double accounts[];
accounts = new double[100];
. . .
Now that we have created an array with 100 items, we can refer to those items numerically, like this (note that
we are storing $43.95 in account 3 and printing that amount out):
public class App {
public static void main(String[] args) {
double accounts[];
accounts = new double[100];
accounts[2] = 43.95;
System.out.println("Account 3 has $" + accounts[2]); }
}
Heres the result of this program:
C:\>java App
Account 3 has $43.95
As you can see, you can now refer to the items in the array by using a numeric index, which organizes them in
an easy way. In Java, the lower bound of an array you declare this way is 0, so the statement accounts = new
double[100] creates an array whose first item is accounts[0] and last item is accounts[99].
You can combine the declaration and creation steps into one step, as shown below:
public class App {
public static void main(String[] args) {
double accounts[] = new double[100];
accounts[2] = 43.95;
System.out.println("Account 3 has $" + accounts[2]); }
}
You can also initialize an array with values when you declare it if you enclose the list of values you want to use
in curly braces, as youll see in this chapter. For example, this code creates four accounts and stores 43.95 in
accounts[3]:
public class App {
public static void main(String[] args) {
double accounts[] = { 0, 0, 0, 43.95 };
System.out.println("Account 4 has $" + accounts[3]); }
}
It turns out that some of the customers in the Java Programming Bank are unhappy, though; they want a
checking account in addition to a savings account. How will you handle this and still keep things indexed by
account number?
The accounts[] array is a one-dimensional array, also called a vector, which means you can think of it as a
single list of numbers that you can index with one number. However, arrays can have multiple dimensions in
Java, which means you can have multiple array indexes. In this next example, well extend accounts[] into a
two-dimensional arrayaccounts[][]to handle both a savings account and a checking account. The first
index of accounts[][] will be 0 for savings accounts and 1 for checking accounts, and the second index will be
the account number as before. Heres how this works in code:
public class App {
public static void main(String[] args) {
double accounts[][] = new double[2][100];
accounts[0][2] = 43.95;
accounts[1][2] = 2385489382.06;
System.out.println("Savings account 3 has $" + accounts[0][2]);
System.out.println("Checking account 3 has $" + accounts[1][2]); }
}
After creating a two-dimensional array, values in it can be referenced using two index values. For example, here
we are assuming the value 0 for savings account and 1 for checking account. The savings account details in the
account number 3 can now be referenced as accounts[0][2] and that in the checking account can be
referenced as accounts[1][2]. Shown here are the results when you run this application:
C:\>java App
Savings account 3 has $43.95
Checking account 3 has $2.38548938206E9
35
Chapter 2: Variables, Arrays, and Strings
Note that we have given account 3 a checking balance of $2,385,489,382.06 (wishful thinking) and that Java has
printed that out as 2.38548938206E9. This is Javas shorthand for 2.38548938206X10 9not an inconsiderable bank
balance by any means.
Youll see a lot of arrays in this chapter, but you should know that Java now supports much more complex data structures than
arrays. These data structures are built into the language. Java now supports hashes and maps as well as other types of data
structure, and as youll see all that when we take a look at the collection classes in the forthcoming chapter.
Strings
You may have noticed that we have been using the + operator to create the text to print in the previous examples
like this:
public class App {
public static void main(String[] args) {
double accounts[][] = new double[2][100];
accounts[0][2] = 43.95;
accounts[1][2] = 2385489382.06;
System.out.println("Savings account 3 has $" + accounts[0][2]);
System.out.println("Checking account 3 has $" + accounts[1][2]); }
}
Thats because their own class in Javathe String classsupports text strings and you can think of the
String class as defining a new data type.
For example, heres how we create a string named greeting that holds the text Hello from Java!:
public class App {
public static void main(String[] args) {
String greeting = "Hello from Java!";
. . .
Now we can treat this string as we would other types of variables, including printing it out:
public class App {
public static void main(String[] args) {
String greeting = "Hello from Java!";
System.out.println(greeting); }
}
Heres the result of this application:
C:\>java App
Hello from Java!
Although strings are not one of the simple data types in Java, yet they deserve a place in this chapter because
most programmers treat them as they would any other data type. In fact, many programmers would argue that
strings should be a simple data type in Java as they are in other languages. The reason they are not has to do
with Java lineage, which stretches back to C. C has no string simple data type; in C, you handle strings as one-
dimensional arrays of characters, which is pretty awkward. One of the things that made programmers happy
about C++ was that most implementations included a String class that you could use much as you would any
other data type. Java follows this usage, implementing strings as a class, not as an intrinsic data type, but string
handling is so fundamental to programming that it makes sense to start looking at string variables in this
chapter.
There are two string classes in JavaString and StringBuffer. You use the String class to create text
strings that cannot change, and you can use StringBuffer to create strings you can modify. As you can see in
the preceding code, you can use strings much as you would any simple data type in Java. Well take a look at
using strings in this chapter as well as in the next chapter (which is on using operators such as + and ). Well
also take a look at using operators on strings.
Thats enough overview for nowits now time to start creating and using variables, arrays, and strings.
36
Immediate Solutions
Immediate Solutions
What Data Types are Available?
Say, the Big Boss (BB) says, how about writing a Java program to manage the companys debt? We are in
debt? you ask. Just a little, the BB replies. How little? you ask. About $2,848,238,493, 902.77, says the BB.
Hmm! you say. Sounds like a job for floating-point numbers.
What simple data types can you use to create variables in Java? Youll find them in Table 2.1 below. The simple
data types can be broken up by category, as we did at the beginning of this chapter, like this:
IntegersRefer to the byte, short, int, and long types. They contain signed, whole-value numbers.
Floating point numbersRefer to the float and double types. They contain signed, floating-point
numbers.
CharacterRefers to the char type that holds characters such as letters and numbers.
BooleanRefers to the type that holds only two types of values: true and false.
Table 2.1: Variable types
Variable type Bytes of storage Range
boolean 1 bit True, False
byte 1 -128 to 127
char 2 \u0000 to \uffff
double 8 4.9E-324 to 1.7976931348623157E308
float 4 1.4E-45 to 3.4028235E+38
int 4 -2,147,483,648 to 2,147,483,647
long 8 -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
short 2 -32,768 to 32,767
Thats an overview of what simple data types are available; to put each of them to work, see the following
solutions.
Its worth realizing that you cant completely count on the numeric precision listed in Table 2.1 because Java implementations
do differ by machine. However, you can use the StrictMath class (you can find more about these classes at
http://docs.oracle.com/javase/8/docs/api/) to ensure that the same mathematical precision is used no matter what platform your
program is running on.
Creating Integer Literals
The Novice Programmer (NP) appears and says, So, how do I assign a hexadecimal valuethat is, base 16to a
variable in Java? You say, You have to use a hexadecimal literal, which starts with the characters 0x or 0X.
A literal is a constant value that you can use directly in your Java code, and there are a number of rules that
govern them. We have already used integer literals in this chapter, which is the most common type
programmers use. Heres the example:
public class App {
public static void main(String[] args) {
int days = 365;
System.out.println("Number of days = " + days); }
}
37
Chapter 2: Variables, Arrays, and Strings
Here, we are assigning an integer literal with a value of 365 to the variable days. By default, integer literals are
of the int type. However, if you assign them to other integer types, such as short, Java converts the literal type
automatically. On the other hand, long values can have more digits than int values, so Java provides an
explicit way of creating long literals: You append an L to the end of the literal. Heres an example:
public class App {
public static void main(String[] args) {
long value;
value = 1234567890123456789L;
System.out.println("The value = " + value); }
}
Heres the result of this code:
C:\>java App
The value = 1234567890123456789
You can also create literals in octal format by starting them with a leading zero and in hexadecimal format by
starting with 0x or 0X. Here are some examples:
public class App { public static void main(String[] args) {
int value; value = 16;
System.out.println("16 decimal = " + value);
value = 020;
System.out.println("20 octal = " + value + " in decimal");
value = 0x10;
System.out.println("10 hexadecimal = " + value + " in decimal"); }
}
Heres what this program displays:
C:\>java App
16 decimal = 16
20 octal = 16 in decimal
10 hexadecimal = 16 in decimal
Creating Floating-Point Literals
The Novice Programmer appears and says, I have a problem. I want to put a floating-point number 1.5 into a
floating-point variable, but Java keeps saying Incompatible type for =. Explicit cast needed to convert double.
Whats going on? You say, By default, the floating-point numbers used as literals are actually of type double
and not of type float. You can change that by adding an f or F to the end of the literal to make it a float, or a d
or D to make it a double. Oh! the NP replies.
Floating-point literals are of type double by default in the Java code; examples include 3.1415926535, 1.5, and
0.1111111. The standard notation for floating-point literals is to have a whole number followed by a fractional
part. You can also indicate a power of 10 with e or E, like this:
1.345E10
This is the same as 1.345X1010 or 9.999E23, which is the same as 9.999X1023. Heres an example in which we
are trying to assign a floating-point literal to a variable of type float:
public class App { public static void main(String[] args) {
float value;
value = 1.5;
System.out.println("The value = " + value); }
}
Unfortunately, the default type for floating-point literals is double, so Java gives me the following error:
C:\>javac App.java
App.java:2: error: incompatible types: possible lossy conversion from double to float
value = 1.5;
^
1 error
We can fix this by explicitly making my literal into a float, like this:
public class App {
public static void main(String[] args) {
float value;
value = 1.5f;
38
Immediate Solutions
System.out.println("The value = " + value); }
}
Now the code runs as youd expect:
C:\>java App
The value = 1.5
Creating Boolean Literals
Boolean values can only be true or false in Java (not 0 or 1 or other numeric values as in other languagesthis is
the part of Javas strong data typing). This means that only two Boolean literals you can use are true and false.
Heres an example using true as a Boolean literal:
public class App {
public static void main(String[] args) {
boolean value;
value = true;
System.out.println("The value = " + value); }
}
Heres the result of this program:
C:\>java App
The value = true
Creating Character Literals
Hey, says the Novice Programmer, how do I assign a letter to a variable in Java? Im evaluating all the
companys products and want to assign them letter grades. You can use character literals, each of which
represents a character, you reply. By the way, does the Big Boss know about this? Not yet, says the NP.
The basic form of a Java character literal is just a value that corresponds to a character in the Unicode character
set (for more on Unicode, see http://www.unicode.org). Character literals are actually numbers that act as
indexes into the Unicode character set, not actual characters. For example, the Unicode code for the letter C is 67.
Therefore, the following application prints out a C:
public class App {
public static void main(String[] args) {
char char3;
char3 = 67;
System.out.println("The third letter in alphabet = " + char3); }
}
Heres the result of the above code:
C:\>java App
The third letter in alphabet = C
However, you can also refer to the Unicode code for the letter C with a character literal, which you would
enclose in single quotes, like this:
public class App {
public static void main(String[] args) {
char char3; char3 = 'C';
System.out.println("The third letter in alphabet = " + char3); }
}
Heres is the result of this code, which, obviously, is the same as the result of the previous code:
C:\>java App
The third letter in alphabet = C
Besides enclosing characters in single quotes to make character literals, you can also enclose special character
escape sequences in single quotes to make character literals that you couldnt make by typing a single character.
Here are the escape sequences:
\ (single quote)
\ (double quote)
\\ (backslash)
\b (backspace)
39
Chapter 2: Variables, Arrays, and Strings
\ddd (octal character)
\f (form feed)
\n (newline; called a line feed in DOS and Windows)
\r (carriage return)
\t (tab)
\uxxxx (hexadecimal Unicode character)
For example, if you want to show a double quotation mark in the displayed text, you can use the \ escape
sequence, like this:
public class App {
public static void main(String[] args) {
System.out.println("He said, \"Hello!\""); }
}
Heres the result of this code:
C:\>java App
He said, "Hello!"
Creating String Literals
The Novice Programmer is backthis time with some coffee. OK, the NP says, heres the problem: I want to
use just one println statement to print out multiple linescan I do that? Sure, you say, As long as you use
the \n character literal to stand for a newline. Hows that? the NP asks.
Heres an example of what the NP wants to do. In this case, well print out some multiline text using the \n
character literal to start a new line:
public class App {
public static void main(String[] args) {
System.out.println("Here is \nsome multiline\ntext"); }
}
Heres the output of this application:
C:\>java App
Here is
some multiline
text
As with most other programming languages, you can enclose text string literals in double quotes (unlike single
character literals, which you enclose in single quotes). You can also use the character escape sequences
introduced in the previous topic. Note that string literals in Java code are actually converted by the compiler into
String objects, not inherent simple data types (which means that odd code such as Hello.length() is
perfectly legal and will return the length of the string Hello).
Creating Binary Literals
The Novice Programmer is back and says, How can we create a literal of integer type and save the value in the
literal in binary format? You are confused and say, And why would you want to do that? The NP says, I
have just learned the procedure to convert decimals to binary and thought that the computer eventually stores
and processes everything in binary. Why not save some time of the computer by providing the value in binary
directly. I want to help the poor guy.
One of the features that Java has implemented is to assign the values in binary format. If you are assigning a
value in binary format, you need to use the letters 0b before keying in the actual value. The binary literals
express the integral type in the binary number system.
The literals are useful in a number of programming tasks to be performed. They are frequently used to create
numeric arrays. The relation between the data members of the array, which is represented using the binary
literals, is more apparent than the relation represented using the members in the hexadecimal or octal notations.
The reason behind the apparent relation representation is that the numbers represented using binary literals are
40
Immediate Solutions
more detailed than the hexadecimal or octal literals. A good example of the relation between the array members
is rotation of 2 bits among the successive array members, as shown in the following example:
public class App {
public static void main(String[] args) {
int val = 0b00010000;
int myPhases[] = {
0b00110011,
0b11001100,
0b00110011,
0b11001100 };
System.out.println("The value in val is: " + val);
System.out.println("And following are the values stored in the array myPhases:");
System.out.println(myPhases[0]);
System.out.println(myPhases[1]);
System.out.println(myPhases[2]);
System.out.println(myPhases[3]); }
}
The output of the program is as follows:
C:\>java App
The value in val is: 16
And following are the values stored in the array myPhases:
51
204
51
204
Using Underscores in Numeric Literals
The Novice Programmer says, I want to store the credit card numbers in variables and make them more
readable by separating the digits the way they are printed on the credit cards. The NP adds, I would also like
to perform mathematical operations on those values because I will be giving out the cards in sequential order.
You respond, Well, that is not possible unless you are using the latest version of Java, that is, Java 7 or 8. You
add, This is a new feature of Java 7 that allows the programmer to enter the integer values and separate them
with underscores to make them more readable.
The use of underscores in numeric literals is a newly introduced feature of Java 7. This allows the programmer
the freedom to use underscores in numeric literals, making it more readable and minimizing the typographical
errors that are very likely otherwise. You can use any number of underscore characters (_) to break the groups of
digits in the long numeric literals. The literals still remain very much ready for performing mathematical
operations. This feature was added to Java just for the sake of adding more readability to the numeric values.
An example that demonstrates the usage of underscores in numeric literals is as follows:
public class App {
public static void main(String[] args) {
long card = 1345_4489_4545_7252L;
System.out.println("Your Credit Card number is: " + card);
}
}
The output of the preceding code is as follows:
C:\>java App
Your Credit Card number is: 1345448945457252
The underscores will not be displayed during the execution, as they are only for the convenience of the
programmer. For example, in the above program, we have created a variable of the type long and saved a
hypothetical 16-digit credit card number that contains underscores to separate every four digits. The L at the end
of the credit card number in the program signifies that the value is of the long data type.
41
Chapter 2: Variables, Arrays, and Strings
It is important to note that you can put underscores in a numeric literal only in between the digits of the numeric
literal. Or the underscore character should be accompanied by at least one digit on each side. You cannot place
an underscore in the numeric literals in the following places:
At the start or the end of the numeric literal
Next to the decimal point in the floating-point literal
In front of an F or L suffix in the floating-point or long literal
Places where a string of digits is expected in the numeric literal
Declaring Integer Variables
Now Im into some real programming, the Novice Programmer says, and I need to store some integer data.
How can I do that? With an integer variable., you say, Pull up a chair and Ill go through it.
Java uses four types of integer, each with its own number of bytes put aside for it in memorybyte (1 byte),
short (2 bytes), int (4 bytes), and long (8 bytes). For the range of possible values each type can handle, see the
topic What Data Types Are Available? in the Immediate Solutions section of this chapter. Which one you use
depends on the range of data you want to use as well as other considerations such as how much memory is
available (in case you want to set up a lot of integers).
Heres an example that puts all the integer types to use, declares an integer of each type, assigns each type some
data, and then displays that data:
public class App {
public static void main(String[] args) {
byte byte1;
short short1;
int int1;
long long1;
byte1 = 1;
short1 = 100;
int1 = 10000;
long1 = 100000000;
System.out.println("byte1 = " + byte1);
System.out.println("short1 = " + short1);
System.out.println("int1 = " + int1);
System.out.println("long1 = " + long1); }
}
Heres the result of this application:
byte1 = 1
short1 = 100
int1 = 10000
long1 = 100000000
Declaring Floating-Point Variables
Sorry, says the Novice Programmer, but integers just dont cut it. Im trying to design a currency converter,
and I thought I could ignore the cents part of each value, but the Big Boss told me that every cent counts. Is there
any other data type we can use? Sure, you say. You can use the float and double types.
Java has two built-in types of floating-point variables, each with its own number of bytes set aside for it in
memory: float (4 bytes) and double (8 bytes). For the range of possible values each type can handle, see the
topic What Data Types Are Available? in this chapter. The one you use depends on the range of data you want
to use as well as other considerations such as how much memory is available (in case you want to set up a lot of
floating-point values).
Heres an example that declares and uses both a float and a double (note that we explicitly make each literal
value either a float or a double literal so that therell be no problem with type conversions):
public class App {
public static void main(String[] args) {
float float1;
42
Immediate Solutions
double double1;
float1 = 1.11111111111F;
double1 = 1.1111111111111E+9D;
System.out.println("float1 = " + float1);
System.out.println("double1 = " + double1); }
}
Heres the output of the code (note that we have exceeded the precision allowed for a float, so its value is
rounded):
C:\>java App
float1 = 1.1111112
double1 = 1.1111111111111E9
Declaring Character Variables
You can declare character variables with the keyword char. For the possible values you can store in a char
variable, see the topic Creating Character Literals in this chapter.
Heres an example that declares two char variables: char1 and char2. This example demonstrates that you can
assign either a Unicode code or a character literal to a char (in fact, the compiler translates character literals into
Unicode codes):
public class App {
public static void main(String[] args) {
char char1, char2;
char1 = 65;
char2 = 'B';
System.out.println("char1 = " + char1);
System.out.println("char2 = " + char2); }
}
Heres the result of this code:
C:\>java App
char1 = A
char2 = B
Heres a sneak peak at a future topic, in which we add some text to the end of char1, converting it to a string,
and increment the value in char2, changing it from B to C:
public class App {
public static void main(String[] args) {
char char1, char2;
char1 = 65;
char2 = 'B';
System.out.println("char1 = " + char1);
System.out.println("char2 = " + char2);
System.out.println("char1 + 1 = " + char1 + 1);
System.out.println("char2 = " + ++char2); }
}
Heres the output of the new version of this program:
C:\>java App
char1 = A
char2 = B
char1 + 1 = A1
char2 = C
Declaring Boolean Variables
You declare Boolean variables with the boolean keyword. Boolean variables can take only two values in Java
true and false (not numerical values such as 0 and 1 as in other programming languages). Heres an example in
which we declare and use two Boolean variables:
public class App {
public static void main(String[] args) {
boolean boolean1, boolean2;
boolean1 = true;
boolean2 = false;
43
Chapter 2: Variables, Arrays, and Strings
System.out.println("boolean1 = " + boolean1);
System.out.println("boolean2 = " + boolean2);
}
}
Heres the result of this code:
C:\>java App
boolean1 = true
boolean2 = false
Boolean values are usually used in tests to determine program flow. We are going to jump the gun here and give
you a sneak peek into the next chapter. Here, we are using these two Boolean variables with the Java if
statement. We test the value in boolean1 with the if statement, which makes the code display the message
boolean1 is true (if its true) and boolean1 is false (otherwise):
public class App {
public static void main(String[] args) {
boolean boolean1, boolean2;
boolean1 = true;
boolean2 = false;
System.out.println("boolean1 = " + boolean1);
System.out.println("boolean2 = " + boolean2);
if(boolean1) { System.out.println("boolean1 is true"); }
else { System.out.println("boolean1 is false"); }
}
}
Heres the new result from this code:
C:\>java App
boolean1 = true
boolean2 = false
boolean1 is true
Initializing Variables Dynamically
OK, the Novice Programmer says, I have got it straight now. First, I declare a variable and then I assign a
value to it. Actually, you say, You can do both in one step. The NP replies, Tell me how!
So far, we have been declaring variables and then assigning values to them, like this:
public class App {
public static void main(String[] args) {
int int1;
int1 = 1;
System.out.println("int1 = " + int1); }
}
However, we can combine these two steps into one by initializing a variable when we declare it, like this:
public class App {
public static void main(String[] args) {
int int1 = 1;
System.out.println("int1 = " + int1); }
}
Heres how to declare and initialize multiple variables:
public class App {
public static void main(String[] args) {
int int1 = 1, int2 = 2, int3 = 3;
System.out.println("int1 = " + int1 + ", int2 = " + int2 + ", int3 = " + int3); }
}
Heres the result of this program:
C:\>java App
int1 = 1, int2 = 2, int3 = 3
Up to this point, we have just assigned constant values to variables, but you can assign any expression (an
expression is any combination of Java terms that yields a value) to a variable when that variable is declared, as
long as the expression is valid at that time. For example, here we are assigning a value of 2 to int1, a value of 3
to int2, and the value of int1 times int2 to int3 using the Java multiplication operator (*):
44
Immediate Solutions
public class App {
public static void main(String[] args) {
int int1 = 2, int2 = 3;
int int3 = int1 * int2;
System.out.println("int1 = " + int1 + ", int2 = " + int2 +
", int3 = " + int3); }
}
Heres what this code gives you when you run it:
C:\>java App
int1 = 2, int2 = 3, int3 = 6
Note that the Java compiler has no idea what int1 times int2 will be when it creates the bytecodes for this
application. This means the actual value with which int3 is initialized will be determined at runtime, which is
why this process is called dynamic initialization.
As in C++, in Java, you can also intersperse your variable declarations throughout your code, as we are doing here:
public class App {
public static void main(String[] args) {
int int1 = 2, int2 = 3;
System.out.println("int1 = " + int1 + ", int2 = " + int2);
int int3 = int1 * int2;
System.out.println("int3 = " + int3); }
}
Heres the result of this code:
C:\>java App
int1 = 2, int2 = 3
int3 = 6
Conversion between Data Types
Uh oh, says the Novice Programmer. Im stuck. I have an int variable that I want to assign to a byte variable,
but Java keeps giving me an Incompatible type for =. error. Whats wrong? Thats a type conversion
problem, you explain, and you have to use an explicit type cast. Hmm, says the NP, how does that work?
Java is a strongly typed language; and as a result, you are often faced with the situation of assigning a variable of
one type to a variable of another type. The assigning of a variable of one type to a variable of another type can
be done by either relying on automatic type conversion or making an explicit type cast. Well take a look at
both here.
Automatic Conversions
When you are assigning one type of data to a variable of another type, Java will convert the data to the new
variable type automatically if both the following conditions are true:
The data type and the variable types are compatible.
The target type has a larger range than the source type.
For example, you can assign a byte value to an int variable because byte and int are compatible types, and
int variables have a larger range than byte values. Therefore, no data will be lost in the type conversion. Heres
an example:
public class App {
public static void main(String[] args) {
byte byte1 = 1;
int int1;
int1 = byte1;
System.out.println("int1 = " + int1); }
}
The Java compiler has no problem with this code, and it makes the type conversion automatically. Heres the
result of this program:
C:\>java App
int1 = 1
45
Chapter 2: Variables, Arrays, and Strings
Converting a data type to another with a larger range is called widening conversion. In widening conversions, the
numeric types, such as the integer and floating-point types, are compatible with each other. On the other hand,
char and boolean types are not compatible with each other or with the numeric types.
Casting to New Data Types
Performing a conversion from a data type of larger range to one that has a smaller range is called narrowing
conversion. The Java compiler does not perform automatic narrowing conversions because there are chances of
losing accuracy. To perform a narrowing conversion, it must be done with an explicit cast, which looks
like this:
(target-data-type) value
For example, in this code, we are converting an integer type into a byte type:
public class App {
public static void main(String[] args) {
byte byte1; int int1 = 1;
byte1 = (byte) int1;
System.out.println("byte1 = " + byte1); }
}
Trying to perform a narrowing conversion would throw an exception, but performing the same with the explicit
type cast would not. This is due to the fact that Java assumes that you are aware of the possibility of losing data
by converting a potentially larger data with a larger data type into a smaller type. Simply put, the programmer is
responsible for any loss of data while performing any narrowing conversions. For example, when you put a
floating-point number into a long, the fractional part of the number will be truncated, and you may lose more
data if the floating-point value is outside the range that a long can hold.
Heres the output of this code:
C:\>java App
byte1 = 1
One thing to note is that the Java compiler also automatically promotes types as needed when it evaluates
expressions. For example, consider the following code, in which everything looks like it involves only bytes:
public class App {
public static void main(String[] args) {
byte byte1 = 100; byte byte2 = 100; byte byte3;
byte3 = byte1 * byte2 / 100;
System.out.println("byte3 = " + byte3); }
}
Here Java gives the following error:
C:\>javac App.java
App.java:4: error: incompatible types: possible lossy conversion from int to byte
byte3 = byte1 * byte2 / 100;
^
1 error
However, because Java knows that multiplying bytes can result in integer-sized values, it automatically
promotes the result of the byte1 * byte2 operation to an integer, which means you actually have to use an
explicit cast here to get back to the byte type:
public class App {
public static void main(String[] args) {
byte byte1 = 100;
byte byte2 = 100;
byte byte3;
byte3 = (byte) (byte1 * byte2 / 100);
System.out.println("byte3 = " + byte3); }
}
This code compiles and runs as youd expectbut it wouldnt without the (byte) cast:
C:\>java App
byte3 = 100
46
Immediate Solutions
In general, the Java compiler promotes byte and short types to int types in expressions. If one operand is a long, the entire
expression is made a long. Similarly, if one operand is a float, the whole expression is made a float; if one operand is a double,
the whole expression is made a double.
Declaring One-Dimensional Arrays
The Big Boss appears and says, Its time to start cracking down on customers who are overdue paying their bills
to me. OK, you say, Can I see the accounts? I never actually kept any accounts, the BB says. Oh, you
reply. I guess Ill have to set up an array to store the accounts in first.
As explained earlier in this chapter, arrays provide an easy way of handling a set of data by index, which is great
for computers because then you can manipulate the index in your code. Java supports one-dimensional and
multi-dimensional arrays, and well take a look at both of them here. Getting an array ready for use is a two-step
process. First, you must declare the array. Heres how you declare a one-dimensional array in general:
type name[];
For example, heres how to declare an array of double values, which well name accounts[]:
public class App {
public static void main(String[] args) {
double accounts[];
. . . }
}
In fact, theres another way of doing this that follows the pointer-declaration syntax in C++. You can also declare arrays with the
brackets ([]) after the type, not the name of the variable, like this: double[ ] accounts.
Unlike declaring simple variables, declaring an array does not set aside memory for the array because Java isnt
sure how big you want it to be yet. This means theres another step to the processactually creating the array.
See the next topic for the details.
Creating One-Dimensional Arrays
After youve declared a one-dimensional array, the next step is to actually create that array by allocating
memory for it. As youll see in the forthcoming chapter, the Java memory allocation operator is the new operator.
Therefore, we can create and use the new array like this:
public class App {
public static void main(String[] args) {
double accounts[];
accounts = new double[100];
accounts[2] = 1335.67;
System.out.println("Account 3 is overdue by $" + accounts[2]); }
}
Here, we have created an array of exactly 100 double values, all of which Java initializes to 0. The lower bound
of all Java arrays is 0, so the first element in the array is accounts[0] and the last element is accounts[99]. If
the array index is outside the range 0 to 99, Java will create a fatal error, and the program will halt. Heres the
result of this program:
C:\>java App
Account 3 is overdue by $1335.67
In fact, you can combine the declaration and creation processes into one step for arrays, like this:
public class App {
public static void main(String[] args) {
double accounts[] = new double[100];
accounts[2] = 1335.67;
System.out.println("Account 3 is overdue by $" + accounts[2]); }
}
47
Chapter 2: Variables, Arrays, and Strings
Initializing One-Dimensional Arrays
The Novice Programmer is back with a question. I know I can initialize simple variables when I declare them,
the Novice Programmer says, but what about initializing arrays when I declare them? No problem, you say.
To initialize the data in one-dimensional arrays, you just place the values between curly braces, one value after
the other, separated by commas, beginning with the first value in the array. Heres an example that initializes the
first four elements of the accounts[] array with data:
public class App {
public static void main(String[] args) {
double accounts[] = {238.45, 999.33, 0, 1335.67};
System.out.println("Account 4 is overdue by $" + accounts[3]); }
}
Declaring Multi-Dimensional Arrays
Hmm, says the Novice Programmer thoughtfully, I think I need more than a one-dimensional array. Im
supposed to be keeping track of products as indexed by product number, and the array is supposed to store the
number of items in inventory, the cost of each item, the number sold, the number . Hold it, you say. Use a
multi-dimensional array.
You can declare multi-dimensional arrays in much the same way you declare one-dimensional arrays; just
include a pair of square brackets for every dimension in the array:
type name[][][]...;
We looked at declaring multi-dimensional arrays previously in this chapter; for example, heres how to declare a
two-dimensional array with two rows and 100 columns:
public class App {
public static void main(String[] args) {
double accounts[][] = new double[2][100];
. . . }
}
In fact, theres another way of doing this that follows the pointer-declaration syntax in C++. You can also declare arrays with the
brackets ([ ]) after the type, not the name of the variable, like this: double[ ][ ] accounts.
Thats how it works with two-dimensional arraysthe left index specifies the row in the array and the right
index specifies the column. Of course, you dont have to limit yourself to two dimensions.
Heres how you can declare a four-dimensional array:
public class App {
public static void main(String[] args) {
double accounts[][][][] = new double[2][3][4][5];
. . . }
}
As you can see, its as easy to declare multi-dimensional arrays as it is to declare one-dimensional arrays. Now
what about actually creating the declared array? See the next topic for the details.
Creating Multi-Dimensional Arrays
The Novice Programmer asks, Now that I have declared a new multi-dimensional array, how do I create it?
Coming right up, you say.
You create a new multi-dimensional array by allocating memory for it with the new operator, giving the array
the dimensions you want. Heres how this looks in an example:
public class App {
public static void main(String[] args) {
double accounts[][];
accounts = new double[2][100];
accounts[0][2] = 43.95;
accounts[1][2] = 2385489382.06;
System.out.println("Savings account 3 has $" + accounts[0][2]);
48
Immediate Solutions
System.out.println("Checking account 3 has $" + accounts[1][2]); }
}
Heres the result of this code:
C:\>java App
Savings account 3 has $43.95
Checking account 3 has $2.38548938206E9
You can also condense the declaration and memory allocations into one step, like this:
public class App {
public static void main(String[] args) {
double accounts[][] = new double[2][100];
accounts[0][2] = 43.95;
accounts[1][2] = 2385489382.06;
System.out.println("Savings account 3 has $" + accounts[0][2]);
System.out.println("Checking account 3 has $" + accounts[1][2]); }
}
Heres an example that creates and uses a four-dimensional array:
public class App {
public static void main(String[] args) {
double accounts[][][][] = new double[2][3][4][5];
accounts[0][1][2][3] = 43.95;
System.out.println("Account [0][1][2][3] has $" +
accounts[0][1][2][3]); }
}
Heres the result of this program:
C:\>java App
Account [0][1][2][3] has $43.95
Multi-dimensional arrays are actually arrays of arrays, which means that if you have a two-dimensional array
(array[][]), you can actually treat it as an array of one-dimensional arrays, which you can access as
array[0], array[1], array[2], and so on. Heres a slightly advanced example of doing just that using a
for loop (which youll see more of in the next chapter) and using the length property (which youll see in a
few topics) to find the length of an array:
public class App {
public static void main(String[] args) {
double array[][] = {{1, 2, 3}, {3, 2, 1}, {1, 2, 3}};
int sum = 0, total = 0;
for(int outer_index = 0; outer_index < array.length; outer_index++){
for(int inner_index = 0; inner_index < array[outer_index].length; inner_index++) {
sum += array[outer_index][inner_index];
total++; } }
System.out.println("Average array value = " + (sum / total)); }
}
Heres the result of this code:
C:\>java App
Average array value = 2
So far, all the arrays we have used have had the same number of elements for each dimension, but you dont
need to set things up that way. To learn more, you can take a look at the topic after the next one. First lets look
at initializing multi-dimensional arrays.
Initializing Multi-Dimensional Arrays
You can initialize multi-dimensional arrays with data when declaring them in much the same way you initialize
one-dimensional arraysjust include a set of curly braces for each dimension and place the values with which you
want to initialize the array in those curly braces. For example, heres how to initialize a two-dimensional array:
public class App {
public static void main(String[] args) {
double accounts[][] = { {10.11, 19.56, 4343.91, 43.95},
{ 11.23, 54.23, 543.62, 2385489382.06 } };
System.out.println("Savings account 3 has $" + accounts[0][2]);
System.out.println("Checking account 3 has $" +
49
Chapter 2: Variables, Arrays, and Strings
accounts[1][2]); }
}
Heres what running this code yields:
C:\>java App
Savings account 3 has $4343.91
Checking account 3 has $543.62
Creating Irregular Multi-Dimensional Arrays
OK, says the Novice Programmer proudly. Now Im an array expert. Uh huh, you say. Can you give
each row in an array a different number of elements? The NP says, Excuse me?
As with many other programming languages, multi-dimensional arrays are actually arrays of arrays in Java. This
means you can construct arrays as you like, as in the below example, in which each row of a two-dimensional
array has a different number of elements:
public class App {
public static void main(String[] args) {
double array[][] = new double[5][];
array[0] = new double[500]; array[1] = new double[400];
array[2] = new double[300]; array[3] = new double[200];
array[4] = new double[100]; array[3][3] = 1335.67;
System.out.println("Account [0][400] has $" + array[0][400]);
System.out.println("Account [1][300] has $" + array[1][300]);
System.out.println("Account [2][200] has $" + array[2][200]);
System.out.println("Account [3][100] has $" + array[3][100]);
System.out.println("Account [4][50] has $" + array[4][50]);
System.out.println("Account [3][3] has $" + array[3][3]); }
}
Whats happening here is that we are treating each row of a two-dimensional array as a one-dimensional array
by itself and creating each of those one-dimensional arrays separately.
Each dimensional array defined in this program fetches the element according to the value of index taken
individually. Note here that the value of the array variable that is not defined is taking the default value; as in
this case, the default value of double is 0.0.
Heres the result of this code:
C:\>java App
Account [0][400] has $0.0
Account [1][300] has $0.0
Account [2][200] has $0.0
Account [3][100] has $0.0
Account [4][50] has $0.0
Account [3][3] has $1335.67
Now, lets fetch the value that exceeds the array index as shown in the following program:
public class App {
public static void main(String[] args) {
double array[][] = new double[5][];
array[0] = new double[500];
array[1] = new double[400];
array[2] = new double[300];
array[3] = new double[200];
array[4] = new double[100];
array[3][3] = 1335.67;
System.out.println("Account [0][500] has $" + array[0][500]);
System.out.println("Account [1][500] has $" + array[1][500]);
System.out.println("Account [2][400] has $" + array[2][400]);
System.out.println("Account [3][300] has $" + array[3][300]);
System.out.println("Account [4][200] has $" + array[4][200]);
System.out.println("Account [3][3] has $" + array[3][3]); }
}
50
Immediate Solutions
The preceding program gets compiled but running the code yields, is the exceptional handling error as follows:
C:\>java App
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 500
at App.main(App.java:10)
Getting an the Length of an Array
Its often useful to know the length of an array, especially if you are iterating over all elements in the array in
your code. To find the number of elements in an array named array1, you can use the term array1.length.
Heres an example from the next chapter that uses a for loop to find the average student grade from a set of six
grades (here, the term grades.length returns a value of 6):
public class App {
public static void main(String[] args) {
double grades[] = {88, 99, 73, 56, 87, 64};
double sum, average;
sum = 0;
for (int loop_index = 0; loop_index < grades.length; loop_index++) {
sum = sum + grades[loop_index]; }
average = sum / grades.length;
System.out.println("Average grade = " + average); }
}
Heres the result of this code:
C:\>java App
Average grade = 77.83333333333333
Understanding General Form of Static Import
To access static members, it is required to qualify references with the class they belong to. For example,
double calc = Math.cos(Math.PI * theta);
To understand this better, you sometimes add static members to an interface and inherit the same from that
interface. This is not advised though, because a class of the static members of another class you are using is just a
plain implementation detail. Whenever a class implements an interface, it becomes the part of the classs public
API, and implementation detail should not interfere with other public APIs.
The static import allows unqualified access to static members. You do not need to inherit from the type
containing static members. Alternatively, the program may import the members individually:
import static java.lang.Math.PI;
or collectively:
import static java.lang.Math.*;
The static members may be used without criterion, once imported:
double calc = cos(PI * theta);
The static import declaration mentioned previously and the normal import declaration are comparable.
You can use the static import instead of declaring local copies of constants, or utilizing inheritance (the
Constant Interface Antipattern). This means that the static import is used when we require frequent access to
static members from a couple of classes. However, excess use of this feature can make your program unreadable
and difficult to maintain, creating problems with the namespace of all the static members you import.
Importing Static Members
In a program, you can import the static members of a class by simply importing the named package of that class.
For example, in the Circumference class, you can use the constant PI defined in the Math class by using either
its fully qualified name Math.PI or simply PI if you import the PI member of the Math package:
double circumference_circle() { return 2 * Math.PI*radius; }
51
Chapter 2: Variables, Arrays, and Strings
This shows the need for the static member of the Circumference class with the name PI and would provide a
much more accurate definition of . The Math prefix to the name PI doesnt really add clarity to the code, and it
would be better without it.
We can avoid the prefixing of PI to the Math class name by importing the PI member name from
the Math class:
import static java.lang.Math.PI;
class Circumference {
. . .
double circumference_circle() { return 2*PI*radius; }
}
All the static members can also be imported by using the * notation. This import applies only to the classes
defined in a named package for the static members of a class. If you require importing the name of static member
of a class that you define, the definition of the class should be included in a named package. Names of static
members with no names in the default package cannot be imported. The class name in the static import
statement must always be qualified with its package name.
The String Class
I have been looking through the list of simple data types in Java, the Novice Programmer says, And I cant
find text strings there. Shouldnt they be there? Some people say so, you reply. Strings are handled as objects
in Java. One advantage of this is that a String object has a great variety of methods you can use with it.
In many languages, text strings are fundamental data types inherent to the specific language; but in Java, strings
are handled with the String and StringBuffer classes. Lets take a look at the String class first.
String objects hold text strings that you cant change; if you want to change the actual text in the string, you
should use the StringBuffer class instead. Heres an example in which we create a string and print it out
(notice how much this code makes the String class look like any other simple data type):
public class App {
public static void main(String[] args) {
String s1 = "Hello from Java!";
System.out.println(s1); }
}
Heres the result of this code:
C:\>java App
Hello from Java!
The String class is enormously powerful, with methods that enable you to convert the string into a character
array, convert numbers into strings, search strings, create substrings, change the case of the string, get a string
length, compare strings, and much more. The String class is obviously a class, not an intrinsic data type, which
means you create objects of that class with constructors, which youll learn all about in Chapter 4. A constructor is
just like a normal method of a class, except you use it to create an object of that class. Youll get a sneak peek at
the String class constructors here. The String class also has a data member you use when comparing strings
(which well take a look at in the next chapter). This data member is shown in Table 2.2. The String class
constructors, which you can use to create String objects (see the topic Creating Strings, coming up in this
chapter), appear in Table 2.3, and the methods of the String class appear in Table 2.4.
Well put the material you see in the tables below to use in the next few topics, in which well create and use
String objects.
Table 2.2: String class field summary
Field Does this
static Comparator<String> It yields a comparator (which youll see more about later) that orders
CASE_INSENSITIVE_ORDER String objects, as in compareToIgnoreCase
52
Immediate Solutions
Table 2.3: String class constructor summary
Constructor Does this
String() It initializes a new String object so that it holds an empty character
sequence
String(byte[] bytes) It constructs a new String object by converting the array of bytes by
using the platforms default character encoding
String(byte[] bytes, Charset It constructs a new String by decoding the specified array of bytes
charset) using the specified charset
String(byte[] ascii, int hibyte) It is deprecated because it did not properly convert bytes into characters
String(byte[] bytes, int offset, It constructs a new String object by converting the subarray of bytes
int length) using the default character encoding
String(byte[] bytes, int offset, It constructs a new String by decoding the specified subarray of bytes
int length, Charset charset) using the specified charset
String(byte[] ascii, int hibyte, It is deprecated because it did not properly convert bytes into characters
int offset, int count)
String(byte[] bytes, int offset, It constructs a new String object by converting the subarray of bytes
int length, String charsetName) using the specified charset
String(byte[] bytes, String It constructs a new String object by converting the array of bytes using
charsetName) the specified charset
String(char[] value) It allocates a new String object so that it represents the sequence of
characters contained in the character array argument
String(char[] value, int offset, It allocates a new String object that contains characters from a subarray
int count) of the character array argument
String(int[] codePoints, int It allocates a new String object that contains characters from a subarray
offset, int count) of the Unicode code point array argument
String(String original) It initializes a new String object so that it represents the same sequence
of characters as the argument string
String(StringBuffer buffer) It allocates a new String object that contains the sequence of characters
contained in the string buffer argument
String(StringBuilder builder) It allocates a new String object that contains the sequence of characters
contained in the string builder argument
Table 2.4: String class methods
Method Does this
char charAt(int index) It yields the character at the given index
int codePointAt It yields the character (Unicode code point) at the specified index
(int index)
int codePointBefore(int index) It yields the character (Unicode code point) before the specified index
int codePointCount(int It yields the number of Unicode code point in the specified range of this
beginIndex, int endIndex) string
int compareTo It compares two strings lexicographically
(String anotherString)
int compareToIgnoreCase It compares two strings lexicographically, ignoring case
(String str)
String concat(String str) It concatenates the given string to the end of this string
boolean contains(CharSequence s) It returns True if this string contains the specified sequence of char values
53
Chapter 2: Variables, Arrays, and Strings
Table 2.4: String class methods
Method Does this
boolean It compares this string to the specified CharSequence
contentEquals(CharSequence cs)
boolean It compares this string to the specified StringBuffer
contentEquals(StringBuffer sb)
static String copyValueOf It yields a String object thats equivalent to the given character array
(char[] data)
static String copyValueOf It yields a String object thats equivalent to the given character array by
(char[] data, int offset, int using offsets
count)
boolean endsWith It returns True if the string ends with the given suffix
(String suffix)
boolean equals It compares this string to an object
(Object anObject)
boolean equalsIgnoreCase It compares this String object to another String object, ignoring case
(String anotherString)
static String format(Locale l, It returns a formatted string using the given locale, format string, and
String format, Object...args) arguments
static String format(String It returns a formatted string using the given format string and arguments
format, Object...args)
byte[] getBytes() It converts this String object into bytes with the default charset, storing
the result in a new byte array
byte[] getBytes(Charset charset) It encodes this String into a byte sequence using the given charset, storing
the result in a new byte array
void getBytes It is deprecated because it did not properly convert characters into bytes
(int srcBegin,int srcEnd,
byte[] dst, int dstBegin)
byte[] getBytes It converts this String object into bytes with the given charset, storing
(String charsetName) the result in a new byte array
void getChars It copies characters from this string into the destination array
(int srcBegin, int srcEnd, char[]
dst, int dstBegin)
int hashCode() It yields a hash code for this string
int indexOf(int ch) It yields the index within this string of the first occurrence of the given
character
int indexOf(int ch, int It yields the index within this string of the first occurrence of the given
fromIndex) character, starting the search at the given index
int indexOf(String str) It yields the index within this string of the first occurrence of the given
substring
int indexOf(String str, int It yields the index within this string of the first occurrence of the given
fromIndex) substring, starting at the given index
String intern() It yields a representation for the String object
boolean isEmpty() It yields True if length of string is 0
int lastIndexOf(int ch) It yields the index within this string of the last occurrence of the given
character
int lastIndexOf(int ch, int It yields the index within this string of the last occurrence of the given
fromIndex) character, searching backward from the given index
int lastIndexOf(String str) It yields the index within this string of the rightmost occurrence of the
given substring
54
Immediate Solutions
Table 2.4: String class methods
Method Does this
int lastIndexOf It yields the index within this string of the last occurrence of the given
(String str,int fromIndex) substring, searching backward from the given index
int length() It yields the length of this string
boolean matches(String regex) It returns True if this string matches the given regular expression
int offsetByCodePoints(int index, It returns the index within this string which is offset from the given
int codePointOffset) index by codePointOffset code points
boolean regionMatches It tests whether two string regions are equal, allowing you to ignore case
(boolean ignoreCase, int toffset,
String other, int ooffset, int
len)
boolean regionMatches(int It tests whether two string regions are equal
toffset, String other, int
ooffset, int len)
String replace(char oldChar, char It yields a new string by replacing all occurrences of oldChar in this
newChar) string with newChar
String replace(CharSequence It yields a new string by replacing each substring of this string that
target, CharSequence replacement) matches the literal target sequence with the given literal replacement
sequence
String replaceAll(String regex, It yields a new string by replacing each substring of this string that
String replacement) matches the given regular expression with the given replacement
String replaceFirst(String regex, It yields a new string by replacing the first substring of this string that
String replacement) matches the given regular expression with the given replacement
String[] split(String regex) It splits this string around matches of the given regular expression
String[] split(String regex, int It splits this string around matches of the given regular expression and
limit) the limit given as parameter
boolean startsWith(String prefix) It tests whether this string starts with the given prefix
boolean startsWith(String prefix, It tests whether this string starts with the given prefix, beginning at the
int toffset) given index
CharSequence subSequence( int It returns a new character sequence, which is a subsequence of this
beginIndex, int endIndex) sequence
String substring It yields a new string, which is a substring of this string
(int beginIndex)
String substring(int beginIndex, It yields a new string, which is a substring of this string, allowing you to
int endIndex) specify the end index
char[] toCharArray() It converts this string to a new character array
String toLowerCase() It converts all the characters in this String object to lowercase by using
the rules of the default locale, which is returned by
Locale.getDefault() method
String toLowerCase It converts all the characters in this String object to lowercase using the
(Locale locale) rules of the given Locale
String toString() It returns the string object
String toUpperCase() It converts all the characters in this String object to uppercase using the
rules of the default locale, which is returned by Locale.getDefault()
method
String toUpperCase It converts all the characters in this String object to uppercase using the
(Locale locale) rules of the given locale
String trim() It removes white space from both ends of this string
55
Chapter 2: Variables, Arrays, and Strings
Table 2.4: String class methods
Method Does this
static String valueOf It yields the string representation of the boolean argument
(boolean b)
static String valueOf It yields the string representation of the char argument
(char c)
static String valueOf It yields the string representation of the char array argument
(char[] data)
static String valueOf It yields the string representation of a specific subarray of the char array
(char[ ] data, int offset, int argument
count)
static String valueOf(double d) It yields the string representation of a double type argument
static String valueOf(float f) It yields the string representation of a float type argument
static String valueOf It yields the string representation of an int type argument
(int i)
static String valueOf(long l) It yields the string representation of a long type argument
static String valueOf(Object obj) It yields the string representation of an Object type argument
Creating Strings
So Java includes a String class to handle text strings, the Novice Programmer says. Thats great, because
Im writing this novel, see, and. Hold it, you say. I dont want to hear about it.
Lets take a look at some of the many ways of creating String objects. Heres a way youve already seen:
public class App { public static void main(String[] args) {
String s1 = "Hello from Java!";
. . . }
}
In fact, when you use a string literal such as Hello from Java! in your code, Java treats it as a String object So
whats really happening here is that one String object is assigned to another.
Of course, you can also declare a string first and then assign a value to it:
public class App { public static void main(String[] args) {
String s1 = "Hello from Java!";
String s2;
s2 = "Hello from Java!";
. . . }
}
Heres a case in which we use one of the String class constructors. In this case, we are just creating an empty
string and then assigning data to it:
public class App {
public static void main(String[] args) {
String s1 = "Hello from Java!";
String s2;
s2 = "Hello from Java!";
String s3 = new String();
s3 = "Hello from Java!";
. . .}
}
You can also pass a text string to the String class constructor directly to create a new string, like this:
public class App {
public static void main(String[] args) {
String s1 = "Hello from Java!";
String s2;
s2 = "Hello from Java!";
56
Immediate Solutions
String s3 = new String();
s3 = "Hello from Java!";
String s4 = new String("Hello from Java!");
. . . }
}
Other String class constructors are available that can take character arrays or subsets of character arrays (the
String class knows which constructor you are using by the number and type of arguments you pass to it). You
can even use the String class valueOf method to get a string representation of numeric values:
public class App {
public static void main(String[] args) {
String s1 = "Hello from Java!";
String s2;
s2 = "Hello from Java!";
String s3 = new String();
s3 = "Hello from Java!";
String s4 = new String("Hello from Java!");
char c1[] = {'H', 'i', ' ', 't', 'h', 'e', 'r', 'e'};
String s5 = new String(c1);
String s6 = new String(c1, 0, 2);
String s7 = String.valueOf(c1);
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
System.out.println(s4);
System.out.println(s5);
System.out.println(s6);
System.out.println(s7); }
}
To convert a string into a number, you can use the numeric wrapper classes, such as Integer, Long, Float, and so on, using
methods such as Integer.parseInt() and Long.parseLong().
At the end of this code, we print out all the strings we have created. Heres what appears when the program
is run:
C:\>java App
Hello from Java!
Hello from Java!
Hello from Java!
Hello from Java!
Hi there
Hi
Hi there
Getting String Length
The Novice Programmer is breathless. I have written half my novel, the NP says, and I need to find out how
long it is so far. How can I do that? Use the String class length() method, you say.
Heres an example that shows how to use the String classs length() method (note that it also shows how
Java treats string literals as String objects by using length() method on a string literal):
public class App {
public static void main(String[] args) {
String s1 = "Hello from Java!";
System.out.println("\"" + s1 + "\"" + " is " + s1.length() + " characters long");
System.out.println("\"" + "Hello" + "\"" + " is " + "Hello".length() + " characters
long"); }
}
57
Chapter 2: Variables, Arrays, and Strings
Heres the output of this program:
C:\>java App
"Hello from Java!" is 16 characters long
"Hello" is 5 characters long
Concatenating Strings
Concatenating strings means joining them together, and we have already used the + operator in this book to do
just that. However, theres another way to concatenate stringsyou can use the String class concat()
method to join two strings and create a new one.
How does that look in code? Heres an example where we use both the + operator and the concat() method to
create the same string:
public class App {
public static void main(String[] args) {
String s1 = "Hello";
String s2 = s1 + " from";
String s3 = s2 + " Java!";
String s4 = s1.concat(" from");
String s5 = s4.concat(" Java!");
System.out.println(s3);
System.out.println(s5); }
}
Heres the result of the preceding code:
C:\>java App
Hello from Java!
Hello from Java!
As you have already seen when printing out numbers, when you concatenate a numeric value with a string, the
numeric value is concatenated as a string.
Note that concatenating numbers does indeed treat them as strings, so be carefulfor example, System.out.println (3 + 3 = +
3 + 3) displays 3 + 3 = 33, not 3 + 3 = 6.
Getting Characters and Substrings
The String class provides a number of methods that let you dissect strings into their component characters and
substrings. For example, you can use the charAt() method to get the character at a specific position:
public class App {
public static void main(String[] args) {
String s1 = "Hello from Java!";
char c1 = s1.charAt(0);
System.out.println("The first character of \"" + s1 + "\" is " + c1);
. . . }
}
You can use the toCharArray() method to convert a String object into a char array, and you can use the
getChars() method to get the number of characters:
public class App {
public static void main(String[] args) {
String s1 = "Hello from Java!";
char c1 = s1.charAt(0);
System.out.println("The first character of \"" + s1 + "\" is " + c1);
char chars1[] = s1.toCharArray();
System.out.println("The second character of \"" + s1 + "\" is " + chars1[1]);
char chars2[] = new char[5];
s1.getChars(0, 5, chars2, 0);
58
Immediate Solutions
System.out.println("The first five characters of \"" + s1 + "\" are " + new
String(chars2));
. . .
You can also use the substring() method to create a new string thats a substring of the old one, like this:
public class App {
public static void main(String[] args) {
String s1 = "Hello from Java!";
char c1 = s1.charAt(0);
System.out.println("The first character of \"" + s1 + "\" is " + c1); char chars1[] =
s1.toCharArray();
System.out.println("The second character of \"" + s1 + "\" is " + chars1[1]); char
chars2[] = new char[5];
s1.getChars(0, 5, chars2, 0);
System.out.println("The first five characters of \"" + s1 + "\" are " + new
String(chars2));
String s2 = s1.substring(0, 5);
System.out.println("The first five characters of \"" + s1 + "\" are " + s2); }
}
Heres the result of running this program:
C:\>java App
The first character of "Hello from Java!" is H
The second character of "Hello from Java!" is e
The first five characters of "Hello from Java!" are Hello
The first five characters of "Hello from Java!" are Hello
Searching For and Replacing Strings
You can search strings for characters and substrings by using the indexOf() and lastIndexOf() methods.
The indexOf() method returns the zero-based location of the first occurrence in a string of a character or
substring, and lastIndexOf() returns the location of the last occurrence of a character or substring.
Heres an example that shows how to use indexOf() and lastIndexOf() methods:
public class App {
public static void main(String[] args) {
String s1 = "We have drawn a nice drawing.;
System.out.println("The first occurrence of \"draw\" is " + "at location " +
s1.indexOf("draw"));
System.out.println("The last occurrence of \"draw\" is " + "at location " +
s1.lastIndexOf("draw"));
. . .
The String class also has a replace() method, which lets you replace all occurrences of a single character
with another single character. You might think this violates the idea that you cant change the text in a String
object; however, this method creates an entirely new String object. Heres an example showing how this
method works (note that we turn all occurrences of the letter h into the letter f in a text string):
public class App {
public static void main(String[] args) {
String s1 = "we have drawn a nice drawing";
System.out.println("The first occurrence of \"draw\" is " + "at location " +
s1.indexOf("draw"));
System.out.println("The last occurrence of \"draw\" is " + "at location " +
s1.lastIndexOf("draw"));
String s2 = "Edna, you\'re hired!";
System.out.println(s2.replace('h', 'f')); }
}
59
Chapter 2: Variables, Arrays, and Strings
Heres the result of this code:
C:\>java App
The first occurrence of "draw" is at location 8
The last occurrence of "draw" is at location 21
Edna, you're fired!
Changing Case in Strings
The Novice Programmer says, The Big Boss told me my programs output wasnt emphatic enough. Do you
have any ideas?, Try the toUpperCase() method, you say.
You can use the toLowerCase() method to convert a string into lowercase, and you can use the
toUpperCase() method to convert it into uppercase.
Heres how this looks in code:
public class App {
public static void main(String[] args) {
System.out.println("Hello from Java!".toLowerCase());
System.out.println("Hello from Java!".toUpperCase()); }
}
Heres the result of this program:
C:\>java App
hello from java!
HELLO FROM JAVA!
Checking for Empty String
Java SE 6 onwards, you can check for empty string by using a new method isEmpty() which has been
introduced in String class. The isEmpty() method returns true if and only if the length of string is 0. Heres
an example:
public class App {
public static void main(String[] args) {
String str="";
System.out.println("The string is Empty?-"+str.isEmpty()); }
}
Heres the result:
C:\>java App
The string is Empty?-true
Formatting Numbers in Strings
You can format numbers in strings by using the NumberFormat class of the java.text package. This class
supports the format(), setMinimumIntegerDigits(), setMinimumFractionDigits(),
setMaximumIntegerDigits(), and setMaximumFractionDigits() methods. Heres an example, using
the setMaximumFractionDigits() method, in which we round off a double value as we format it:
import java.text.*;
public class App {
public static void main(String[] args) {
double value = 1.23456789;
NumberFormat nf = NumberFormat.getNumberInstance();
nf.setMaximumFractionDigits(6);
String s = nf.format(value);
System.out.println(s); }
}
60
Immediate Solutions
Heres the result:
C:\>java App
1.234568
The StringBuffer Class
Hmm, says the Novice Programmer. I have stored my whole novel in a String object, but now I cant
change it. Whats wrong? You cant change the text in a String object, you say. You have to use a
StringBuffer object instead. Now you tell me, replies the NP.
The StringBuffer class gives you much of what the String class offersand something more: The ability to
modify the actual string. Heres an example that uses the StringBuffer class replace method to change the
contents of a StringBuffer object from Hello from Java! to Hello to Java!:
public class App {
public static void main(String[] args) {
StringBuffer s1 = new StringBuffer("Hello from Java!");
s1.replace(6, 10, "to");
System.out.println(s1); }
}
Heres the result of running this code:
C:\>java App
Hello to Java!
Youll find the StringBuffer class constructors in Table 2.5 and its methods in Table 2.6. Well put the
StringBuffer class to work in the next few topics.
Table 2.5: StringBuffer class constructors
Constructors Does this
StringBuffer() It constructs a string buffer with no characters in it and a capacity of 16
characters
StringBuffer(CharSequence seq) It constructs a string buffer that contains the same characters as the
specified CharSequence
StringBuffer(int capacity) It constructs a string buffer with no characters in it and the given capacity
StringBuffer(String str) It constructs a string buffer so that it represents the same sequence of
characters as the argument string
Table 2.6: StringBuffer class methods
Method Does this
StringBuffer append It appends the string representation of the boolean argument to the
(boolean b) sequence
StringBuffer append(char c) It appends the string representation of the char argument to the
sequence
StringBuffer append It appends the string representation of the char array argument to the
(char[] str) sequence
StringBuffer append(char[] str, int It appends the string representation of a subarray of the char array
offset, int len) argument to the sequence
StringBuffer append(CharSequence s) It appends the specified CharSequence to the sequence
StringBuffer append(CharSequence s, It appends a subsequence of the specified CharSequence to the sequence
int start, int end)
StringBuffer append It appends the string representation of the double argument to the
(double d) sequence
61
Chapter 2: Variables, Arrays, and Strings
Table 2.6: StringBuffer class methods
Method Does this
StringBuffer append(float f) It appends the string representation of the float argument to the
sequence
StringBuffer append(int i) It appends the string representation of the int argument to the sequence
StringBuffer append(long l) It appends the string representation of the long argument to the
sequence
StringBuffer append It appends the string representation of the Object argument to the
(Object obj) sequence
StringBuffer append It appends the string to this character sequence
(String str)
StringBuffer append It appends the given StringBuffer to the sequence
(StringBuffer sb)
String appendCodePoint(int It appends the string representation of the codePoint argument to the
codePoint) sequence
int capacity() It yields the current capacity of the string buffer
char charAt(int index) It yields the given character of the sequence represented by the string
buffer, as indicated by the index argument.
int codePointAt(int index) It yields the character (Unicode code point) at the specified index.
int codePointBefore(int index) It yields the character (Unicode code point) before the specified index.
int codePointCount(int beginIndex, It yields the number of Unicode code points in the range of given index
int endIndex) arguments.
StringBuffer delete(int start, int It removes characters in a substring of the sequence.
end)
StringBuffer deleteCharAt(int It removes the character at the given position in the sequence.
index)
void ensureCapacity(int It ensures that the capacity of the buffer is at least equal to the given
minimumCapacity) minimum.
void getChars(int srcBegin, int It copies characters from the sequence into the destination character array
srcEnd, char[] dst, int dstBegin) dst.
int indexOf(String str) It returns the index of first occurrence of the given substring.
int indexOf(String str, int It returns the index of first occurrence of the given substring, starting at
fromIndex) the given fromIndex.
StringBuffer insert(int offset, It inserts the string representation of the boolean argument into the
boolean b) sequence.
StringBuffer insert(int offset, It inserts the string representation of the char argument into the
char c) sequence.
StringBuffer insert(int offset, It inserts the string representation of the char array argument into the
char[] str) sequence.
StringBuffer insert(int index, It inserts the string representation of a subarray of the str array
char[] str, int offset, int len) argument into the sequence.
StringBuffer insert(int dstOffset, It inserts th