Java Programming/Print Version
Java Programming/Print Version
Java Programming/Print Version
Wikibooks.org
Contents
1 A BOUT T HIS B OOK 1.1 W HO S HOULD R EAD T HIS B OOK . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1.2 H OW THIS BOOK IS EVOLVING . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . H ISTORY 2.1 T HE G REEN TEAM . . . . . . . . . . . . . . . . 2.2 R ESHAPING THOUGHT . . . . . . . . . . . . . . 2.3 T HE DEMISE OF AN IDEA , BIRTH OF ANOTHER 2.4 R ECENT HISTORY . . . . . . . . . . . . . . . . . 2.5 V ERSIONS . . . . . . . . . . . . . . . . . . . . . 2.6 C ITATIONS . . . . . . . . . . . . . . . . . . . . . T HE J AVA P LATFORM 3.1 J AVA TECHNOLOGIES . . . . . . 3.2 J AVA RUNTIME E NVIRONMENT 3.3 L ANGUAGES . . . . . . . . . . . 3.4 S IMILAR P LATFORMS . . . . . . 1 1 2 3 4 5 7 8 8 11 13 13 14 15 15 17 17 19 20 25 25 26 26 27 27 27 28 29 29 29 29 30 30 31 31 31
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
J AVA P ROGRAMMING E NVIRONMENT 4.1 T HE J AVA C OMPILER . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4.2 T HE J AVA RUNTIME E NVIRONMENT . . . . . . . . . . . . . . . . . . . . . . . . . . . 4.3 OTHER JDK TOOLS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . I NSTALLATION 5.1 W INDOWS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5.2 U BUNTU L INUX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5.3 E XTERNAL L INKS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . C OMPILATION 6.1 C OMPILING TO BYTECODE . . . . . . . . . . . . . . . 6.2 AUTOMATIC C OMPILATION OF D EPENDENT C LASSES 6.3 PACKAGES , S UBDIRECTORIES , AND R ESOURCES . . . 6.4 F ILENAME C ASE . . . . . . . . . . . . . . . . . . . . . 6.5 C OMPILER O PTIONS . . . . . . . . . . . . . . . . . . . 6.6 A DDITIONAL T OOLS . . . . . . . . . . . . . . . . . . . 6.7 JB UILDER . . . . . . . . . . . . . . . . . . . . . . . . . 6.8 JC REATOR . . . . . . . . . . . . . . . . . . . . . . . . . 6.9 E CLIPSE . . . . . . . . . . . . . . . . . . . . . . . . . . 6.10 N ET B EANS . . . . . . . . . . . . . . . . . . . . . . . . 6.11 B LUE J . . . . . . . . . . . . . . . . . . . . . . . . . . . 6.12 K AWA . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
III
Contents
6.13 6.14 7
A NT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . T HE JIT COMPILER . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
31 32 33 33 36 41 43 43 44 45 45 47 47 48 56 57 58 59 60 60 61 61 63 63 63 64 64 64 65 67 67 67 71 74 75 75 75 76 77 78 79 79 80
E XECUTION 7.1 JSE CODE EXECUTION . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7.2 J2EE CODE EXECUTION . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7.3 J INI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . F IRST J AVA P ROGRAM 8.1 H ELLO W ORLD . . . . . . . 8.2 M ODIFYING THE P ROGRAM 8.3 C OMMON P ROBLEMS . . . 8.4 T HE N EXT S TEP . . . . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
U NDERSTANDING A J AVA P ROGRAM 9.1 T HE D ISTANCE C LASS : I NTENT, S OURCE , AND U SE . . . . . . . . . . . . . . . . . . 9.2 D ETAILED P ROGRAM S TRUCTURE AND O VERVIEW . . . . . . . . . . . . . . . . . . . 9.3 C OMMENTS IN J AVA PROGRAMS . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
10 S YNTAX 10.1 U NICODE . . . . . . . . 10.2 L ITERALS . . . . . . . . 10.3 B LOCKS . . . . . . . . . 10.4 W HITESPACES . . . . . . 10.5 R EQUIRED W HITESPACE 10.6 I NDENTATION . . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
11 S TATEMENTS 11.1 W HAT EXACTLY ARE STATEMENTS ? . . . . . . . . . . 11.2 W HERE DO YOU FIND STATEMENTS . . . . . . . . . . 11.3 VARIABLES . . . . . . . . . . . . . . . . . . . . . . . . 11.4 D ATA TYPES . . . . . . . . . . . . . . . . . . . . . . . 11.5 W HOLE NUMBERS AND FLOATING POINT NUMBERS 11.6 A SSIGNMENT STATEMENTS . . . . . . . . . . . . . . 11.7 P ROGRAM C ONTROL F LOW . . . . . . . . . . . . . . 11.8 S TATEMENT B LOCKS . . . . . . . . . . . . . . . . . . 11.9 B RANCHING S TATEMENTS . . . . . . . . . . . . . . . 11.10 I TERATION S TATEMENTS . . . . . . . . . . . . . . . . 11.11 T HE CONTINUE AND BREAK STATEMENTS . . . . . . 12 C LASSES , O BJECTS AND T YPES 12.1 O BJECTS AND C LASSES . . . . . . . . 12.2 I NSTANTIATION AND C ONSTRUCTORS 12.3 T YPE . . . . . . . . . . . . . . . . . . . 12.4 M ULTIPLE CLASSES IN A J AVA FILE . . 12.5 E XTERNAL LINKS . . . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
. . . . .
IV
Contents
13.3 13.4
80 81 83 83 84 84 87 87 89 89 89 91 92 93 93 95 96 97 99 101 101 102 102 104 104 105 106 107 107 108 109 110 111 112 112 113 113 113 113 114
14 N ESTED C LASSES 14.1 N EST A CLASS INSIDE A CLASS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14.2 N EST A CLASS INSIDE A METHOD . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14.3 A NONYMOUS C LASSES . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15 A CCESS M ODIFIERS 15.1 A CCESS MODIFIERS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16 M ETHODS 16.1 M ETHOD D EFINITION . . . . . . . . . . 16.2 M ETHOD O VERLOADING . . . . . . . . 16.3 M ETHOD O VERRIDING . . . . . . . . . 16.4 PARAMETER PASSING . . . . . . . . . . 16.5 F UNCTIONS . . . . . . . . . . . . . . . . 16.6 R ETURN PARAMETER . . . . . . . . . . . 16.7 S PECIAL METHOD, THE C ONSTRUCTOR 16.8 S TATIC M ETHOD . . . . . . . . . . . . . 16.9 E XTERNAL LINKS . . . . . . . . . . . . . 17 P RIMITIVE T YPES 18 T YPES 18.1 18.2 18.3 18.4 18.5 18.6 18.7 19
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
D ATA T YPES IN J AVA . . . . . . A BOUT J AVA T YPES . . . . . . . E XAMPLES OF T YPES . . . . . . A RRAY T YPES . . . . . . . . . . P RIMITIVE D ATA T YPES . . . . D ATA C ONVERSION (C ASTING ) AUTOBOXING / UNBOXING . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . U SING S TRING B UFFER /S TRING B UILDER TO CONCATENATE STRINGS C OMPARING S TRINGS . . . . . . . . . . . . . . . . . . . . . . . . . . . S PLITTING A S TRING . . . . . . . . . . . . . . . . . . . . . . . . . . . . C REATING SUBSTRINGS . . . . . . . . . . . . . . . . . . . . . . . . . . M ODIFYING S TRING CASES . . . . . . . . . . . . . . . . . . . . . . . . S EE ALSO . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
20 A RRAYS 20.1 I NTRO TO A RRAYS . . . . . . 20.2 A RRAY F UNDAMENTALS . . . 20.3 T WO -D IMENSIONAL A RRAYS 20.4 M ULTIDIMENSIONAL A RRAY
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
Contents
21.2 21.3
C ASE C ONVENTIONS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116 S COPE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116 119 119 120 121 122 123 124
22 G ENERICS 22.1 W HAT ARE G ENERICS ? . . . . . . 22.2 I NTRODUCTION . . . . . . . . . . 22.3 N OTE FOR C++ PROGRAMMERS . 22.4 C LASS <T> . . . . . . . . . . . . . 22.5 VARIABLE A RGUMENT . . . . . . 22.6 W ILDCARD T YPES . . . . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
23 D EFINING C LASSES 127 23.1 F UNDAMENTALS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127 24 C REATING O BJECTS 24.1 I NTRODUCTION . . . . . . . . . . . . . . . . . . . . . . . . 24.2 C REATING OBJECT WITH THE new KEYWORD . . . . . . . 24.3 C REATING OBJECT BY CLONING AN OBJECT . . . . . . . . 24.4 C REATING OBJECT RECEIVING FROM A REMOTE SOURCE 131 131 131 132 134
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
25 I NTERFACES 137 25.1 I NTERFACES . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137 25.2 E XTERNAL LINKS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138 26 U SING S TATIC M EMBERS 26.1 W HAT DOES STATIC MEAN ? . . 26.2 W HAT CAN IT BE USED FOR ? . 26.3 D ANGER OF STATIC VARIABLES 26.4 E XTERNAL LINKS . . . . . . . . 139 139 139 140 140
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
27 D ESTROYING O BJECTS 141 27.1 FINALIZE () . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141 28 OVERLOADING M ETHODS AND C ONSTRUCTORS 29 A RRAYS 29.1 I NTRO TO A RRAYS . . . . . . 29.2 A RRAY F UNDAMENTALS . . . 29.3 T WO -D IMENSIONAL A RRAYS 29.4 M ULTIDIMENSIONAL A RRAY 143 145 145 145 145 146 147 147 148 149 152 159 161 161 163
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
30 C OLLECTION C LASSES 30.1 I NTRODUCTION TO C OLLECTIONS 30.2 G ENERICS . . . . . . . . . . . . . . 30.3 C OLLECTION OR M AP . . . . . . . 30.4 S ET OR L IST OR QUEUE . . . . . . 30.5 M AP C LASSES . . . . . . . . . . . . 30.6 T HREAD S AFE C OLLECTIONS . . . 30.7 C LASSES D IAGRAM (UML) . . . . 30.8 E XTERNAL LINKS . . . . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
VI
Contents
31 T HROWING AND C ATCHING E XCEPTIONS 31.1 C ATCHING M ATCHING RULES . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31.2 E XAMPLE OF HANDLING EXCEPTIONS . . . . . . . . . . . . . . . . . . . . . . . . . . 31.3 A PPLICATION E XCEPTIONS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31.4 RUNTIME E XCEPTIONS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31.5 M AIN E XCEPTION C LASSES . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31.6 S EE A LSO . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31.7 M INIMIZE THE USE OF THE KEYWORD NULL IN ASSIGNMENT STATEMENTS . . . . 31.8 M INIMIZE THE USE OF THE NEW T YPE [ INT ] SYNTAX FOR CREATING ARRAYS OF OB JECTS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31.9 C HECK ALL REFERENCES OBTAINED FROM UNTRUSTED METHODS . . . . . . . . . 31.10 C OMPARING STRING VARIABLE WITH A STRING LITERAL . . . . . . . . . . . . . . . . 31.11 S EE ALSO . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
165 165 169 170 171 172 174 174 175 175 175 176
32 L INKS 177 32.1 E XTERNAL R EFERENCES . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177 32.2 E XTERNAL LINKS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177 33 L ICENSE 34 GNU F REE D OCUMENTATION L ICENSE 35 AUTHORS L IST OF F IGURES 181 183 185 191
VII
Contents
VIII
Also there are many good commercial books that can be used to learn Java (see the external links). This book does not intend to replace them. Rather this book can be used to supplement them, during the learning of Java. It always helps the learning process to hear the same information in different ways, and this book represents one of the ways. And when the Java language is mastered, this book can be used as a reference. When you want to look something up quickly, instead of searching in a printed book, you can look it up in this book. This book can also be used by advanced Java programmers either by contributing or using this book as a reference. Also there is an Advanced Topics section for advanced Java programmers.
1 2 3 4
H T T P :// E N . W I K I B O O K S . O R G / W I K I /O B J E C T %20O R I E N T E D %20P R O G R A M M I N G H T T P :// E N . W I K I B O O K S . O R G / W I K I /M A I N %20P A G E H T T P :// E N . W I K I B O O K S . O R G / W I K I /S U B J E C T %3AC O M P U T E R %20 P R O G R A M M I N G %20 C O N C E P T S H T T P :// E N . W I K I B O O K S . O R G / W I K I /O B J E C T %20O R I E N T E D %20P R O G R A M M I N G
2 History
On 23 M AY1 19952 , J OHN G AGE3 , the director of the Science Ofce of the S UN M ICROSYS TEMS 4 along with M ARC A NDREESEN 5 , co-founder and executive vice president at N ETSCAPE 6 announced to an audience of SunWorldTM that Java technology wasnt a myth and that it was a reality and that it was going to be incorporated into N ETSCAPE N AVIGATOR7 .8 At the time the total number of people working on Java were less than 30 people.<ref name="CITEREFEarlyYearsSun1"/> This team would shape the future in the next decade and no one had any idea as to what was in store. From being the mind of an unmanned vehicle on M ARS9 to the operating environment on most of the consumer electronics, e.g., cable set-top boxes,VCRs, toasters, and also for PERSONAL DATA ASSISTANTS10 (PDAs).11 Java has come a long way from its inception. Lets see how it all began.
1 2 3 4 5 6 7 8
H T T P :// E N . W I K I P E D I A . O R G / W I K I /23%20M A Y H T T P :// E N . W I K I P E D I A . O R G / W I K I /1995 H T T P :// E N . W I K I P E D I A . O R G / W I K I /J O H N %20G A G E H T T P :// E N . W I K I P E D I A . O R G / W I K I /S U N %20M I C R O S Y S T E M S H T T P :// E N . W I K I P E D I A . O R G / W I K I /M A R C %20A N D R E E S E N H T T P :// E N . W I K I P E D I A . O R G / W I K I /N E T S C A P E H T T P :// E N . W I K I P E D I A . O R G / W I K I /N E T S C A P E %20N A V I G A T O R
History
Figure 1: James Gosling, architect and designer of the compiler for the Java technology
Behind closed doors, a project was initiated in December of 199012 , whose aim was to create a programming tool that could render obsolete the C and C++ programming languages. Engineer Patrick Naughton had become extremely frustrated with the state of Suns C++ and C APIs (application programming interfaces) and tools. While he was considering to move towards N E XT13 , he was offered a chance to work on new technology and the "Stealth Project" was started, a secret nobody but he knew. This Stealth Project was later named the "Green Project" when J AMES G OSLING14 and M IKE S HERIDAN15 joined Patrick.<ref name="CITEREFEarlyYearsSun1"/> Over the period of time that the Green Project teethed, the prospects of the project started becoming clearer to the engineers working on it. No longer was its aim to create a new language far superior to the present ones, but it aimed to target the language to devices other than the computer. Staffed at 13 people, they began work in a small ofce on S AND H ILL R OAD16 in M ENLO PARK , C ALIFORNIA17 . This team would be called "Green Team" henceforth in time. The project they underwent was chartered by Sun Microsystems to anticipate and plan for the "next-wave" in computing. For the team, this meant at least one signicant trend, that of the convergence of digitally controlled consumer devices and computers.<ref name="CITEREFEarlyYearsSun1"/>
12 13 14 15 16 17
H T T P :// E N . W I K I P E D I A . O R G / W I K I /1990 H T T P :// E N . W I K I P E D I A . O R G / W I K I /N E XT H T T P :// E N . W I K I P E D I A . O R G / W I K I /J A M E S %20G O S L I N G H T T P :// E N . W I K I P E D I A . O R G / W I K I /M I K E %20S H E R I D A N H T T P :// E N . W I K I P E D I A . O R G / W I K I /S A N D %20H I L L %20R O A D H T T P :// E N . W I K I P E D I A . O R G / W I K I /M E N L O %20P A R K %2C%20C A L I F O R N I A
Reshaping thought
Yes
John Gage
J AMES G OSLING20
Yes
Yes
Yes
FirstPerson employee and member of the Java Products Group Science Ofce (Director), Sun Microsystems Lead engineer and key architect of the Java technology
18 19 20
History
GT FP Table 1: Whos who of the Java technology<ref name="CITEREFEarlyYearsSun1"/> Has worked for GT (Green Team), FP (FirstPerson) and JP (Java Products Group) Name Bill Joy
JP
Details
Jonni Kanerva
Yes
Tim Lindholm
Yes
Yes
Scott McNealy
Patrick Naughton
Yes
Yes
George Paolini
Kim Polese
Yes
Co-founder and VP, Sun Microsystems; Principal designer of the UC Berkeley, version of the UNIX® OS Java Products Group employee, author of The Java FAQ1 FirstPerson employee and member Java Products Group Chairman, President, and CEO of Sun Microsystems Green Team member, FirstPerson cofounder Corporate Marketing (Director), Suns Java Software Division FirstPerson product marketing
GT FP Table 1: Whos who of the Java technology<ref name="CITEREFEarlyYearsSun1"/> Has worked for GT (Green Team), FP (FirstPerson) and JP (Java Products Group) Name Lisa Poulson
JP
Details
Yes
Mike Sheridan
Yes
Original director of public relations for Java technology (BursonMarsteller) FirstPerson President Former Sun Microsystems Chief Technology Ofcer Green Team member
History
Finally at the SunWorldTM conference, Andreesen unveiled the new technology to the masses. Riding along with the explosion of interest and publicity in the Internet, Java quickly received widespread recognition and expectations grew for it to become the dominant software for browser and consumer applications.<ref name="CITEREFClarkLindseyHistory1"/>
2.5 Versions
Unlike C and C++, Javas growth is pretty recent. Here, wed quickly go through the development paths that Java took with age.
Figure 2: Development of Java over the years. From version 1.0 to version 1.7, Java has displayed a steady growth.
25 26 27 28 29
H T T P :// E N . W I K I P E D I A . O R G / W I K I /GNU%20G E N E R A L %20P U B L I C %20L I C E N S E H T T P :// E N . W I K I P E D I A . O R G / W I K I /S O L A R I S %20O P E R A T I N G %20E N V I R O N M E N T H T T P :// E N . W I K I P E D I A . O R G / W I K I /M I C R O S O F T %20W I N D O W S H T T P :// E N . W I K I P E D I A . O R G / W I K I /M A C %20OS H T T P :// E N . W I K I P E D I A . O R G / W I K I /L I N U X
Versions
30 31
History
JVM Improvements - Most of the run time library is now mapped into memory as a memory image, as opposed to being loaded from a series of class les. Large portion of the runtime libraries will now be shared among multiple JVM instances. (from HTTP :// JAVA . SUN . COM / FEATURES /2003/05/ BLOCH _ QA . HTML33 )
33 34
H T T P :// J A V A . S U N . C O M / F E A T U R E S /2003/05/ B L O C H _ Q A . H T M L
10
Citations
Desktop Deployment - At long last, Java SE 6 unies the Java Plug-in technology and Java WebStart engines, which just makes sense. Installation of the Java WebStart application got a much needed makeover. Security - Java SE 6 has simplied the job of its security administrators by providing various new ways to access platform-native security services, such as native Public Key Infrastructure (PKI) and cryptographic services on Microsoft Windows for secure authentication and communication, Java Generic Security Services (Java GSS) and Kerberos services for authentication, and access to LDAP servers for authenticating users. The -lities: Quality, Compatibility, Stability - Bug xes ...
2.6 Citations
C ATEGORY:J AVA P ROGRAMMING35
35
11
History
12
3 4 5 6 7 8 9 10 11 12 13 14
H T T P :// E N . W I K I P E D I A . O R G / W I K I / P L A T F O R M %20%28 C O M P U T I N G %29 H T T P :// E N . W I K I P E D I A . O R G / W I K I /S U N %20M I C R O S Y S T E M S H T T P :// E N . W I K I P E D I A . O R G / W I K I /J A V A %20 P R O G R A M M I N G %20 L A N G U A G E H T T P :// E N . W I K I P E D I A . O R G / W I K I / V I R T U A L %20 M A C H I N E H T T P :// J A V A . S U N . C O M / D E V E L O P E R / T E C H N I C A L A R T I C L E S / J A V A O N E 2005/ N A M I N G . H T M L H T T P :// E N . W I K I P E D I A . O R G / W I K I /J2SE H T T P :// E N . W I K I P E D I A . O R G / W I K I /E N T E R P R I S E H T T P :// E N . W I K I P E D I A . O R G / W I K I /J2EE H T T P :// E N . W I K I P E D I A . O R G / W I K I /J2ME H T T P :// J A V A . S U N . C O M / J 2 S E /1.5.0/ D O C S / I N D E X . H T M L H T T P :// E N . W I K I P E D I A . O R G / W I K I /J A V A %20 V I R T U A L %20 M A C H I N E H T T P :// E N . W I K I P E D I A . O R G / W I K I /J A V A %20D E V E L O P M E N T %20K I T
13
15 16 17 18 19 20
H T T P :// E N . W I K I P E D I A . O R G / W I K I /J A V A %20 B Y T E C O D E H T T P :// E N . W I K I P E D I A . O R G / W I K I / I N T E R P R E T E R %20%28 C O M P U T I N G %29 H T T P :// E N . W I K I P E D I A . O R G / W I K I /J A V A %20 V I R T U A L %20 M A C H I N E H T T P :// E N . W I K I P E D I A . O R G / W I K I / J U S T - I N - T I M E %20 C O M P I L A T I O N H T T P :// E N . W I K I P E D I A . O R G / W I K I / E M U L A T O R S H T T P :// E N . W I K I P E D I A . O R G / W I K I /L I B R A R Y %20%28 C O M P U T E R %20 S C I E N C E %29%23D Y N A M I C % 20 L I N K I N G
14
Languages
that applications can call at runtime. Because the Java platform is not dependent on any specic operating system, applications cannot rely on any of the existing libraries. Instead, the Java platform provides a comprehensive set of standard class libraries, containing much of the same reusable functions commonly found in modern operating systems. The Java class libraries serve three purposes within the Java platform. Like other standard code libraries, they provide the programmer with a well-known set of functions to perform common tasks, such as maintaining lists of items or performing complex string parsing. In addition, the class libraries provide an abstract interface to tasks that would normally depend heavily on the hardware and operating system. Tasks such as network access and le access are often heavily dependent on the native capabilities of the platform. The Java java.net and java.io libraries implement the required native code internally, then provide a standard interface for the Java applications to perform those tasks. Finally, some underlying platforms may not support all of the features a Java application expects. In these cases, the class libraries can either emulate those features using whatever is available, or provide a consistent way to check for the presence of a specic feature.
3.3 Languages
The word Java, by itself, usually refers to the Java programming language which was designed for use with the Java platform. Programming languages are typically outside of the scope of the phrase "platform". However, Sun does not encourage the use of any other languages with the platform, and lists the Java programming language as a core part of the Java 2 platform. The language and runtime are therefore commonly considered a single unit. Nevertheless, third parties have produced a number of compilers which target the JVM. Some of these are for existing languages, while others are for extensions to the Java language itself. These include: G ROOVY21 P IZZA22 GJ23 (Generic Java), which was incorporated into ofcial Java as of Suns version 1.5. N ET REXX24
15
the concepts and innovations of Java; in fact, it has an implementation of a Java-like language called V ISUAL J#28 (formerly known as J++29 ). (It is Java-like in that J# is not the Java language. Instead, J# contains non-standard extensions of the language.) Later Microsoft stopped, withdrew its J# support, and created a new language called C#. C# is very similar to J# and Java, but not compatible with them. The differences between Java and C# can be read at C OMPARISON OF C S HARP AND J AVA30 . C ATEGORY:J AVA P ROGRAMMING31
28 29 30 31
H T T P :// E N . W I K I P E D I A . O R G / W I K I /J%20S H A R P %20 P R O G R A M M I N G %20 L A N G U A G E H T T P :// E N . W I K I P E D I A . O R G / W I K I /J%20 P L U S %20 P L U S H T T P :// E N . W I K I P E D I A . O R G / W I K I /C O M P A R I S O N %20 O F %20C%20S H A R P %20 A N D %20J A V A H T T P :// E N . W I K I B O O K S . O R G / W I K I /C A T E G O R Y %3AJ A V A %20P R O G R A M M I N G
16
javac compiles Java source les into executable Java class les. Source les are text les with a .java le name extension. You can create such les with a text editor, like N OTEPAD4 , or an IDE. javac then compiles these les into loadable and executable class les, using the .class extension. For example, if you create a Java class org/wikibooks/util/PrintDate.java
package org.wikibooks.util; import java.util.Date; public class PrintDate { public static void main(String[] args) { System.out.println(new Date()); } }
1 2 3 4
17
javac org/wikibooks/util/PrintDate.java
You would normally invoke this in a shell whose working directory is the root directory containing all of your source les resides. (The Java package statement, package org.wikibooks.util, corresponds to the directory structure org/wikibooks/util see J AVA PACKAGES5 .)
javac will create the le PrintDate.class in the same directory where the source le is located. If there are syntax errors, javac will print those to the shell. The PrintDate.class le contains
the byte code, that will run under all hardware where the Java runtime is installed. Even if the PrintDate.class le was created in Windows operating system, you can copy this le to unix and it will be executed ne. Usually there is more than one class le created and those les are packaged to a application_-
5 6 7
Chapter 13 on page 79
H T T P :// E N . W I K I P E D I A . O R G / W I K I /B Y T E C O D E H T T P :// E N . W I K I P E D I A . O R G / W I K I /X86%20 A R C H I T E C T U R E
18
The class is hence said to have a main entry point dened and is usually called a Java program. The method described above as the main entry point is usually nicknamed the main method. Java classes without main methods are simply classes, although they may be part of a program. Each Java class can have a main method, as opposed to C, and C++ where there can only be one, for the whole program. This feature is good in a sense that the main method can be implemented to do some testing on the class. The program must dene one classs main method as the entry point for the program.
This will run the main method in the PrintDate class in the org.wikibooks.util package. (Packages provide a convenient way to provide NAMESPACES10 and organization of Java classes. Well use org.wikibooks.util as a parent package in this module. M ORE ON PACKAGES11 .) Your program will begin execution in the shell window. Inputs and outputs will be gathered from and to your shell window. On a Windows platform, you can use a DOS12 command window as
8 9 10 11 12
H T T P :// E N . W I K I B O O K S . O R G / W I K I /J A V A %20P R O G R A M M I N G %2FJ A V A %20F O U N D A T I O N S % 23O B J E C T S %20 A N D %20C L A S S E S H T T P :// E N . W I K I B O O K S . O R G / W I K I /J A V A %20P R O G R A M M I N G %2FJ A V A %20F O U N D A T I O N S % 23M E T H O D S
19
the command shell program for the execution of Java programs. The JRE is normally called java because the java program is the most widely used program to execute Java programs.
Rather than executing in the console, the Java program would be executed in a separate Windows native process. This is typically done for Java applications which create their own graphical user interface (GUI) windows. The above-mentioned org.wikibooks.util.PrintDate program, which prints output to the standard output stream, is not appropriate for use with javaw as there is no console output. Instead, org.wikibooks.util.ViewDate would be a program which creates its own windows to display the date. As with java, IDEs also manage the execution of Java programs in slightly different ways. They may provide shortcuts for running programs and windows for capturing the output. On UNIX/Linux this does not matter. If the program is launched graphically (by le association in a le manager) a console is not shown. GUI programs will have the titlebars following the look and feel of your desktop (KDE, GNOME, Fluxbox, XFCE) theme.
20
The most difcult thing with apt is that Sun decided to use a whole set of new terminology. apt can simply be seen as a source code preprocessor framework, and annotation processors are typically just code generators. See also: G ETTING S TARTED WITH THE A NNOTATION P ROCESSING T OOL ( APT )13
13
H T T P :// J A V A . S U N . C O M / J 2 S E /1.5.0/ D O C S / G U I D E / A P T /G E T T I N G S T A R T E D . H T M L
21
4.3.7 RMI Tools 4.3.8 Java IDL and RMI-IIOP Tools 4.3.9 Deployment & Web Start Tools 4.3.10 Browser Plug-In Tools 4.3.11 Monitoring and Management Tools / Troubleshooting Tools
With Java 1.5 a set of monitoring and management tools have been added to the JDK, in addition to a set of troubleshooting tools. The monitoring and management tools are intended for monitoring and managing the virtual machine and the execution environment. They allow, for example, monitoring memory usage during the execution of a Java program. The troubleshooting tools provide rather esoteric insight into aspects of the virtual machine. (Interestingly, the Java debugger is not categorized as a troubleshooting tool.) All the monitoring and management and troubleshooting tools are currently marked as "experimental" (which does not affect jdb). So they might disappear in future JDKs.
22
those classes may require (such as text les, conguration les, images) at runtime. Internally, a jar le is really a .zip FILE14 .
for all the tools that are bundled with Suns JDK.
14 15 16 17 18 19 20
H T T P :// E N . W I K I P E D I A . O R G / W I K I /ZIP%20%28 F I L E %20 F O R M A T %29 H T T P :// E N . W I K I P E D I A . O R G / W I K I /D E B U G G I N G H T T P :// E N . W I K I B O O K S . O R G / W I K I /P R O G R A M M I N G %3AJ A V A %3AD E B U G G I N G %20 I N %20J A V A H T T P :// E N . W I K I B O O K S . O R G / W I K I /P R O G R A M M I N G %3AJ A V A _C O M M E N T S H T T P :// E N . W I K I P E D I A . O R G / W I K I /A P P L I C A T I O N %20 P R O G R A M M I N G %20 I N T E R F A C E H T T P :// J A V A . S U N . C O M / J 2 S E /1.5.0/ D O C S / T O O L D O C S / I N D E X . H T M L H T T P :// E N . W I K I B O O K S . O R G / W I K I /C A T E G O R Y %3AJ A V A %20P R O G R A M M I N G
23
24
5 Installation
To formally begin programming in Java, you would need to obtain the Java software necessary and install it on your system. This section will help you set up any system with the latest Java software. There are two things you need to have on your computer to develop Java programs: a way to make the programs, and a way to write those programs. The following sections will describe both.
5.1 Windows
5.1.1 Download/Install
Downloading the program involves navigating to the website HTTP :// JAVA . SUN . COM / JAVASE / DOWNLOADS / INDEX . JSP 1 . Here you are presented by a wide array of choices. Dont fret. For the moment, all you need is the JDK, so click on the red button with "Download JDK" inside. If you want to add something like Netbeans to your system, its easy enough to do that at a later period. Once downloaded, go through the install process, reading and agreeing to the terms and conditions. I recommend you keep everything at their default settings to keep things simple.
5.1.2 Editor
With your system set up youll want a method of writing your java les. Later on, you might want to think about getting an IDE such as Netbeans. IDEs make it convenient if you work as part of a large team in an industrial environment. They do a lot of work for you, but if you dont fully understand the Java code itself, an IDE can do more harm than good. So its recommended for the starting chapter that you use a text editor. You can use notepad, which is default on all Windows operating systems. However, there is a free and open source program called Notepad++, which you can download from HTTP :// NOTEPAD PLUS . SOURCEFORGE . NET 2 . This program is designed to be used as a programmers notepad, with whats called syntax highlighting, which is a way of colouring text based on various keywords. This makes the code more readable, and it can be easier to spot errors in code.
1 2
H T T P :// J A V A . S U N . C O M / J A V A S E / D O W N L O A D S / I N D E X . J S P H T T P :// N O T E P A D - P L U S . S O U R C E F O R G E . N E T
25
Installation
5.2.2 Editor
Gedit is the default program provided when Ubuntu is installed. Think of it like the windows notepad, but much better. Because Linux is made by hackers and programmers, the default notepad provided has all the things youd expect a programmers writer to have. The Notepad++ equivalent for Linux is Scite, if you feel like installing it you can use the command:
3 4 5
26
6 Compilation
We have already discussed COMPILATION BASICS 1 . Heres a recap of the concepts wed seen earlier and some additional details.
1 2 3 4
Chapter 4 on page 17
H T T P :// E N . W I K I P E D I A . O R G / W I K I /B Y T E C O D E
27
Compilation
automatically compiled.
javac ... MainClass.java
However, you cant rely on this feature if your program is using reection to create objects, or you are compiling for servlets or a "jar" package. In these cases you should list these classes for explicit compilation.
javac ... MainClass.java, ServletOne.java, ...
The best way is to use a build tool to build your application. The build tool would check all the needed dependencies and compile only the needed class for the build. The A NT5 tool is the best and the most popular build tool currently available. Using A NT6 you would build your application from the command line by typing:
ant build.xml
The xml le contains all the information needed to build the application. Note: In rare cases, your code may appear to compile correctly but the program behaves as if you were using an old copy of the source code (or otherwise reports errors during runtime.) When this occurrs, you may need to clean your compilation folder by either deleting the class les or using the Clean command from the IDE. The next most popular way to build applications are using an IDE. IDE stands for Integrated Development Environment, examples of which are listed below.
5 6 7
28
Filename Case
Example: Top level package. A class with this package declaration package example; has to be in a directory named example
Example: Subpackages. A class with this package declaration package org.wikibooks.en; has to be in the org/wikibooks/en directory. Java programs often contain non-code les such as images and properties les. These are referred to generally as resources and stored in directories local to the classes in which theyre used. For example, if the class com.example.ExampleApp uses the icon.png le, this le could be stored as /com/example/resources/icon.png. These resources present a problem when a program is complied, because javac does not copy them to wherever the .class les are being complied to (see above); it is up to the programmer to move the resource les and directories. See also the section on how to automate this using ant8 , below.
6.7 JBuilder
JBuilder is a IDE with proprietary source code, sold by B ORLAND9 . One of the advantages in integration with together, a modeling tool.
8 9 Chapter 6.13 on page 31
H T T P :// E N . W I K I B O O K S . O R G / W I K I /B O R L A N D
29
Compilation
6.8 JCreator
Theres info at: http://www.apcomputerscience.com/ide/jcreator/index.htm
6.9 Eclipse
Eclipse is a free IDE, plus a developer tool framework that can be extended for a particular development need. IBM was behind this free software development and it replaced IBM Visual Age tool. The idea was to create a standard look and feel that can be extended. The extendibility has distinguished Eclipse from other IDE tools. Eclipse also meant to compete with Microsoft Visual Studio tools. Microsoft tools give a standard way of developing code in the Microsoft world. Eclipse gives a similar standard way of developing code in the Java world, with big success so far. With the online error checking only, coding can be speed up by at least 50%(coding does not include programming). The goal for Eclipse are twofold: Give a standard IDE for developing code Give a starting point, and the same look and feel for all other more sophisticated tools built on Eclipse IBMs WSAD, and later IBM Rational Software Development Platform are built on Eclipse. Standard Eclipse features: Standard window management (perspectives, views, browsers, explorers, ...) As you type error checking (immediate error indications, ...) As you type help window (type ., or <ctrl> space, ...) Automatic build (changed source code automatically compiled, ...) Built in debugger (full featured GUI debugger) Source code generation (getters and setters, ...) Searches (for implementation, for references, ...) Code refactoring (global reference update, ...) Plug-in-based architecture (be able to build tools that integrate seamlessly with the environment and other tools) ... For more information see; E CLIPSE 10 . P LUGINCENTRAL11
10 11
H T T P :// W W W . E C L I P S E . O R G / H T T P :// W W W . E C L I P S E P L U G I N C E N T R A L . C O M /
30
NetBeans
6.10 NetBeans
The NetBeans IDE is a free, open-source Integrated Development Environment for software developers. The IDE runs on many platforms including Windows, Linux, Solaris, and the MacOS. It is easy to install and use straight out of the box. The NetBeans IDE provides developers with all the tools they need to create professional cross-platform desktop, enterprise, web and mobile applications. More info can be found at http://www.netbeans.org/products/ide/
6.11 BlueJ
BlueJ is an IDE that includes templates and will compile and run the applications for you. BlueJ is often used by classes because it is not necessary to set classpaths. BlueJ has its own sets of Librarys and you can add your own under preferences. That sets the classpath for all compilations that come out of it to include those you have added and the BlueJ libraries. BlueJ offers an interesting GUI for the creation of packages and programs. Classes are represented as boxes with arrows running between them to represent inheritance/implementation or if one is constructed in another. BlueJ adds all those classes (the project) into the classpath at compile time. B LUE J H OMESITE12
6.12 Kawa
Kawa was developed by Tek-Tools. It is basically a Java editor which does not include wizards, and GUI tools. It is best suited to experienced Java programmers in small and midsized development teams. The latest version is 4.0, you can See a JAVAWORLD ARTICLE15
DOWNLOAD IT. 13
6.13 Ant
For comprehensive information about all aspects of Ant, please see the A NT W IKIBOOK16 .
12 13 14 15 16
31
Compilation
Ant is a build management tool designed to replace make as the tool for automated builds of large Java applications. Like Java, and unlike make, Ant is designed to be platform independent. Building a Java application requires certain tasks to be performed. Those tasks may include not only compiling the code, but also copying les, packaging the program into a jar le, running tests and so on. Some of these tasks may depend upon others having been done previously (not creating a jar unless the program has been complied, for instance). It might also be a good idea to not execute all tasks every time the program is complied -- e.g. to only compile changed source les. Ant makes all of these things easy. The tasks and their dependencies are dened in a build.xml le, generally kept in the root directory of the java project. Ant parses this le and executes the tasks therein. Below we give an example build.xml le. Ant tool is written in Java and is open source, so it can be extended if there is a task youd like to be done during the build that is not in the pre-dened tasks list. It is very easy to hook your ant task code to the other tasks: your code only needs to be in the classpath, and the Ant tool will load it at runtime. For more information about writing your own Ant tasks, please see the project website at http://ant.apache.org/. UNKNOWN TEMPLATE "code"
32
7 Execution
There are various ways in which Java code can be executed. A complex Java application usually uses third party APIs or services. In this section we list the most popular ways a piece of Java code may be packed together and/or executed.
../tmp/3.jpg
33
Execution
Stand alone Java application : (Figure 1) Stand alone application refers to a Java program where both the user interface and business modules are running on the same computer. The application may or may not use a database to persist data. The user interface could be either AWT or Swing. The application would start with a main() method of a Class. The application stops when the main() method exits, or if an exception is thrown from the application to the JVM. Classes are loaded to memory and compiled as needed, either from the le system or from a *.jar le, by the JVM. Invocation of Java programs distributed in this manner requires usage of the command line. Once the user has all the class les, he needs to launch the application by the following command line (where Main is the name of the class containing the main() method.)
java Main
Java jar class libraries : Utility classes, framework classes, and/or third party classes are usually packaged and distributed in Java *.jar les. These jar les need to be put in the CLASSPATH of the java program from which these classes are going to be used. If a jar le is executable, it can be run from the command line:
java -jar Application.jar
../tmp/4.jpg
34
JSE code execution Java Applet code : (Figure 2) Java Applets are Java code referenced from HTML2 pages, by the <APPLET> tag. The Java code is downloaded from a server and runs in the client browser JVM. Java has built-in support to render applets in the browser window. Sophisticated GUI clients were found hard to develop, mostly because of the download time, incompatibilities between browsers JVM, and its communication requirements back to the server. Applets are rarely used today, and are most commonly used as small, separate graphic-like animation applets. The popularity of Java declined when Microsoft withdrew its Java support from I NTERNET E XPLORER3 default conguration, however, the plugin is still available as a free download from JAVA . COM4 . More information can be found about applets at the A PPLET C HAPTER5 , in this book. Also, Wikipedia has an article about J AVA A PPLETS6 . Client Server applications : The client server applications consist of a front-end, and a backend part, both running on a separate computer. The idea is that the business logic would be on the back-end part of the program, which would be reused by all the clients. Here the challenge is to achieve a separation between front-end user interface code, and the back-end business logic code. The communication between the front-end and the back-end can be achieved by two ways. One way is to dene a data communication PROTOCOL7 between the two tiers. The back-end part would listen for an incoming request. Based on the PROTOCOL8 it interprets the request and sends back the result in data form. The other way is to use J AVA R EMOTE I NVOCATION9 (RMI). With the use of RMI, a remote object can be created and used by the client. In this case Java objects are transmitted across the network. More information can be found about client-server programming, with sample code, at the C LIENT S ERVER C HAPTER10 in this book. Web Applications : For applications needed by lots of client installations, the client-server model did not work. Maintaining and upgrading the hundreds or thousands of clients caused a problem. It was not practical. The solution to this problem was to create a unied, standard client, for all applications, and that is the B ROWSER11 .
2 3 4 5 6 7 8 9 10 11
H T T P :// E N . W I K I P E D I A . O R G / W I K I /HTML H T T P :// E N . W I K I P E D I A . O R G / W I K I /I N T E R N E T %20E X P L O R E R H T T P :// J A V A . C O M / H T T P :// E N . W I K I B O O K S . O R G / W I K I /J A V A %20P R O G R A M M I N G %2FA P P L E T S H T T P :// E N . W I K I P E D I A . O R G / W I K I /J A V A %20 A P P L E T H T T P :// E N . W I K I P E D I A . O R G / W I K I /P R O T O C O L %20%28 C O M P U T I N G %29 H T T P :// E N . W I K I P E D I A . O R G / W I K I /P R O T O C O L %20%28 C O M P U T I N G %29 H T T P :// E N . W I K I P E D I A . O R G / W I K I /J A V A %20 R E M O T E %20 M E T H O D %20 I N V O C A T I O N H T T P :// E N . W I K I B O O K S . O R G / W I K I /J A V A %20P R O G R A M M I N G %2FC L I E N T %20S E R V E R H T T P :// E N . W I K I P E D I A . O R G / W I K I /W E B %20 B R O W S E R
35
Execution
Having a standard client, it makes sense to create a unied, standard back-end service as well, and that is the A PPLICATION S ERVER12 . Web Application is an application that is running in the A PPLICATION S ERVER13 , and it can be accessed and used by the B ROWSER14 client. There are three main area of interest in Web Applications, those are: The W EB B ROWSER15 . This is the container of rendering HTML text, and running client scripts The HTTP16 PROTOCOL17 . Text data are sent back and forth between Browser and the Server The W EB SERVER18 to serve static content, A PPLICATION SERVER19 to serve dynamic content and host EJB20 s. Wikipedia also has an article about W EB APPLICATION21 .
12 13 14 15 16 17 18 19 20 21 22
H T T P :// E N . W I K I P E D I A . O R G / W I K I /A P P L I C A T I O N %20 S E R V E R H T T P :// E N . W I K I P E D I A . O R G / W I K I /A P P L I C A T I O N %20 S E R V E R H T T P :// E N . W I K I P E D I A . O R G / W I K I /W E B %20 B R O W S E R H T T P :// E N . W I K I P E D I A . O R G / W I K I /W E B %20B R O W S E R H T T P :// E N . W I K I P E D I A . O R G / W I K I /H Y P E R T E X T %20T R A N S F E R %20P R O T O C O L H T T P :// E N . W I K I P E D I A . O R G / W I K I /P R O T O C O L %20%28 C O M P U T I N G %29 H T T P :// E N . W I K I P E D I A . O R G / W I K I /W E B %20 S E R V E R H T T P :// E N . W I K I P E D I A . O R G / W I K I /A P P L I C A T I O N %20 S E R V E R H T T P :// E N . W I K I P E D I A . O R G / W I K I /E N T E R P R I S E %20J A V A B E A N H T T P :// E N . W I K I P E D I A . O R G / W I K I /W E B %20 A P P L I C A T I O N H T T P :// E N . W I K I P E D I A . O R G / W I K I /S O F T W A R E %20 C O M P O N E N T R Y
36
Java Servlet code : (Figure 3) Java got its popularity with server side programming, more specifically with J2EE23 servlets. Servlets are running in a simple J2EE framework to handle client HTTP24 requests. They are meant to replace CGI PROGRAMMING25 for web pages rendering dynamic content. The servlet is running in a so called servlets responsibility is to:
SERVLET- CONTAINER / WEB CONTAINER 26 .
The
Handle the request by doing the business logic computation, Connecting to a database if needed, Create HTML to present to the user through the browser The HTML output represents both the presention logic and the results of the business computations. This represents a huge problem, and there is no real application relying only on servlets to handle the presention part of the responsibility. There are two main solutions to this: Use a template tool (Store the presentation part in an HTML le, marking the areas that need to be replaced after business logic computations).
23 24 25 26
H T T P :// E N . W I K I P E D I A . O R G / W I K I /J A V A %20EE H T T P :// E N . W I K I P E D I A . O R G / W I K I /H Y P E R T E X T %20T R A N S F E R %20P R O T O C O L H T T P :// E N . W I K I P E D I A . O R G / W I K I /C O M M O N %20G A T E W A Y %20I N T E R F A C E H T T P :// E N . W I K I P E D I A . O R G / W I K I /W E B %20 C O N T A I N E R
37
Execution
Use JSP (See next section) Wikipedia also has an article about S ERVLETS27 .
Java Server Pages (JSP) code : (Figure 4) JSP is an HTML le with embedded Java code inside. The rst time the JSP is accessed, the JSP is converted to a Java Servlet. This servlet outputs HTML which has inside the result of the business logic computation. There are special JSP tags that helps to add data dynamically to the HTML. Also JSP technology allows to create custom tags. Using the JSP technology correctly, business logic computations should not be in the embedded Java part of the JSP . JSP should be used to render the presentation of the static and dynamic data. Depending on the complexity of the data, 100% separation is not easy to achieve. Using custom tags, however may help to get closer to 100%. This is advocated also in MVC28 architecture (see below).
27 28
38
EJB code : (Figure 5) In the 1990s, with the client server computing, a trend started, that is to move away from Mainfraim computing. That resulted in many small separate applications in a Company/Enterprise. Many times the same data was used in different applications. A new philosophy, "Enterprise Computing", was created to address these issues. The idea was to create components that can be reused throughout the Enterprise. The Enterprise Java Beans (EJBs) were supposed to address this. An EJB is an application component that runs in an EJB container. The client accesses the EJB modules through the container, never directly. The container manages the life cycle of the EJB modules, and handles all the issues that arise from network/enterpise computing. Some of those are SECURITY / ACCESS CONTROL29 , OB JECT POOLING 30 , TRANSACTION MANAGEMENT 31 , ... . EJBs have the same problems as any reusable code: they need to be generic enough to be able to be reused and the changes or maintenance of EJBs can affect existing clients. Many times EJBs are used unnecessarily when they are not really needed. An EJB should be designed as a separate application in the enterprise, fullling one function.
29 30 31
39
Execution
../tmp/8.png
Combine J2EE components to create an MVC architecture : This leads us to the three layers/tiers as shown in (Figure 6). In modern web applications, with lots of static data and nice graphics, how the data is presented to the user became very important and usually needs the help of a graphic artist. To help programmers and graphic artists to work together, the separation between data, code, and how it is presented became crucial. The view (User Interface Logic) contains the logic that is necessary to construct the presentation. This could be handled by JSP technology. The servlet acts as the controller and contains the logic that is necessary to process user events and to select an appropriate response.
40
Jini
The business logic (model) actually accomplishes the goal of the interaction. This might be a query or an update to a database. This could be handled by EJB technology. For more information about MVC, please see MVC32 .
7.3 Jini
After J2EE Sun had a vision about the next step of network computing. That is J INI33 . The main idea is that in a network environment, there would be many independent services and consumers. Jini would allow these services/consumers to interact dynamically with each other in a robust way. The basic features of Jini are: No user intervention is needed when services are brought on or ofine. (In contrast to EJBs where the client program has to know the server and port number where the EJB is deployed, in Jini the client is supposed to nd, to discover, the service in the network.) Self healing by adapting when services (consumers of services) come and go. (Services periodically need to renew a lease to indicate that they are still available.) Consumers of JINI services do not need prior knowledge of the services implementation. The implementation is downloaded dynamically and run on the consumer JVM, without conguration and user intervention. (For example, the end user may be presented with a slightly different user interface depending upon which service is being used at the time. The implementation of the user interface code would be provided by the service being used.) A minimal Jini network environment consists of: One or more services A lookup-service keeping a list of registered services One or more consumers Jini is not widely used at the current writing (2006). There are two possible reasons for it. One is Jini a bit complicated to understand and to set it up. The other reason is that Microsoft pulled out from Java, which caused the industry to turn to the use of proprietary solutions. C ATEGORY:J AVA P ROGRAMMING34
32 33 34
41
Execution
42
} }
Save it as HelloWorld.java. Again, make sure that the lename is the same case as the class name. Compile and run it:
javac HelloWorld.java java HelloWorld
declares a Java class named HelloWorld. This class is declared public - it is available to any other class. The next line,
1 2
43
begins a Java method named main. The main method is where Java will start executing the program. args is a method parameter which will contain the command line arguments used to run the program. The method must be both public and static for the program to run correctly. For more information on modiers such as public and static, see A CCESS M ODIFIERS3 , though at this level, you dont need to know a whole lot about them. The
System.out.println(string);
statement sends the text Hello, world! to the console (with a line terminator). The nal two braces mark the end of the main method and the end of the class.
it will print
Hello, wikibooks!
Chapter 15 on page 87
44
Common Problems
Hello, wikibooks!
or, if you do not pass a command line parameter, it will simply print
Hello, World!
Wikipedia has a hello world sample for each type of java code, for more information see J AVA ( PROGRAMMING LANGUAGE )#H ELLO WORLD4
W ORLD6
4 5 6 7
Chapter 9 on page 47
H T T P :// C S . W I K I B O O K S . O R G / W I K I /K U R Z %20 P R O G R A M O V %E1 N %ED%20 V %20J A V %01%1B%2FH E L L O % 20W O R L D H T T P :// P T . W I K I B O O K S . O R G / W I K I /J A V A %2FC R I A N D O %20 E %20 E X E C U T A N D O %20 O %20 P R I M E I R O % 20 P R O G R A M A
45
46
At this point, you may wish to review the source to see how much you might be able to understand. While perhaps not being the most literate of programming languages, someone with understanding of other procedural languages such as C, or other OO languages such as C++ or C#, will be able to understand most if not all of the sample program.
47
Understanding a Java Program Once you save the le, COMPILE1 the program:
javac Distance.java
(If the javac command fails, review the J AVA INSTALLATION INSTRUCTIONS2 .) To run the program, you supply it with the x and y coordinates of two points on a plane. (For this version of Distance, only integer points are supported.) The command sequence is
java Distance x0 y0 x1 y1
to compute the distance between the points (x0 , y0 ) and (x1 , y1 ) For example, the command
java Distance 0 3 4 0
will compute the distance between the points (0,3) and (4,0) and print the following:
Distance between java.awt.Point[x=0,y=3] and java.awt.Point[x=4,y=0] is 5.0
The command
java Distance -4 5 11 19
will compute the distance between the points (-4,5) and (11,19):
Distance between java.awt.Point[x=-4,y=5] and java.awt.Point[x=11,y=19] is 20.518284528683193
Well explain this strange looking output, and also show how to improve it, later.
1 2
48
is the class declaration. It consists (in this case) of two keywords, P U B L I C 10 and C L A S S 11 followed by the identier Distance. This means that we are dening a class named Distance. Other classes, or in our case, the command line, can refer to the class by this name. The public keyword is an ACCESS MODIFIER12 which declares that this class and its members may be accessed from other classes. The class keyword, obviously, identies this declaration as a class. Java also allows declarations of INTERFACES 13 and (as of Java 5) ANNOTATIONS 14 .
3 4 5 6 7 8 9 10 11 12 13 14
Chapter 10 on page 57
H T T P :// E N . W I K I B O O K S . O R G / W I K I /J A V A %20P R O G R A M M I N G %2FK E Y W O R D S
49
The class declaration is then followed by a block (surrounded by curly braces) which provides the classs denition. The denition is the implementation of the class - the declaration and denitions of the classs members. This class contains exactly six members, which we will explain in turn. 1. Two eld declarations, named point0 and point1 2. A constructor declaration 3. Three method declarations
declares two INSTANCE FIELDS15 . Instance elds represent named values that are allocated whenever an instance of the class is constructed. When a Java program creates a Distance instance, that instance will contain space for point0 and point1. When another Distance object is created, it will contain space for its own point0 and point1 values. The value of point0 in the rst Distance object can vary independently of the value of point0 in the second Distance object. This declaration consists of: 1. The P R I V A T E 16 access modier, which means these instance elds are not visible to other classes. 2. The type of the instance elds. In this case, the type is java.awt.Point. This is the class Point in the java.awt package. 3. The names of the instance elds in a comma separated list. These two elds could also have been declared with two separate but more verbose declarations,
private java.awt.Point point0; private java.awt.Point point1;
Since the types of these elds is a reference type (i.e. a eld that refers to or can hold a reference to an object value), Java will implicitly initialize the values of point0 and point1 to null when a Distance instance is created. The null value means that a reference value does not refer to an object. The special Java literal, null is used to represent the null value in a program. While you can explicitly assign null values in a declaration, as in
private java.awt.Point point0 = null; private java.awt.Point point1 = null;
15 16
50
Example: Constructor A CONSTRUCTOR17 is a special method in a class which is used to construct an instance of the class. The constructor can perform initialization for the object, beyond that which the Java VM does automatically. For example, Java will automatically initialize the elds point0 and point1 to null. Below is the constructor for this class. It consists of ve parts: 1. The optional ACCESS MODIFIER ( S )18 . In this case, the constructor is declared public 2. The constructor name, which must match the class name exactly: Distance in this case. 3. The constructor PARAMETERS19 . The parameter list is required. Even if a constructor does not have any parameters, you must specify the empty list (). The parameter list declares the type and name of each of the methods parameters. 4. An optional throws clause which declares the exceptions that the constructor may throw. This constructor does not declare any exceptions. 5. The constructor body, which is a Java BLOCK20 (enclosed in {}). This constructors body contains two statements.
public Distance(int x0, int y0, int x1, int y1) { point0 = new java.awt.Point(x0, y0); point1 = new java.awt.Point(x1, y1); } This constructor accepts four parameters, named x0, y0, x1 and y1. Each parameter requires a parameter
type declaration, which in this example is int for all four parameters. Java integer values are signed, 32 bit twos complement integers. The parameters in the parameter list are separated by commas. The two assignments in this constructor use Javas new operator to allocate two java.awt.Point objects. The rst allocates an object representing the rst point, (x0, y0), and assigns it to the point0 instance variable (replacing the null value that the instance variable was initialized to). The second statement allocates a second java.awt.Point instance with (x1, y1) and assigns it to the point1 instance variable. This is the constructor for the Distance class. Distance implicitly extends from java.lang.Object. Java inserts a call to the super constructor as the rst executable statement of the constructor if there is not one explicitly coded. The above constructor body is equivalent to the following body with the explicit super constructor call:
{ super(); point0 = new java.awt.Point(x0, y0); point1 = new java.awt.Point(x1, y1); }
17 18 19 20
51
While it is true that this class could be implemented in other ways, such as simply storing the coordinates of the two points and computing the distance as (x 1 x 0 )2 + ( y 1 y 0 )2 , this class instead uses the existing java.awt.Point class. This choice matches the abstract denition of this class: to print the distance between two points on the plane. We take advantage of existing behavior already implemented in the Java platform rather than implementing it again. We will see later how to make the program more exible without adding much complexity, because we choose to use object abstractions here. However, the key point is that this class uses information hiding. That is, how the class stores its state or how it computes the distance is hidden. We can change this implementation without altering how clients use and invoke the class.
Example: Methods Methods are the third and most important type of class member. This class contains three methods in which the behavior of the Distance class is dened: printDistance(), main(), and
intValue()
The printDistance() method The printDistance() method prints the distance between the two points to the standard output (normally the console).
public void printDistance() { System.out.println("Distance between " + point0 + " and " + point1 + " is " + point0.distance(point1)); }
This INSTANCE METHOD21 executes within the context of an implicit Distance object. The instance eld references, point0 and point1, refer to instance elds of that implicit object. You can also use the special variable this to explicitly reference the current object. Within an instance method, Java binds the name this to the object on which the method is executing, and the type of this is that of the current class. The body of the printDistance method could also be coded as
System.out.println("Distance between " + this.point0 + " and " + this.point1 + " is " + this.point0.distance(this.point1)); }
to make the instance eld references more explicit. This method both computes the distance and prints it in one statement. The distance is computed with point0.distance(point1); distance() is an instance method of the java.awt.Point class (of which point0 and point1 are instances. The method operates on point0 (binding this to the object that point0 refers to during the execution of the method)
21
H T T P :// E N . W I K I B O O K S . O R G / W I K I /J A V A %20P R O G R A M M I N G %2FI N S T A N C E %20M E T H O D S
52
and accepting another Point as a parameter. (Actually, it is slightly more complicated than that, but well explain later.) The result of the distance() method is a double precision oating point number. This method uses the syntax
"Distance between " + this.point0 + " and " + this.point1 + " is " + this.point0.distance(this.point1)
to construct a String to pass to the System.out.println(). This expression is a series of S TRING CONCATENATION22 methods which concatenates Strings or the String representation of primitive types (such as doubles) or objects, and returns a long string. For example, the result of this expression for the points (0,3) and (4,0) is the String
"Distance between java.awt.Point[x=0,y=3] and java.awt.Point[x=4,y=0] is 5.0"
which the method then prints to System.out. In order to print, we invoke the println(). This is an instance method from java.io.PrintStream, which is the type of the static eld out in the class java.lang.System. The Java VM binds System.out to the standard output stream when it starts a program.
The main() method The main() method is the main entry point which Java invokes when you start a Java program from the command line. The command
java Distance 0 3 4 0
instructs Java to locate the Distance class, put the four command line arguments into an array of String values, then pass those arguments the public static main(String[]) method of the class. (We will introduce arrays shortly.) Any Java class that you want to invoke from the command line or desktop shortcut must have a main method with this signature.
public static void main(String[] args) { Distance dist = new Distance( intValue(args[0]), intValue(args[1]), intValue(args[2]), intValue(args[3])); dist.printDistance(); }
22
53
The main() method invokes the nal method, intValue(), four times. The intValue() takes a single string parameter and returns the integer value represented in the string. For example, intValue("3") will return the integer 3.
The intValue() method The intValue() method delegates its job to the Integer.parseInt() method. The main method could have called Integer.parseInt() directly; the intValue() method simply makes the main() method slightly more readable.
private static int intValue(String data) { return Integer.parseInt(data); }
This method is P R I V A T E 23 since, like the elds point0 and point1, it is part of the internal implementation of the class and is not part of the external programming interface of the Distance class.
Static vs. Instance Methods Both the main() and intValue() methods are STATIC METHODS24 . The static keyword tells the compiler to create a single memory space associated with the class. Each individual object instantiated has its own private state variables and methods but use the same static methods and members common to the single class object created by the compiler when the rst class object is instantiated or created. This means that the method executes in a static or non-object context - there is no implicit separate instance available when the static methods run from various objects, and the special variable this is not available. As such, static methods cannot access instance methods or instance elds (such as printDistance()) or point0) directly. The main() method can only invoke the instance method printDistance() method via an instance reference such as dist.
Reference Types A reference type is a Java data type which is dened by a Java class or interface. Reference types derive this name because such values refer to an object or contain a reference to an object. The idea is similar to pointers in other languages like C.
23 24
54
Detailed Program Structure and Overview Java represents sequences of character data, or S TRING25 , with the reference type java.lang.String which is most commonly referred to as String. String literals, such as "Distance between " are constants whose type is String. This program uses three separate reference types: 1. java.lang.String (or simply String) 2. Distance 3. java.awt.Point For more information see chapter : J AVA P ROGRAMMING /C LASSES , O BJECTS AND T YPES26 .
Primitive Types In addition to object or reference types, Java supports PRIMITIVE TYPES27 . The primitive types are used to represent Boolean, character, and numeric values. This program uses only one primitive type explicitly, int, which represents 32 bit signed integer values. The program also implicitly uses double, which is the return type of the distance() method of java.awt.Point. double values are 64 bit IEEE oating point values. The main() method uses integer values 0, 1, 2, and 3 to access elements of the command line arguments. The Distance() constructors four parameters also have the type int. Also, the intValue() method has a return type of int. This means a call to that method, such as intValue(args[0]), is an expression of type int. This helps explain why the main method cannot call
new Distance(args[0], args[1], args[2], args[3]) // this is an error
Since the type of the args array element is String, and our constructors parameters must be int, such a call would result in an error because Java cannot automatically convert values of type String into int values. Javas primitive types are boolean, byte, char, short, int, long, oat and double, each of which are also Java language keywords.
Array Types Java supports ARRAYS28 , which are aggregate types which have a xed element type (which can be any Java type) and an integral size. This program uses only one array, String[] args. This indicates that args has an array type and that the element type is String. The Java VM constructs and initializes the array that is passed to the main method. See ARRAYS29 for more details on how to create arrays and access their size. The elements of arrays are accessed with integer indices. The rst element of an array is always element 0. This program accesses the rst four elements of the args array explicitly with the
25 26 27 28 29 Chapter 19 on page 107 Chapter 12 on page 75 Chapter 17 on page 99 Chapter 29 on page 145 Chapter 29 on page 145
55
indices 0, 1, 2, and 3. (This program does not perform any input validation, such as verifying that the user passed at least four arguments to the program. We will x that later.)
void is not a type in Java; it represents the absence of a type. Methods which do not return values are declared as void methods. This class denes two void methods:
public static void main(String[] args) { ... } public void printDistance() { ... }
VOID 30
30 31
2FJ A V A D O C _ A N D _ O T H E R _ C O M M E N T S
56
10 Syntax
Java derives much of its syntax from the C1 programming language: basic assignment statement syntax, expressions, control ow statements and blocks, etc. will be very familiar to C programmers. Unicode : Java source code are built by Unicode characters. Tokens : Java programs consist of a sequence of different kinds of tokens. For example, there are word tokens such as class and public which are KEYWORDS2 . K EYWORDS3 : Those are special words with reserved meaning in Java. Those words can not be used by the programers to name identiers. Identiers : Other words (non keywords) are identiers. Identiers have many different uses in Java but primarily they are used as names, class names, method names, and variable names... .
LITERALS 4
: Java also has tokens to represent numbers, such as 1 and 3; these are known as LITERALS 5 .
String LITERALS6 , such as "http://en.wikibooks.org/Java_Programming", consist of zero or more characters embedded in double quotes. O PERATORS7 : And OPERATORS8 such as + and = are used to express basic computation such as addition or String concatenation or assignment. B LOCKS9 : There are also left and right braces ({ and }) which enclose BLOCKS10 . The body of a class is one such block. S TATEMENTS11 : A Block contains one or more Java STATEMENT ( S )12 , separated by semicolons. A statement is the smallest building block of Java. Separators : Some tokens are punctuation, such as periods . and commas , and semicolons ;.
1 2 3 4 5 6 7 8 9 10 11 12
H T T P :// E N . W I K I B O O K S . O R G / W I K I /P R O G R A M M I N G %3AC H T T P :// E N . W I K I B O O K S . O R G / W I K I /J A V A %20P R O G R A M M I N G %2FK E Y W O R D S H T T P :// E N . W I K I B O O K S . O R G / W I K I /J A V A %20P R O G R A M M I N G %2FK E Y W O R D S
Chapter 10.3 on page 60 Chapter 10.3 on page 60 Chapter 11 on page 63 Chapter 11 on page 63
57
Syntax
WHITESPACE 13
: You use WHITESPACE14 such as spaces, tabs, and newlines, to separate tokens. For example, whitespace is required between keywords and identiers: publicstatic is a single identier with twelve characters, not two Java keywords.
C OMMENTS15 : Comments are not part of the executing code. Comments are used to document the code.
10.1 Unicode
Most Java program text consists of ASCII16 characters, but any Unicode character can be used as part of identier names, in comments, and in character and string literals. U NICODE ESCAPE SEQUENCES 17 may also be used to express a Unicode character. For example, (which is the Greek Lowercase Letter pi) is a valid Java identier.
double
= Math.PI;
may also be represented in Java as the Unicode escape sequence \u03C0. Thus, the following is a valid, but not very readable, declaration and assignment:
double \u03C0 = Math.PI;
The following demonstrate the use of Unicode escape sequences in other Java syntax:
Declare Strings pi and quote which contain \u03C0 and \u0027 respectively:
Note that a Unicode escape sequence functions just like any other character in the source code. E.g., \u0022 (double quote, ") needs to be quoted in a string just like ".
13 14 15 16 17
58
Literals
Declare Strings doubleQuote1 and doubleQuote2 which both contain " (double quote):
10.2 Literals
Java Literals are syntactic representations of boolean, character, numeric, or string data. Literals provide a means of expressing specic values in your program. For example, in the following statement, an integer variable named count is declared and assigned an integer value. The literal 0 represents, natually enough, the value zero.
int count = 0;
The following method call passes a String literal string the boolean literal true and the special null value null to the method parse():
List items = parse(string, true, null);
B OOLEAN L ITERALS20 N UMERIC L ITERALS21 C HARACTER L ITERALS22 I NTEGER L ITERALS23 F LOATING P OINT L ITERALS24
18 19 20 21 22 23 24
H T T P :// E N . W I K I B O O K S . O R G / W I K I /J A V A %20P R O G R A M M I N G %2FS Y N T A X %2FU N I C O D E %20E S C A P E % 20S E Q U E N C E S H T T P :// E N . W I K I B O O K S . O R G / W I K I /C A T E G O R Y %3AJ A V A %20P R O G R A M M I N G H T T P :// E N . W I K I B O O K S . O R G / W I K I /J A V A %20P R O G R A M M I N G %2FL I T E R A L S %2FB O O L E A N % 20 L I T E R A L S H T T P :// E N . W I K I B O O K S . O R G / W I K I /J A V A %20P R O G R A M M I N G %2FL I T E R A L S %2FN U M E R I C % 20L I T E R A L S H T T P :// E N . W I K I B O O K S . O R G / W I K I /J A V A %20P R O G R A M M I N G %2FL I T E R A L S %2FN U M E R I C % 20L I T E R A L S %2FC H A R A C T E R %20L I T E R A L S H T T P :// E N . W I K I B O O K S . O R G / W I K I /J A V A %20P R O G R A M M I N G %2FL I T E R A L S %2FN U M E R I C % 20L I T E R A L S %2FI N T E G E R %20L I T E R A L S H T T P :// E N . W I K I B O O K S . O R G / W I K I /J A V A %20P R O G R A M M I N G %2FL I T E R A L S %2FN U M E R I C % 20L I T E R A L S %2FF L O A T I N G %20P O I N T %20L I T E R A L S
59
Syntax
10.3 Blocks
Java has a concept called block that is enclosed between the { and } characters, called curly braces. A block executed as a single statetement, and can be used where a single statetement is accepted. After a block is executed all local variables dened inside the block is discarded, go out of scope.
{ ... // -- This is a block --}
10.4 Whitespaces
Whitespace in Java is used to separate the tokens in a Java source le. Whitespace is required in some places, such as between ACCESS MODIFIERS28 , TYPE NAMES29 and Identiers, and is used to improve readability elsewhere. Wherever whitespace is required in Java, one or more whitespace characters may be used. Wherever whitespace is optional in Java, zero or more whitespace characters may be used. Java whitespace consists of the space character (0x20), the tab character (hex 0x09), the form feed character (hex 0x0c), the line separators characters newline (hex 0x0a) or carriage return (hex 0x0d) characters.
25
H T T P :// E N . W I K I B O O K S . O R G / W I K I /J A V A %20P R O G R A M M I N G %2FL I T E R A L S %2FS T R I N G % 20L I T E R A L S 26 H T T P :// E N . W I K I B O O K S . O R G / W I K I /J A V A %20P R O G R A M M I N G %2FL I T E R A L S %2F N U L L 27 H T T P :// E N . W I K I B O O K S . O R G / W I K I /C A T E G O R Y %3AJ A V A %20P R O G R A M M I N G
28 29
60
Required Whitespace
Line separators are special whitespace characters in that they also terminate line comments, whereas normal whitespace does not. Other Unicode space characters, including vertical tab, are not allowed as whitespace in Java.
Whitespace is required between public and abstract, between abstract and Distance, between Distance and distanceTo, and between Destination and dest. However, the following is not legal:
publicabstractDistance distanceTo(Destination dest);
because whitespace is required between keywords and identiers. The following is lexically valid
publicabstractDistance distanceTo(Destination dest);
but means something completely different: it declares a method which has the return type publicabstractDistance It is unlikely that this type exists, so the above would result in a semantic error.
10.6 Indentation
Java ignores all whitespace in front of a statement. As this, these two code snippets are identical for the compiler:
public static void main(String[] args) { printMessage(); } void printMessage() { System.out.println("Hello World!"); }
public static void main(String[] args) { printMessage(); } void printMessage() { System.out.println("Hello World!"); }
61
Syntax
However, the rst ones style (with whitespace) is preferred, as the readability is higher. (The method body is easier to distinguish from the head, even at a higher reading speed.) C ATEGORY:JAVA P ROGRAMMING30 C ATEGORY:JAVA P ROGRAMMING31
30 31
62
11 Statements
Now, that we have the Java platform on our systems and have run the rst program successfully, we are geared towards understanding how programs are actually made. As we have already discussed. A program is a set of instructions very simple tasks provided to a computer. These instructions are called statements in Java. Statements can be anything from a single line of code to a complex mathematical equation. This section helps you understand what statements are and how they work.
This line is a simple instruction that tells the system to initialize a variable and set its value as 24. Within that simple denition, we talked about initialization of a variable and setting its value. This all might sound a bit too technical, but it will make sense as you read ahead.
The class declaration and function declaration will be described in the upcoming chapters.
63
Statements
11.3 Variables
Christmases are usually exciting, birthdays too. And the one thing that makes them exciting are: you get presents. Think of a present youve ever gotten. A tiny (or big, if youre lucky) box with your name on it. Now think of variables as something similar. They are tiny little boxes in the computers memory that save something within themselves. This something within them is called a value.
Note: A variable is an identier to a value in the systems memory.
This is actually wrong. By denition (if you have been awake throughout your mathematics lectures) youd know that integers are whole numbers: 0, 1, 2, all the way up to innity. Anything with a decimal point is not an integer, hence the statement by virtue of it is wrong. What would make it right is when you assign a certain type to the variable that would accept numbers with decimal points numbers with decimal points are called oating points.
64
Assignment statements
Why not float, you say? Well, there are several reasons why not. 10.5 can be anything a float or a double but by a certain rule, it is given a certain type. This can be explained further by looking at the table below.
Data type Values accepted Declaration
long
float
double
Any number between -128 byte b = 123; and 127. Any number between short s = 12345; -32,768 and 32,767. Any number between int i = 1234567; -2,147,483,648 and 2,147,483,647. long l = 1234567890L; Any number between -9,223,372,036,854,775,808 and 9,223,372,036,854,775,807. Extremely large numbers oat f = 123.4567f; beyond the scope of discussion here. double d = 1234.56789; Extremely large numbers beyond the scope of discussion here. The only difference between double and float is the addition of an f as a sufx after the float value.
The above table only list the number data types. We will look at the others as we go on. So, did you notice why we used a double in listing 1.3, and not a float? The answer is pretty simple. If wed used a float, we would have to append the number with a f as a sufx, so 10.5 should be 10.5f as in:
Listing 1.4: The correct way to dene oating point numbers of type float.
float age = 10.5f;
65
Statements
You do not necessarily have to use a new line to write each statement. Just like English, you can begin writing the next statement where you ended the rst one as depicted below:
Listing 1.6: Multiple assignment statement on the same line.
int a = 10; int b = 20; int c = 30;
However, the only problem with writing such code is, its very difcult to read it back. It doesnt look that intimidating at rst, but once youve got a signicant amount of code, its usually better to organize it in a way that makes sense. It would look more complex and incomprehensible written as it is in Listing 1.6. Now that we have looked into the anatomy of a simple assignment statement, we can look back at what weve achieved. We know that... A statement is a unit of code in programming. If we are assigning a variable a value, the statement is called an assignment statement. An assignment statement include three parts: a data type, variable name (also called an identier) and the value of a variable. We will look more into the nature of identiers and values in the section titled I DENTIFIERS , LITERALS AND EXPRESSIONS1 later. Now, before we more on to the next topic, you need to try and understand what the code below does.
Listing 1.7: Multiple assignment statements with expressions
int firstNumber = 10; int secondNumber = 20; int result = firstNumber + secondNumber;
The rst two statements are pretty much similar to those in Listing 1.5 but with different variable names. The third however is a bit interesting. Weve already talked of variables as being similar to gift boxes. Think of your computers memory as a shelf where you put all those boxes. Whenever you need a box (or variable), you call its identier (thats the name of the variable). So calling the variable identier firstNumber gives you the number 10, calling secondNumber would give you 20 hence when you add the two up, the answer should be 30. Thats what the value of the last variable result would be. The part of the third statement where you add the numbers, i.e., firstNumber + secondNumber is called an expression and the expression is what decides what the value is to be. If its just a plain value, nothing fancy, then its called a literal. With the information you have just attained, you can actually write a decent Java program that can sum up values. To learn more, continue reading.
1
H T T P :// E N . W I K I B O O K S . O R G / W I K I /J A V A %20P R O G R A M M I N G %2FI D E N T I F I E R S %2C%20 L I T E R A L S % 20 A N D %20 E X P R E S S I O N S
66
<!--
{
public static void main(String[] args)
67
Statements
{ System.out.println("Inside aMethod!"); } }
Running the above code would provide us with this screen of information.
Inside main method! Invoking aMethod! Inside aMethod! Back in main method!
The program ow begins in the main method. Just as aMethod is invoked, the ow travels to the called method. At this very point, the ow branches to the other method. Once the method is completed, the ow is returned to the point it left off and resumes at the next statement after the call to the method.
Also referred to as if statements, these allow a program to perform a test and then take action based on the result of that test. The form of the if statement:
if (condition){ do statements here if condition is true } else { do statements here if condition is false
The condition is a boolean expression which can be either true or false. The actions performed will depend on the value of the condition. Example:
if ( i > 0 ){
68
Branching Statements
If statements can also be made more complex using the else if combination:
if (condition 1){ do statements here if condition 1 is true
}
else if (condition 2){ do statements here if condition 1 is false and condition 2 is true } else { do statements here if neither condition 1 nor condition 2 is true
Example:
if ( i > 0 ){
If there is only one statement to be executed after the condition, as in the above example, it is possible to omit the curly braces, however Suns JAVA C ODE C ONVENTIONS2 explicitly state that the braces should always be used. There is no looping involved in an if statement so once the condition has been evaluated the program will continue with the next instruction after the statement.
If...else statements
The if ... else statement is used to conditionally execute one of two blocks of statements, depending on the result of a boolean condition. Example:
if (list == null) {
}
else {
H T T P :// J A V A . S U N . C O M / D O C S / C O D E C O N V / H T M L /C O D E C O N V E N T I O N S . D O C 6. H T M L #449
69
Statements
Suns JAVA C ODE C ONVENTIONS3 recommend that the braces should always be used. An if statement has two forms:
if (boolean-condition)
statement1
and
if (boolean-condition)
statement1
else
statement2
Use the second form if you have different statements to execute if the boolean-condition is true or if it is false. Use the rst if you only wish to execute statement1 if the condition is true and you do not wish to execute alternate statements if the condition is false. The following example calls two int methods, f() and y(), stores the results, then uses an if statement to test if x is less than y and if it is, the statement1 body will swap the values. The end result is x always contains the larger result and y always contains the smaller result.
int x = f(); int y = y(); if ( x < y ) { int z = x;
x = y; y = z; }
if...else statements also allow for the use of another statement, else if. This statement is used to provide another if statement to the conditional that can only be executed if the others are not true. For example:
if (x == 2)
x = 4;
else if (x == 3)
x = 6;
else
x = -1;
The else if statement is useful in this case because if one of the conditionals is true, the other must be false. Keep in mind that if one is true, the other will not execute. For example, if the statement contained in the rst conditional, if(x == 2), were changed to x = 3;, the second conditional, the else if, would still not execute. However, when dealing with primitive types in
H T T P :// J A V A . S U N . C O M / D O C S / C O D E C O N V / H T M L /C O D E C O N V E N T I O N S . D O C 6. H T M L #449
70
Iteration Statements
conditional statements, it is more desirable to use S W I T C H S T A T E M E N T S 4 rather than multiple else if statements.
Switch statements
The switch conditional statement is basically a shorthand version of writing many if...else statements. The syntax for switch statements is as follows:
switch(<variable>)
{ case <result>: <statements>; break; case <result>: <statements>; break; default: <statements>; break; }
This means that if the variable included equals one of the case results, the statements following that case, until the word break will run. The default case executes if none of the others are true. Note: the only types that can be analysed through switch statements are char, byte, short, or int primitive types. This means that String variables can not by analyzed through switch statements.
int n = 2, x; switch(n)
} return x;
In this example, since the integer variable n is equal to 2, case 2 will execute, make x equal to 4. Thus, 4 is returned by the method.
71
Statements
statement; }
Here the condition is an expression. An expression as discussed earlier is any statement that returns a value. While condition statements evaluate to a boolean value, that is, either true or false. As long as the condition is true, the loop will iterate the block of code over and over and again. Once the condition evaluates to false, the loop exits to the next statement outside the loop.
If you compile and run the statement above, the program will print the numbers 0 to 99 and their squares
0 1 2 3 ... 99 0 1 4 9 9801
5 6
72
Iteration Statements
For an example, well take an array of Strings denoting days in a week and traverse through the collection, examining one item at a time.
String[] days = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"};
for (String day : days) {
System.out.println(day); }
Notice that the loop automatically exits after the last item in the collection has been examined in the statement block. Although the enhanced for loop can make code much clearer, it cant be used in some common situations. Only access. Elements can not be assigned to, eg, not to increment each element in a collection. Only single structure. Its not possible to traverse two structures at once, eg, to compare two arrays. Only single element. Use only for single element access, eg, not to compare successive elements. Only forward. Its possible to iterate only forward by single steps. At least Java 5. Dont use it if you need compatibility with versions before Java 5.
73
Statements
C ATEGORY:JAVA P ROGRAMMING7
74
The class doesnt do anything yet, as you will need to add methods and member variables rst.
75
In general there are four constructor types: default, non-default, copy, and cloning. A default constructor will build the most basic instance. Generally, this means assigning all the members values like null, zero, or an empty string. Nothing would stop you, however, from your default sports car color from being red, but this is generally bad programming style. Another programmer would be confused if your basic car came out red instead of say, colorless. A non-default constructor is designed to create an object instance with prescribed values for most, if not all, of the objects members. The car is red, goes from 0-60 in 12 seconds, tops out at 190mph, etc. A copy constructor is not included in the Java language, however one can easily create a constructor that do the same as a copy constructor. Its important to understand what it is. As the name implies, a copy constructor creates a new instance to be a duplicate of an already existing one. In Java, this can be also accomplished by creating the instance with the default constructor, and then using the assignment operator to equivocate them. This is not possible in all languages though, so just keep the terminology under your belt. Java has the concepts of cloning object, and the end results are similar to copy constructor. Cloning an object is faster than creation with the new keyword, because all the object memory is copied at once to destination cloned object. This is possible by implementing the Cloneable interface, which allows the method Object.clone() to perform a eld-by-eld copy.
12.3 Type
When an object is created, a reference to the object is also created. The object can not be accessed directly in Java, only through this object reference. This object reference has a type assigned to it. We need this type when passing the object reference to a method as a parameter. Java does strong type checking. Type is basically a list of features/operations, that can be performed through that object reference. The object reference type basically is a contract that guarantees that those operations will be there at run time. When a car is created, it comes with a list of features/operations listed in the user manual that guarantees that those will be there when the car is used. When you create an object from a class by default its type is the same as its class. It means that all the features/operations the class dened are there and available, and can be used. See below:
(new ClassName()).operations();
You can assign this to a variable having the same type as the class:
ClassName objRefVariable = new ClassName(); objRefVariable.operations();
76
You can assign the created object reference to the class super class, or to an interface the class implements:
SuperClass objectRef = new ClassName(); // features/operations list are defined by the SuperClass class .. Interface inter = new ClassName(); // features/operations list are defined by the interface
In the car analogy, the created car may have different Type of drivers. We create separate user manuals for them, Average user manual, Power user manual, Child user manual, or Handicapped user manual. Each type of user manual describes only those features/operations appropriate for the type of driver. The Power driver may have additional gears to switch to higher speeds, that are not available to other type of users... When the car key is passed from an adult to a child we replacing the user manuals, that is called Type Casting. In Java, casts can occur in three ways: up casting: going up in the inheritance tree, until we reach the Object up casting: to an interface the class implements down casting: until we reach the class the object was created from
Type and Type Casting will be covered in more details later at JAVA P ROGRAMMING /T YPES1
module.
{ ... }
class AdditionalClass
{ ... }
Because they have the "package (default)" access specier, the AdditionalClass can be accessed only in the same package. These "additional" classes compile to separate ".class" bytecode les when compiled, just as if they were in separate source les. However, including multiple classes in one le may increase the difculty in examining the structure of a given application.
77
2 3
78
13 Packages
13.1 Java Package / Name Space
Usually a Java application is built by many developers and it is common that third party modules/classes are integrated. The end product can easily contain hundreds of classes. Class name collision is likely to happen. To avoid this a Java class can be put in a "name space". This "name space" in Java is called the package. The Java package needs to be unique across Vendors to avoid name collisions. For that reason Vendors usually use their domain name in reverse order. That is guaranteed to be unique. For example a company called Your Company Inc., would use a package name something like this: com.yourcompany.yourapplicationname.yourmodule.YourClass. To put a class in a package, the package keyword is used at the top of each class le. For Example,
package com.yourcompany.yourapplication.yourmodule;
When we want to reference a Java class that is dened outside of the current package name space, we have to specify which package name space that class is in. So we could reference that class with something like com.yourcompany.yourapplication.yourmodule.YourClass . To avoid having to type in the package name each time when we want to reference an outside class, we can declare which package the class belongs to by using the import Java keyword at the top of the le. For Example,
import com.yourcompany.yourapplication.yourmodule.YourClass;
Then we can refer to that class by just using the class name YourClass . In rare cases it can happen that you need to reference two classes having the same name in different packages. In those cases, you can not use the import keyword for both classes. One of them needs to be referenced by typing in the whole package name. For Example,
package com.mycompany.myapplication.mymodule;
...
import com.yourcompany.yourapplication.youmodule.SameClassName;
79
Packages
The Java package has one more interesting characteristic; the package name corresponds where the actual le is stored on the le system. And that is actually how the compiler and the class loader nd the Java les on the le system. For example, the class com.yourcompany.yourapplication.yourmodule.YourClass, is stored on the le system in the corresponding directory : com/yourcompany/yourapplication/yourmodule/YourClass. Because of this, package names should be lowercase, since in some operating systems the directory names are not case sensitive.
While it may seem convenient, it may cause problems if you make a typographical error. For example, if you use the above import to use JFrame, but then type JFraim frame=new JFraim();, the Java compiler will report an error similar to "Cannot nd symbol: JFraim". Even though it seems as if it was imported, the compiler is giving the error report at the rst mention of JFraim, which is half-way through your code, instead of the point where you imported JFrame along with everything else in javax.swing. If you change this to import javax.swing.JFraim; the error will be at the import instead of within your code. Furthermore, if you import javax.swing.*; and import java.util.*;, and javax.swing.Queue is later added in a future version of Java, your code that uses Queue (java.util) will fail to compile. This particular example is fairly unlikely, but if you are working with non-Sun libraries, it may be more likely to happen.
To compile and run a class from a projects top directory (that contains the two directories /source and /libraries) you could use the following command:
javac -classpath libraries/lib.jar source/MainClass.java
80
(The above is simplied, and demands that MainClass be in the default package, or a package called source, which isnt very desirable.)
81
Packages
82
14 Nested Classes
In Java you can dene a class inside an other class. A class can be nested: inside another class, or inside a method
{
private String outerInstanceVar; public class InnerClass
{
public void printVars()
The inner class has access to the enclosing class instances variables and methods, even private ones, as seen above. This makes it very different from the nested class in C++, which are equivalent to the "static" inner classes, see below. An inner object has a reference to the outer object. The nested object can only be created with a reference to the outer object. See below.
public void testInner()
{ ... OuterClass outer = new OuterClass(); OuterClass.InnerClass inner = outer.new InnerClass(); ... }
(When in a non-static method of the outer class, you can directly use new InnerClass(), since the class instance is implied to be this.)
83
Nested Classes
You can directly access the reference to the outer object from within an inner class with the syntax OuterClass.this; although this is usually unnecessary because you already have access to its elds and methods. Inner classes compile to separate ".class" bytecode les, usually with the name of the enclosing class, followed by a "$", followed by the name of the inner class. So for example, the above inner class would typically be compiled to a le named "OuterClass$InnerClass.class".
{
public void method()
{
class InnerClass
{ } } }
In addition to instance variables of the enclosing class, local classes can also access local variables of the enclosing method, but only ones that are declared final. This is because the local class instance might outlive the invocation of the method, and so needs its own copy of the variable. To avoid problems with having two different copies of a mutable variable with the same name in the same scope, it is required to be nal, so it cannot be changed.
84
Anonymous Classes
{
public void click(); } ... ActionListener clk = new ActionListener() { public void click() { // --- implementation of the click event --... return; } };
In the above example the class that implements the ActionListener is anonymous. The class is dened where it is instantiated. The above code is harder to read than if the class explicitly dened, so why use it? If many implementations are needed for an interface and those classes are used only in one particular place, using anonymous class makes sense. The following example uses anonymous class to implement an action listener.
import java.awt.*; import java.awt.event.*; import java.io.Serializable; class MyApp implements Serializable
{ BigObjectThatShouldNotBeSerializedWithAButton bigOne; Button aButton = new Button(); MyApp() { aButton.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { System.out.println("Hello There"); } } ); } }
The following example does the same thing, but it names the class that implements the action listener.
import java.awt.*; import java.awt.event.*; import java.io.Serializable; class MyApp implements Serializable
{ BigObjectThatShouldNotBeSerializedWithAButton bigOne; Button aButton = new Button(); // --- Nested class to implement the action listener --class MyActionListener implements ActionListener { public void actionPerformed(ActionEvent e) {
85
Nested Classes
Using anonymous classes is especially preferable when you intend to use many different classes that each implement the same Interface. C ATEGORY:JAVA P ROGRAMMING1
86
15 Access Modiers
15.1 Access modiers
You surely would have noticed by now, the words public, protected and private at the beginning of classs method declarations used in this book. These keywords are called the access modiers in the Java language syntax, and can be dened as...
Quote:
.. keywords that help set the visibility and accessibility of a class, its member variables, and methods. The following table shows what Access Modiers are appropriate for classes, nested classes, member variables, and methods:
Class Nested class Method, or Member variable Interface Interface method signature
public protected
same as its class its class and its subclass, and from its package only from its package only from its class
Points to ponder:
Note that Interface method visibility is P U B L I C 1 by default. You do not need to specify the access modier it will default to P U B L I C 2 . For clarity it is considered a good practice to put the P U B L I C 3 keyword. The same way all member variables dened in the Interface by default will become S T A T I C 4 F I N A L 5 once inherited in a class. If a class has public visibility, the class can be referenced by anywhere in the program. If a class has package visibility, the class can be referenced only in the package where the class is dened. If a class has private visibility, (it can happen only if the class is dened nested in an other class) the class can be accessed only in the outer class.
87
Access Modiers
If a variable is dened in a public class and it has public visibility, the variable can be reference anywhere in the application through the class it is dened in. If a variable has package visibility, the variable can be referenced only in the same package through the class it is dened in. If a variable has private visibility, the variable can be accessed only in the class it is dened in. If a method is dened in a public class and it has public visibility, the method can be called anywhere in the application through the class it is dened in. If a method has package visibility, the method can be called only in the same package through the class it is dened in. If a method has private visibility, the method can be called only in the class it is dened in.
6
H T T P :// E N . W I K I B O O K S . O R G / W I K I /C A T E G O R Y %3A
88
16 Methods
16.1 Method Denition
A method is an operation on a particular object. An object is an instance of a class. When we dene a class we dene its member variables and its methods. For each method we need to give a name, we need to dene its input parameters and we need to dene its return type. We also need to set its visibility(private, package, or public). If the method throws an Exception, that needs to be declared as well. The syntax of method denition is:
class MyClass
{ ...
public ReturnType methodName( ParamOneType param1, ParamTwoType param2 ) throws ExceptionName { ReturnType retType; ... return retType; } ... }
We can declare that the method does not return anything using the void java keyword. For example:
private void methodName( String param1, String param2 )
{ ...
return;
When the method returns nothing, the return keyword at the end of the method is optional. The return keyword can be used anywhere in the method, when the executation ow reach the return keyword, the method execution is stopped and the execution ow returns to the caller method.
89
Methods
{ ... }
public void runAroundThe( Park park )
{ ... }
Related terminology is the method signature. In java the method signature contains method name and the input parameter types. The java compiler takes the signature for each method and makes sure that each method signature is unique for a class. For example the following two method denitions are valid:
public void logIt( String param, Error err )
{ ... }
public void logIt( Error err, String param )
{ ... }
Because the type order is different. If both input parameters were type String, that would be a problem since the compiler would not be able to distinguish between the two:
public void logIt( String param, String err )
{ ... }
public void logIt( String err, String param )
{ ... }
The compiler would give an error for the following method denitions as well:
public void logIt( String param )
{ ... }
public String logIt( String param )
{
String retType;
...
return retValue;
Note, the return type is not part of the unique signature. Why not? The reason is that a method can be called without assigning its return value to a variable. This feature came from C and C++. So for the call:
90
Method Overriding
{ logIt( msg ); }
In the above example obj reference has the type MyClass on both line 1 and line 3. However the obj reference points two different objects. On line 1 it references SubOfMyClass object, on line 3 it references MyClass object. So on line 5 which method will be called, method dene in MyClass, or the method that dened in its subclasses. Because the obj reference can point to object and all its sub object, and that will be known only at runtime, a table needs to be kept with all the possible method address to be called. Also another rule is that when you do an override, the visibility of the new method that overrides the super class method can not be reduced. The visibility can be increased, however. So if the super class method visibility is public, the override method can not be package, or private. In the case of the exception the override method may throw can be the same as the super class or it can be one of that exception inherited class. So the common rule is that the override method must throw the same exception or it is any of its subclasses. NOTE: A common mistake to think that if we can override methods, we could also override member variables. This is not the case, as member variables are not overriden.
91
Methods
{ 1 MyClass obj = new SubOfMyClass(); 2 3 MyClass obj = new MyClass(); 4 5 String var = obj.myMemberVar; // -- The myMemberVar is defined in the MyClass object }
In the above example, it does not count what object the obj reference points to, because it was declared MyClass type on both line 1 and line 3, the variable in the MyClass object will be referenced. In real examples we rarely use public variables, but if you do keep in mind that Java does not support variable overriding.
// -- The
On line 7 the value of var1 is 10 and the value of var2 is 20. When the variables were passed in to the methods their values were copied. This is called passing the parameter by value. In java we do not represent an object directly, we represent an object throught an object reference. You can think of an object reference as a variable having the address of the object. So the object reference passed in by value, but the object itself is not. For example:
1 2 { MyObjOne obj = new MyObjOne();
92
Functions
3 obj.setName("Christin"); 4 ... 5 myMethod( obj ); 6 String name = obj.getName(); // --- The name attribute was changed to Susan inside the method 7 } 8 void myMethod( MyObjOne obj ) 9 { 10 obj.setName("Susan"); 11 ... 12 obj = new MyObjOne(); 13 obj.setName("Sonya"); 14 ... 15 }
On line 2, we created an object, on line 3 we set its name property to Christin. On line 5 we called the myMethod( obj ). Inside the method, we changed the name to Susan through the passed in object reference. So that change will stay. Note however that after we reassigned the obj reference to a new object, that is no effect whatsoever on the passed in object.
16.5 Functions
In java, functions (methods really) are just like in C++ except that they must be declared inside a class and objects are passed by reference automatically. You cannot create pointers to a function but Java has events which really are function pointers under the hood for when you need that type of functionality.
int a_function(double d) { return (int)d; }
93
Methods
{ ... /** Nested object is for return values from getPersonInfoById method */ public static class ReturnObj { private int age; private String name;
public void setAge( int val )
{
this.age = val;
}
public int getAge()
{
return age;
}
public void setName( String val )
{ name = val; }
public String getName()
{
return name; } } // --- End of nested class defination ---
/** Method using the nested class to return values */ public ReturnObj getPersonInfoById( int ID ) { int age; String name; ... // --- Get the name and age based on the ID from the database --... ReturnObj ret = new ReturnObj(); ret.setAge( age ); ret.setName( name );
return ret;
} }
In the above example the getPersonInfoById method returns an object reference that contains both values the name and age. See below how you may use that object:
{ ... MyObject obj = new MyObject(); MyObject.ReturnObj person = obj.getPersonInfoById( 102 ); System.out.println( "Person Name=" + person.getName() ); System.out.println( "Person Age =" + person.getAge() ); ... }
94
{ private String memberField; /** * MyClass Constructor, there is no input parameter */ public MyClass() { ... } /** * MyClass Constructor, there is one input parameter */ public MyClass( String param1 ) { memberField = param1; ... } }
In the above example we dened two constructors, one with no input parameter, and one with one input parameter. You may ask which constructor will be called. Its depends how the object is created with the new keyword. See below:
{ ... MyClass obj1 = new MyClass(); no input parameter will be called MyClass obj2 = new MyClass("Init Value"); one input param. will be called ... } // The constructor with // The constructor with
In the above example we created two objects from the same class, or we can also say that obj1 and obj2 both have the same type. The difference between the two is that in the rst one the memberVar eld is not initialized, in the second one that is initialized to Init Value. obj1, and obj2 contains the reference to the object. Each class must have a constructor. If we do not dene one, the compiler will create a default so called empty constructor automatically.
public class MyClass
95
Methods
} }
The Constructor is called automatically when an object is created with the new keyword. A constructor may also be called from an other constructor, see below:
public class MyClass
{ private String memberField; /** * MyClass Constructor, there is no input parameter */ public MyClass() { MyClass("Default Value"); } /** * MyClass Constructor, there is one input parameter */ public MyClass( String param1 ) { memberField = param1; ... } }
In the above example, the constructor with no input parameter calls the other constructor with the default initial value. This gives an option to the user, to create the object with the default value or create the object with a specied value.
{
static public String myStaticMethod()
Static Methods can be referenced anywhere prexed by the class name. See below:
{ ...
96
External links
// --- Call myStaticMethod --System.out.println( "Output from the myStaticMethod:" + MyObject.myStaticMethod() ); ... }
You can write a non object oriented program by using only Static Methods in java. Because java evolved from the C programming language, Static Method is a left over from a non object oriented language. You write Static Method the same way as normal method, the only difference is that you can not reference any member variables and any object methods. Static Methods can reference only Static variables and call only other Static Methods. However you can create an object an use it inside a Static Method.
public class MyObject
{
public String memberVar; static private String memberStaticVar; static public String myStaticMethod()
memberStaticVar = "Value";
// --- Create an object --MyObject obj = new MyObject(); obj.memberVar = "Value"; // --- This is okay since an object is created -... return("I am a Static Method"); } }
97
Methods
98
17 Primitive Types
1. redirect JAVA P ROGRAMMING /T YPES1
99
Primitive Types
100
18 Types
Data Types (or simply Types) in Java are a way of telling what certain data is. It is seen as a way of
declaring allowed values for certain data, the structure of such data and operations associated with it. Any data, be it numeric or a sentence of words, can have a different data type. For instance, just to dene different types of numbers in Java, there are about six simple types available to programmers some dene whole numbers (integers numbers) and others dene numbers with a decimal values (oating point numbers). Java also gives freedom to programmers to create complex and customizable data types. We will deal with complex data types in later chapters.
18.1.1 Primitives
Primitives are the most basic data types available within the Java language. These types serve as the building blocks of data manipulation in Java. Such types serve only one purpose containing
pure, simple values of a kind. Because these data types are dened into the Java type system by
1 2 3
H T T P :// E N . W I K I B O O K S . O R G / W I K I /%23P R I M I T I V E S H T T P :// E N . W I K I B O O K S . O R G / W I K I /%23O B J E C T %20R E F E R E N C E %20T Y P E S H T T P :// E N . W I K I B O O K S . O R G / W I K I /%23A R R A Y S
101
Types
default, they come with a number of operations predened. You can not dene a new operation for such primitive types. In the Java type system, there are three further categories of primitives: N UMERIC P RIMITIVES4 <p>These primitive data types hold only numeric data. Operations associated with such data types are those of simple arithmetic (addition, subtration, etc.) or of comparions (is greater than, is equal to, etc.)</p> T EXTUAL P RIMITIVES5 <p>These primitive data types hold characters (which can be alphabets or even numbers), but unlike numbers, they do not have operations that serve arithmetic purposes. Rather, operations associated with such types are those of textual manipulation (comparing two words, joining characters to make words, etc.) B OOLEAN AND N ULL P RIMITIVES6
4 5 6 7 8 9 10
H T T P :// E N . W I K I B O O K S . O R G / W I K I /%2FN U M E R I C %20P R I M I T I V E S H T T P :// E N . W I K I B O O K S . O R G / W I K I /%2FT E X T U A L %20P R I M I T I V E S H T T P :// E N . W I K I B O O K S . O R G / W I K I /%2FO T H E R %20P R I M I T I V E S H T T P :// E N . W I K I B O O K S . O R G / W I K I /%2FJ A V A %20P R O G R A M M I N G %2FC A S T S H T T P :// E N . W I K I B O O K S . O R G / W I K I /P R O G R A M M I N G %3AS M A L L T A L K H T T P :// E N . W I K I B O O K S . O R G / W I K I /R U B Y %20P R O G R A M M I N G
Chapter 17 on page 99
102
Examples of Types
In the above example the name object references attributes are: Type is : String The referenced object is also : String
11 12 13
103
Types
Both the java.lang.String class methods and java.lang.Object class methods are available for the object reference name.
private Object name = "Marry Brown";
In the above example the name object references attributes are: Type is : Object The referenced object is : String Only the java.lang.Object class methods are available for the object reference name.
32 64
1 --
boo true --
104
The types short, int, long, oat, and double are usually used in arithmetic operations; byte and char can also be used, but less commonly. The character type char is used for text processing. The type byte is commonly used in binary le input output operations.
String objects representing literal character strings in Java, in the java.lang.* package.
java.lang.String is not a primitive type, but instead is a special class built into the Java language. For further info, see String.
The following table shows the conversions between primitive types, it shows the casting operation for explicit conversions:
from byte to byte to char to short to int to long to oat to double from char from short from int from long from oat from double from boolean
(byte) (short)
(byte) (char) -
105
Types
from char
from short
from int
from long
from oat
from double
from boolean
N/A
N/A
N/A
N/A
N/A
N/A
18.7 Autoboxing/unboxing
Autoboxing/unboxing : Autoboxing and unboxing, language features since Java 1.5, make the programmers life much easier when it comes to working with the primitive wrapper types. Consider this code fragment:
int age = 23;
Primitive wrapper objects were Javas way of allowing one to treat primitive data types as though they were objects. Consequently, one was expected to wrap ones primitive data type with the corresponding primitive wrapper object, as shown above. Autoboxing : Since Java 1.5, one may write as below and the compiler will automatically create the wrap object. The extra step of wrapping the primitive is no longer required. It has been automatically boxed up on your behalf.
Points to ponder:
Keep in mind that the compiler still creates the missing wrapper code, so one doesnt really gain anything performance-wise. Consider this feature a programmer convenience, not a performance booster.
int age = 23;
Unboxing : Uses the same process in reverse. Study the following code for a moment. The if statement requires a boolean primitive value, yet it was given a Boolean wrapper object. No problem! Java 1.5 will automatically unbox this.
Boolean canMove = new Boolean(true); if ( canMove ) { System.out.println( "This code is legal in Java 1.5" ); }
C ATEGORY:JAVA P ROGRAMMING14
14
106
19 java.lang.String
{{#ifeq: none Types Java Pro../tmp/9.png gramming Figure String 9 T YPES1 }} {{#ifeq: none Classes, Objects and Types C LASSES , OBJECTS AND
T YPES2
Figure 10 }}
19.1 java.lang.String
String is a special class built into the Java language dened in the java.lang package.
The String class represents character strings. String literals in Java programs, such as "abc", are implemented as instances of this class. For example:
String str = "This is string literal";
On the right hand side a String object is created represented by the string literal. Its object reference is assigned to the str variable. Strings are immutable; that is, they cannot be modied once created. Whenever it looks as if a String object was modied, a new String was actually created and the old one was thrown away. The Java language provides special support for the string concatenation operator ( + ), and for conversion of other objects to strings. For example:
String str = "First part" + " second part"; // --- Is the same as: String str = "First part second part";
107
java.lang.String
Each Java object has the String toString() inherited from the Object class. This method provides a way to convert objects into Strings. Most classes override the default behavior to provide more specic (and more useful) data in the returned String. The String class provides a nice set of methods for string manipulation. Since String objects are immutable, all methods return a new String object. For example:
name = name.trim();
The trim() method returns a copy of the string with leading and trailing whitespace removed. Note that the following would do nothing useful:
name.trim(); // wrong!
This would create a new trimmed string and then throw it away. Study the String class and its methods carefully. Strings are ubiquitous in Java; it will serve you well to know how to manipulate them skillfully.
On the ( + ) operation a new String object is created at each iteration. Suppose coll contains the elements ["Foo", "Bar", "Bam", "Baz"]. The method creates ve Strings ("", "Foo ", "Foo Bar ", "Foo Bar Bam ", and "Foo Bar Bam Baz") even though only last one is actually useful.
108
Comparing Strings
Instead use S TRING B UFFER3 , as shown below, where only one S TRING B UILDER4 object is created: To avoid unnecessary memory use like this, use the S TRING B UFFER5 or S TRING B UILDER6 class. They provide similar functionality to Strings, but store their data in a mutable way. Also because object creation is time consuming, using StringBuffer or StringBuilder produces much faster code.
public String convertToString(Collection<String> coll) { StringBuilder buf = new StringBuilder(); for(String oneElem : coll) // loops through every element in coll { buf.append(oneElem); buf.append(" "); } return buf.toString();
StringBuilder was introduced in Java 5. Unlike StringBuffer, StringBuilder isnt thread safe, so you cant use it in more than one thread (see the chapter on C ONCURRENCY7 ). However, because it doesnt have to worry about synchronization, StringBuilders are faster.
System.out.println("Match Found");
To test for equality, use the equals(Object) method inherited by every class and dened by String to return true if and only if the object passed in is a String containing the exact same data.
3 4 5 6 7
H T T P :// E N . W I K I B O O K S . O R G / W I K I /J A V A %20P R O G R A M M I N G %2FAPI%2F J A V A . L A N G . ST R I N GBU F F E R H T T P :// E N . W I K I B O O K S . O R G / W I K I /J A V A %20P R O G R A M M I N G %2FAPI%2F J A V A . L A N G . ST R I N GBU I L D E R H T T P :// E N . W I K I B O O K S . O R G / W I K I /J A V A %20P R O G R A M M I N G %2FAPI%2F J A V A . L A N G . ST R I N GBU F F E R H T T P :// E N . W I K I B O O K S . O R G / W I K I /J A V A %20P R O G R A M M I N G %2FAPI%2F J A V A . L A N G . ST R I N GBU I L D E R H T T P :// E N . W I K I B O O K S . O R G / W I K I /J A V A %20P R O G R A M M I N G %2FC O N C U R R E N T P R O G R A M M I N G
109
java.lang.String
To order String objects, use the compareTo() method, which can be accessed wherever we use a String datatype. Lets take a look at an example:
String myString = "Hello World!"; //... if(myString.compareTo("Hello World!") == 0 ) { System.out.println("Match Found");
This snippet of code is comparing the String variable myString to "Hello World". The compareTo method returns a negative, zero, or positive number if the parameter is less than, equal to, or greater than the object on which it is called. If myString was to be different, even in the slightest manner we will get a value above or below 0 depending on the exact difference. The result is negative if this String object lexicographically precedes the argument string. The result is a positive integer if this String object lexicographically follows the argument string. Take a look at the JAVA API8 for more details.
8 9
110
Creating substrings
String person = "Brown, John:100 Yonge Street, Toronto:(416)777-9999"; ... String[] personData = person.split( ":" ); ... String name = personData[0]; String address = personData[1]; String phone = personData[2];
An other useful application could be to split the String text based on the new line character, so you could process the text line by line.
In this example, substr would return "fee". As previously discussed, the index of the rst character in a string is 0. By counting from there, it is apparent that the character in index 3 is the second "f" in "coffee". This is known as the beginIndex. All characters from the beginIndex until the end of the string will be copied into the new substring. The second method involves a user-dened beginIndex and endIndex. For example:
String str = "supporting"; String substr = str.substring(3,7);
The string returned by substr would be "port". Please note that the endIndex is not inclusive. This means that the last character will be of the index endIndex-1. Therefore, in this example, every character from index 3 to index 6, inclusive, was copied into the substring.
Note: "Substring" is considered to be one word. This is why the method name does not seem to
follow the common syntax of Java. It is easy to mistake the method substr() for subStr() (which does not exist and would return with a syntax error on compilation). Just remember that this style only applies to methods or other elements that are made up of more than one word.
111
java.lang.String
In this example, a call to a.toLowerCase() would return a result of "wikibooks", and b.toUpperCase() would return "WIKIPEDIA".
10 11 12 13 14
112
20 Arrays
20.1 Intro to Arrays
An array is similar to a table of data, keyed by number. In Java an array is an object like all other objects. Look at the following program: UNKNOWN TEMPLATE "Java_Code_File" Copy the code and compile it. The program will ask you to enter some names then reprints the names in order. It demonstrates three major aspects of arrays: how to dene an array, how to set data, and how to access it. The code String[] names = new String[numNames]; tells Java to create an array of size numNames that will store Strings. To set data, use names[x] = data where x is the index to access. Note that all Java arrays start at 0 and go to (array size - 1). Thus, if you dimension an array to size 10, the highest index is 9.
All elements of the array will be automatically initialized with the default value for that datatype. This is false for booleans, 0 for all numeric primitive types, and null for all reference types. So for example, the previous note created an array of DataType references, all of which are initialized to null. To access an item, use the syntax variable[i] where i is the index To set an item, use the syntax variable[i] = data To nd the length of an array, use the syntax variable.length
{"10", "11", "12", "13", "14"}, {"20", "21", "22", "23", "23"} };
113
Arrays
...
int [][] twoDimIntArray =
{ {00, 01, 02, 03, 04}, {10, 11, 12, 13, 14}, {20, 21, 22, 23, 24} };
Note that the above "twoDimArray" is equivalent to the following more verbose code:
String [][] twoDimArray = new String[3][];
for (int i = 0; i < twoDimArray.length; i++) { twoDimArray[i] = new String[5]; for (int j = 0; j < twoDimArray[i].length; j++) twoDimArray[i][j] = "" + i + j; }
In the above example we dened an array which has three elements, each element contains an array having 5 elements. We could create the array having the 5 elements rst and use that one in the initialize block.
String [] oneDimArray = {"00", "01", "02", "03", "04"}; String [][] twoDimArray = { oneDimArray ,
{"10", "11", "12", "13", "14"}, {"20", "21", "22", "23", "24"} };
Since they are arrays of array references, these multi-dimensional arrays can be "jagged" (i.e. subarrays can have different lenghts), or the subarray reference can even be null. Consider
String [][] weirdTwoDimArray = { {"10", "11", "12"},
114
And can reference the variable (and use the data stored in it) by its name. For example, to create an int primitive type value, named year that stores 2007;
year = 2007;
To access the data in year, use the variable in place of the number.
System.out.println(year);
Produces
1 2
115
2007
CaseConventions(String id) { }
void method() {
}
void longMethodName() {
} }
21.3 Scope
Java uses block scope, which means that a variable is "un-dened" (and becomes useless) at the end of the block in which it is dened. A block is any section of code within curly braces.
H T T P :// E N . W I K I P E D I A . O R G / W I K I /C A M E L C A S E
116
Scope
Common blocks include class denitions, methods and constructors, if/else blocks, and for, while, and do-while loops.
class BlockScope { int classScope; // valid in all of class BlockScope
BlockScope(int param) { // param is valid only in this constructor int localVariable = 0; // valid only in this constructor }
void someMethod() { int local = 42; // valid only in this method if(local > 0) { boolean positive = true; // valid only within the if block } else {
There are three basic kinds of scope for variables in Java: local variable, declared within a method in a class, valid for (and occupying storage only for) the time that method is executing. Every time the method is called, a new copy of the variable is used. instance variable, declared within a class but outside any method. It is valid for and occupies storage for as long as the corresponding object is in memory; a program can instantiate multiple objects of the class, and each one gets its own copy of all instance variables. This is the basic data structure rule of Object-Oriented programming; classes are dened to hold data specic to a "class of objects" in a given system, and each instance holds its own data. static variable, declared within a class as static, outside any method. There is only one copy of such a variable no matter how many objects are instantiated from that class. C ATEGORY:JAVA P ROGRAMMING4
117
118
22 Generics
Generics were added to the Java language syntax in version 1.5. This means that code using Generics will not compile with Java 1.4 and less. Java was long criticized for the need to explicitly type-cast an element when it was taken out of a "container/collection" class. There was no way to enforce that a "collection" class contains only one type of object (e.g., to forbid at compile time that an Integer object is added to a Collection that should only contain Strings). This is now possible since Java 1.5. In the rst couple of years of Java evolution, Java did not have a real competitor. This has changed by the appearance of Microsoft C#. With Generics Java is better suited to compete against C#. Similar constructs to Java Generics exist in other languages, see G ENERIC PROGRAMMING1 for more information.
{ private Person<T> person; ... } ... // --- Create an Employee person --Person<Employee> emplPerson = new Person<Employee>(); ... // --- Create a Customer person --Person<Customer> custPerson = new Person<Customer>();
H T T P :// E N . W I K I P E D I A . O R G / W I K I /G E N E R I C %20 P R O G R A M M I N G
119
Generics
for a method : Just like class declarations, method declarations can be generic--that is, parameterized by one or more type parameters.
public static <T> void assign( Person<T> person, T obj )
{ person.setPerson( obj ); }
use of generics is optional : For backwards compatibility with pre-Generics code, it is okay to use generic classes without the generics type specication thing (<T>). In such a case, when you retrieve an object reference from a generic object, you will have to manually typecast it from type Object to the correct type. The compiler should also warn about unsafe operations.
22.2 Introduction
Java is a strongly typed language. Thats one of the reasons why it is so easy to use. Many potential problems are caught by the compiler. One area where Java was criticized was regarding the container objects. Container objects are objects that contain other objects. Before Generics were introduced there was no way to ensure that a container object contains only one type of objects. When an object was added to a container, it was automatically cast to Java Object. When it was taken out an explicit cast was needed. Normally an explicit cast is checked by the compiler.
String st = "This is a String";
But in the case of container classes, the compiler was not able to catch an invalid type casting.
1 Collection collString = new ArrayList(); 2 collString.add( "This is a String" ); ... 3 Integer integer = (Integer) collString.get(0);
Just looking at line 3, we do not know what type of objects collString contains. If that contains Integers then the code is ne. The below code using Generic:
Collection<String> collString = new ArrayList<String>(); collString.add( "This is a String" ); ... Integer integer = (Integer) collString.get(0); // --- Compilation Error
collString is a container object, that can contain only String objects, nothing else, so when we get
out an element it can be casted only to class that normally a String can be casted. With Generics, Java strict type checking can be extended to container objects. Using Generics with container classes, gives an impression that a new container type is created, with each different type
120
With generics:
Collection<Customer> collCustomer = new ArrayList<Customer>(); collCustomer.add( new Customer() ); ... Collection<Object> collObject = collCustomer; // --- Compilation Error
Both collObject and collCustomer have the same type, BUT it is against the Generic rule, that is collCustomer can contain only Customer objects, and collObject can contain only Object object. So there is an additional check to the normal type checking, the type of the parameter type has to be matched too.
There is only one Class object created. In fact, at runtime, both these objects appear as the same type (both ArrayLists). The generics type information is erased during compilation (type erasure). This means, for example, that if you had function that takes Collection<T> as an argument, and that collection happened to be empty, your function would have no way of instantiating another T object, because it doesnt know what T was. The Class class itself is generic since Java 1.5.
121
Generics
public nal class Class<T> extends Object implements Serializable, GenericDeclaration, Type,
AnnotatedElement { ... }
The T type here represents the type that is handed to the Class object. The T type will be substituted with the class being loaded.
22.4 Class<T>
Since Java 1.5, the class java.lang.Class is generic. It is an interesting example of using genericness for something other than a container class. For example, the type of String.class is Class<String>, and the type of Serializable.class is Class<Serializable>. This can be used to improve the type safety of your reection code. In particular, since the newInstance() method in Class now returns a T, you can get more precise types when creating objects reectively. Now we can use the newInstance() method to return a new object with exact type, without casting. :
Customer cust = Utility.createAnyObject(Customer.class); ... public static <T> T createAnyObject(Class<T> cls) { T ret = null;
try
// - No casting
{ ret = cls.newInstance(); }
catch (Exception e)
// - Casting is needed
{ ret = cls.newInstance(); }
catch (Exception e)
122
Variable Argument
return ret;
Get exact type when getting JavaBean property, using reection : See the following code where the method will return the exact type of the Java Bean property, based on how it will be called.
// --- Using reflection, get a Java Bean property by its name --public static <T> T getProperty(Object bean, String propertyName) { if (bean == null || propertyName == null || propertyName.length() == 0) { return null; } // --- Based on the property name build the getter method name --String methodName = "get" + propertyName.substring(0,1).toUpperCase() + propertyName.substring(1); T property = null;
try
123
Generics
return argList;
The above method can be called with a variable number of arguments, for example:
List<String> list1 = makeAList("One", "Two", "Three"); List<String> list2 = makeAList("One", "Two", "Three", "Four");
In the above example calls, the arguments must be of type String. If we write <? Object> instead of T, then we can pass any kind of objects, regardles of their type:
List<? extends Object> list3 = makeAList("One", 10, new StringBuffer(), new LinkedList());
extends
Note: the number 10 in the above code will be converted (autoboxed) to Integer. See also:
java.util.Arrays.asList(T... a)
Note that we can not add anything to this collection. We can only take out elements of type Object from it. So what is the use of this variable if we can not add anything to the collection it represents? The use of this new construct will be clear when you want to create a generic method that takes any collection.
124
Wildcard Types
For example, to create a collection that may only contain "Serializable" objects, specify:
Collection<? extends Serializable> serColl = new ArrayList<String>();
The above code is valid because, the String class is serializable. Use of a class that is not serializable would cause a compilation error. The following collection can only contain objects that extend the class Animal.
class Dog extends Animal
{ ... } ... // --- Create "Animal Collection" variable --Collection<? extends Animal> animalColl = new ArrayList<Dog>();
"<? super ClassName>" species a restriction on the types of classes that may be used.
For example, to declare a Comparator that can compare Dogs, you use
Comparator<? super Dog> myComparator;
Since Dogs are Animals, you can use this comparator to compare Dogs also. Comparators for any superclass of Dog can also compare Dog; but comparators for any strict subclass cannot.
Comparator<Animal> myAnimalComparator = new AnimalComparator(); static int compareTwoDogs(Comparator<? super Dog> comp, Dog dog1, Dog
125
Generics
The above code is valid because, the Animal class is a supertype of the Dog class. Use of a class that is not a supertype would cause a compilation error. C ATEGORY:JAVA P ROGRAMMING2
126
23 Dening Classes
23.1 Fundamentals
Every class in Java can be composed of the following elements elds - Fields are variables that hold data specic to each object. For example, an employee might have an ID number. (They are also called member variables.) There is one eld for each object of a class. member methods - Member methods perform operations on an object. For example, an employee might have a method to issue his paycheck or to access his name. static elds - Static elds are common to any object of the same class. For example, a static eld within the Employee class could keep track of the last ID number issued. Only one static eld exists for one class. static methods - Static methods are methods that do not affect a specic object. other classes - Sometimes it is useful to contain a class within another one if it is useless outside of the class or should not be accessed outside the class. Constructors - A special method that generates a new object. Parameterized types - Since 1.5, parameterized types can be assigned to a class during denition. The parameterized types will be substituted with the types specied at the classs instantiation. It is done by the compiler. It is similar to the C language macro #dene statement, where a preprocessor evaluates the macros.
public class Employee { that // This defines the Employee class. // The public modifier indicates
// it can be accessed by any other class private static int nextID; one copy of this will exist, are created. // Define a static field. Only // no matter how many Employees
127
Dening Classes
private int myID; stored private String myName; modifier indicates that class can access it. public Employee(String name) pass a name to the constructor { created Employee object. myName = name; myID = nextID; the object nextID++; } public String getName() returns the { return myName; private field myName. } public int getID() { return myID; } public static int getNextID() returns the next ID { another Employee is created. return nextID; }
// Define fields that will be // for each Employee. The private // only code inside the Employee
// This is a member method that // Employee objects name. // Note how it can access the
System.out.println(Employee.getNextID()); Employee a = new Employee("John Doe"); Employee b = new Employee("Jane Smith"); Employee c = new Employee("Sally Brown"); System.out.println(Employee.getNextID()); System.out.println(a.getID() + " : " + a.getName()); System.out.println(b.getID() + " : " + b.getName()); System.out.println(c.getID() + " : " + c.getName()); }
128
Fundamentals
C ATEGORY:JAVA P ROGRAMMING1
129
Dening Classes
130
24 Creating Objects
24.1 Introduction
Before a Java object can be created the class byte code must be loaded from the le system (with .class extension) to memory. This process of locating the byte code for a given class name and converting that code into a Java C LASS1 class instance is known as class loading. There is one C LASS2 created for each type of Java class. All objects in java programs are created on heap memory. An object is created based on its class. You can consider a class as a blueprint, template, or a description how to create an object. When an object is created, memory is allocated to hold the object properties. An object reference pointing to that memory location is also created. To use the object in the future, that object reference has to be stored as a local variable or as an object member variable. The Java Virtual Machine (JVM), keeps track of the usage of object references. If there are no more reference to the object, the object can not be used any more and becomes garbage. After a while the heap memory will be full of unused objects. The JVM collects those garbage objects and frees the memory they allocated, so the memory can be reused again when a new object is created. See below a simple example:
{ // --- Create an object --MyObject obj = new MyObject(); // --- Use the object --obj.printMyValues(); }
The obj contains the object reference pointing to an object created from the MyObject class. The obj object reference is in scope inside the { }. After the } the object becomes garbage. Object references can be passed in to methods, object references can be returned from methods.
1 2
131
Creating Objects
{ // --- Create an MyObject for the first time the application started -MyObject obj = new MyObject(); }
When an object from the MyObject class is created for the rst time. The JVM searches the le system for the denition of the class, that is the Java byte code. The le has the extention of *.class. The CLASSPATH environment variable contains locations where Java classes are stored. The JVM is looking for the MyObject.class le. Depending on which package the class belongs to, the package name will be translated to a directory path. When the MyObject.class le is found, the JVMs class loader loads the class in memory, and creates a Class object. The JVM stores the code in memory, allocates memory for the static variables, and executes any static initialize block. Memory is not allocated for the object member variables at this point, memory will be allocated for them when an instance of the class, an object, is created. There is no limit on how many objects from the same class can be created. Code and static variables are stored only once, no matter how many objects are created. Memory is allocated for the object member variables when the object is created. Thus, the size of an object is determined not by its codes size but by the memory it needs for its member variables to be stored.
{
private int memberVar;
You might think that accessing the private memberVar variable of obj would fail but as this is in the same class this code is legal. The clone() method copies the whole objects memory in one operation. This is much faster than using the new keyword. Object creation with the new keyword is expensive, so if you need to create lots of objects with the same type, performance will be better if you create one object and clone new ones from it. See below a factory method that will return a new object using cloning.
132
HashTable _cacheTemplate = new HashTable; ... /** Clone Customer object for performance reason */ public Customer createCustomerObject() { // --- See if a template object exists in our cache --Customer template = _cacheTemplate.get( "Customer" ); if ( template == null ) { // --- Create template --template = new Customer(); _cacheTemplate.put( "Customer", template ); } return template.clone(); }
Now, lets see how to make the Customer object cloneable. First the Customer class needs to implement the Cloneable Interface. Override and make the clone() method public, as that is protected in the Object class. Call the super.clone()method at the beginning of your clone method. Override the clone() method in all the subclasses of Customer.
public class Customer implements Cloneable
{ ...
public Object clone() throws CloneNotSupportedException
In the above example we used cloning for speed up object creation. An other use of cloning could be to take a snapshot of an object that can change in time. Lets say we want to store Customer objects in a collection, but we want to disassociate them from the live objects . So before adding the object, we clone them, so if the original object changes from that point forward, the added object wont. Also lets say that the Customer object has a reference to an Activity object that contains the customer activities. Now we are facing a problem, it is not enough to clone the Customer object, we also need to clone the referenced objects. The solution: Make the Activity class also cloneable Make sure that if the Activity class has other changeable object references, those has to be cloned as well, as seen below Change the Customer class clone() method as follows:
public class Customer implements Cloneable
{ Activity _activity; ... public Customer clone() throws CloneNotSupportedException { Customer clonedCustomer = (Customer) super.clone(); // -- Clone the object referenced objects --if ( _activity != null )
133
Creating Objects
Note that only mutable objects needs to be cloned. References to unchangeable objects such as String be used in the cloned object without worry.
If the object needs to write or provide a replacement object during serialization, it needs to impement the following two methods, with any access specier:
Object writeReplace() throws ObjectStreamException;
134
Normally, a minor change to the class can cause the serialization to fail. You can still allow the class to be loaded by dening the serialization version id:
private static final long serialVersionUID = 42L;
C ATEGORY:JAVA P ROGRAMMING4
135
Creating Objects
136
25 Interfaces
25.1 Interfaces
Java does not allow you to create a subclass from two classes. There is no multiple inheritance. The major benet of that is that all java objects can have a common ancestor. That class is called Object. All java classes can be up-casted to Object. Example:
class MyObject
{ ... }
When you type the above code, it actually means the following:
class MyObject extends Object // -- The compiler adds extends Object. if not specified { ... }
So it can be guaranteed that certain methods are available in all java classes. This makes the language simpler. To mimic multiple inheritance, java offers interfaces, which are similar to abstract classes. In interfaces all methods are abstract by default, without the abstract key word. Interfaces have no implementation and no variables, but constant values can be dened in interfaces - however, a single class can implement as many interfaces as required.
public interface MyInterface
{
public static nal String CONSTANT = "This value can not be changed"; public String methodOne(); // This method must be implemented by the class that implements this interface
... } ...
public class MyObject implements MyInterface
137
Interfaces
1 2 3
138
{
static private int counter;
...
public AClass()
{
return counter;
} }
The counter variable is incremented each time an object is created. Public static variable should not be used, as these become GLOBAL variables that can be accessed from everywhere in the program. Global constants can be used, however. See below:
static public nal String CONSTANT_VAR = "Const";
Static methods can be used for utility functions or for functions that do not belong to any particular object. For example:
139
public Match
{ ...
public static addTwoNumbers( int par1, int par2 )
{
return par1 + par2;
} }
1 2
140
27 Destroying Objects
Unlike in many other object-oriented programming languages, Java performs automatic garbage collection - any unreferenced objects are automatically erased from memory - and prohibits the user from manually destroying objects.
27.1 nalize()
When an object is garbage-collected, the programmer may want to manually perform cleanup, such as closing any open input/output streams. To accomplish this, the nalize() method is used. Note that nalize() should never be manually called, except to call a super class nalize method from a derived class nalize method. Also, we can not rely on when the nalize() method will be called. If the java application exits before the object is garbage-collected, the nalize() method may never be called.
protected void finalize() throws Throwable
{
try {
doCleanup(); // Perform some cleanup. If it fails for some reason, it is ignored. } nally { super.finalize(); //Call finalize on the parent object } }
The garbage-collector thread runs in a lower priority than the other threads. If the application creates objects faster than the garbage-collector can claim back memory, the program can run out of memory. The nalize method is required only if there are resources beyond the direct control of the Java Virtual Machine that need to be cleaned up. In particular, there is no need to explicitly close an OutputStream, since the OutputStream will close itself when it gets nalized. Instead, the nalize method is used to release either native or remote resources controlled by the class. C ATEGORY:JAVA P ROGRAMMING1
141
Destroying Objects
142
143
144
29 Arrays
29.1 Intro to Arrays
An array is similar to a table of data, keyed by number. In Java an array is an object like all other objects. Look at the following program: UNKNOWN TEMPLATE "Java_Code_File" Copy the code and compile it. The program will ask you to enter some names then reprints the names in order. It demonstrates three major aspects of arrays: how to dene an array, how to set data, and how to access it. The code String[] names = new String[numNames]; tells Java to create an array of size numNames that will store Strings. To set data, use names[x] = data where x is the index to access. Note that all Java arrays start at 0 and go to (array size - 1). Thus, if you dimension an array to size 10, the highest index is 9.
All elements of the array will be automatically initialized with the default value for that datatype. This is false for booleans, 0 for all numeric primitive types, and null for all reference types. So for example, the previous note created an array of DataType references, all of which are initialized to null. To access an item, use the syntax variable[i] where i is the index To set an item, use the syntax variable[i] = data To nd the length of an array, use the syntax variable.length
{"10", "11", "12", "13", "14"}, {"20", "21", "22", "23", "23"} };
145
Arrays
...
int [][] twoDimIntArray =
{ {00, 01, 02, 03, 04}, {10, 11, 12, 13, 14}, {20, 21, 22, 23, 24} };
Note that the above "twoDimArray" is equivalent to the following more verbose code:
String [][] twoDimArray = new String[3][];
for (int i = 0; i < twoDimArray.length; i++) { twoDimArray[i] = new String[5]; for (int j = 0; j < twoDimArray[i].length; j++) twoDimArray[i][j] = "" + i + j; }
In the above example we dened an array which has three elements, each element contains an array having 5 elements. We could create the array having the 5 elements rst and use that one in the initialize block.
String [] oneDimArray = {"00", "01", "02", "03", "04"}; String [][] twoDimArray = { oneDimArray ,
{"10", "11", "12", "13", "14"}, {"20", "21", "22", "23", "24"} };
Since they are arrays of array references, these multi-dimensional arrays can be "jagged" (i.e. subarrays can have different lenghts), or the subarray reference can even be null. Consider
String [][] weirdTwoDimArray = { {"10", "11", "12"},
146
30 Collection Classes
Collections are a group of objects bound together by a common characteristic. Java has various built-in classes to support the collection of objects, either of the same type or general. The most basic construct to work with is the array of which you will come to know of in a SECTION1 later in this chapter.
... Collection coll1 = new ArrayList(); Collection coll2 = new HashSet(); ... < Use coll1 & coll2 >
In the above there are two collections. The usage of the collections are the same, the implementations are different. If the existing collection implementations do not meet your needs, you can write your version of the implementation. Your version of the implementation just needs to implement the same java.util.Collection interface, then you can switch to using your implementation and the code that is using the collection does not need to be changed.
import java.util.Collection; import com.yourcomp.util.YourCollectionImpl;
... Collection coll1 = new YourCollectionImpl(); Collection coll2 = new YourCollectionImpl(); ... < Use coll1 & coll2 >
The Java JDK collection implementations are quite powerful and good, so it is unlikely that you will need to write your own. All collections contain object references. Because of that, if the object is changed after it was put in the collection, the object that is in the collection also changes. The object is not really in the collection, only the object reference is. It is not guaranteed that the objects inside the collections
147
Collection Classes
wont change. This is an issue only if you put an actively used object in the collection. In that case when you are adding an object that could change any time you need to make a copy or clone of the object. A new object will be created and its reference will be put in the collection. In that case there will be no object references outside of the collection, so the objects inside the collection can only be changed if we take out an object reference from the collection. Aside from the java.util.Collection interface, the Java JDK has the java.util.Map interface as well. This denes key value mappings. Implementations of the Map interface do not contain collections of objects. Instead they contain collections of key->value mappings.
import java.util.Map; import java.util.Hashtable;
All collections need to have the same basic operations. Those are: Adding element(s) to the collection Removing element(s) from the collection Obtaining the number of elements in the collection Listing the contents of the collection, (Iterating through the collection)
Before selecting a particular collection implementation, ask the following question: Can my collection contain the same elements, i.e. are duplicates allowed? Can my collection contain the null element? Should the collection maintain the order of the elements? Is the order important in any way? How do you want to access an element? By index, key or just with an iterator? Does the collection need to be synchronized? From a performance perspective, which one needs to be faster, updates or reads? From a usage perspective, which operation will be more frequent, updates or reads?
Once you know your needs, you can select an exsisting implementation. But rst decide if you need a Collection, or a Map.
30.2 Generics
Since JDK version 1.5 an enhancement to the type system of the Java language has been added. It is called Generics. Most often Generics will be used with the collection classes. parameterized type <E> : All collection implementations since 1.5 now have one parameterized type <E> added. The E refers to an Element type. When a collection is created the actual Element type will replace the E. Objects put into a collection are upcasted to Object class. It means that you need to cast the object reference back when you get an element out from the collection. It also means that you need to know the type of the object when you taking it out. For this reason we usually add objects of the
148
Collection or Map
same type to a collection. If a collection contains different types of objects, we will have difculty nding out the type of the objects obtained from a collection at run time. With the use of the parameterized type <E>, the Element-type that can be put into the collection can be specied when the collection object is created.
Collection<Integer> ageList = new ArrayList<Integer>(); ageList.add( new Integer(46) ); // --- Integer can be added ageList.add( "50" ); // --- Compilation error, ageList can have only Integers inside
ageList is a collection that can contain only Integer objects as elements. No casting is required when we take out an element.
Integer age = ageList.get(0);
30.3.1 Collection
Use the Collection interface if you need to keep related (usually the same type of) objects together in a collection where you can: Search for a particular element List the elements Maintain and/or change the order of the elements by using the collection basic operations (Add, Remove, Update,..) Access the elements by an index number The advantages of using the Collection interface are: Gives a generic usage, as we talked about above, it is easy to switch implementation It makes it easy to convert one type of collection to an other. The Collection interface denes the following basic operations: boolean add( E o );
2 Chapter 22 on page 119
149
Collection Classes
boolean addAll( Collection c ); boolean remove( Object o ); boolean removeAll( Collection c ); boolean retainAll( Collection c );
The methods above return true if the collection has changed due to the operation. Note that in addAll() we can add any type of collection. This is the beauty of using the Collection interface. You can have a LinkedList and just call the addAll(list) method, passing in a list. You can pass in a Vector, an ArrayList, a HashSet, a TreeSet, a YourImpOfCollection, ... All those different type of collections will be magically converted to a LinkList. Lets have a closer look at this magic. The conversion is easy because the Collection interface denes a standard way of looping through the elements. The following code is a possible implementation of addAll() method of the LinkList.
import java.util.Collection import java.util.Iterator
...
public String addAll( Collection coll )
while( iter.hasNext() ) {
_linkList.add( iter.next() );
The above code just iterates through the passed in collection and adds the elements to the link list. You do not have to do that, since that is already dened. What you might need to code for is to loop through a Customer collection:
import java.util.Collection import java.util.Iterator import java.yourcompany.Customer
...
public String printCustomerNames( Collection customerColl )
while( iter.hasNext() ) {
Customer cust = (Customer) iter.next();
150
Collection or Map
Notice two things: The above code will work for all type of collections. We have to know the type of objects inside the collection, because we call a method on it.
30.3.2 Map
A map, sometimes also called an Associated Array or a Dictionary, can be thought of as an array where the index need not be an integer. Use the Map interface if you need to keep related objects together in a Map where you can: Access an element by a key object Map one object to other java.util.Map<K,V> : maps keys to values. A map cannot contain duplicate keys; each key can map to at most one value. The Map interface provides three collection views, which allow a maps contents to be viewed as a set of keys, collection of values, or set of key-value mappings. The key is usually a non-mutable object. The value object however can be a mutable object. java.util.SortedMap<K,V> : same as the Map interface, plus the keys in the Map are sorted.
151
Collection Classes
There is no direct implementation for the java.util.Collection interface. The Collection interface has ve sub interfaces. Those are: java.util.Set<E> : contains unique elements, so duplicates not allowed. It is similar to a mathematical Set. java.util.List<E> : elements are put in the list in a certain order, and can be accessed by an index. Duplicates are allowed, the same element can be added to a list. java.util.SortedSet<E> : same as the Set interface; plus the elements in the SortedSet are sorted java.util.Queue<E> : queues provide additional insertion, extraction, and inspection operations. There are FIFO (rst in, rst out) and LIFO (last in, rst out) queues. java.util.BlockingQueue<E> : waits for the queue to become non-empty when retrieving an element, and waits for space to become available in the queue when storing an element. Best used for producer-consumer queues.
152
30.4.1 Set
The basic implementation of the Set interface is the HashSet.
../tmp/13.jpg
Figure 13
java.util.TreeSet<E>: Elements are sorted, not synchronized. null not allowed java.util.HashSet<E> : Not synchronized. Allows the null elements java.util.CopyOnWriteArraySet<E> : Thread safe, a fresh copy is created during modication operation. Add, update, delete are expensive.
153
Collection Classes
java.util.EnumSet<E extends Enum<E>> : All of the elements in an enum set must come from a single enum type that is specied, explicitly or implicitly, when the set is created. Enum sets are represented internally as bit vectors. java.util.LinkedHashSet<E> : Same as HashSet, plus denes the iteration ordering, which is the order in which elements were inserted into the set.
Detecting duplicate objects in Sets
Set cannot have duplicates in it. You may wonder how duplicates are detected when we are adding an object to the Set. We have to see if that object exists in the Set or not. It is not enough to check the object references, the objects values have to be checked as well. To do that, fortunately, each java object has the boolean equal(Object obj);3 , method available inherited from Object. You need to override it. That method will be called by the Set implementation to compare the two objects to see if they are equal or not. There is a problem, though. What if I put two different type of objects to the Set. I put an Apple and an Orange. They can not be compared. Calling the equal()4 method would cause a ClassCastException. There are two solutions to this: Solution one : Override the int hashCode()5 method and return the same values for the same type of objects and return different values for different type of objects. The equal()6 method is used to compare objects only with the same value of hashCode. So before an object is added, the Set implementation needs to: nd all the objects in the Set that has the same hashCode as the candidate object hashCode and for those, call the equal()7 methods passing in the candidate object if any of them returns true, the object is not added to the Set. Solution two : Create a super class for the Apple and Orange, lets call it Fruit class. Put Fruits in the Set. You need to do the following: Do not override the equals() and hashCode() methods in the Apple and Orange classes Create appleEquals() method in the Apple class, and create orangeEquals() method in the Orange class Override the hashCode() method in the Fruit class and return the same value, so the equals() is called by the Set implementation Override the equals() method in the Fruit class for something like this.
public boolean equals( Object obj ) {
3 4 5 6 7
H T T P :// E N . W I K I B O O K S . O R G / W I K I /J A V A %20P R O G R A M M I N G %2FAPI%2F J A V A . L A N G .O B J E C T % 23 E Q U A L S %28%29%20M E T H O D H T T P :// E N . W I K I B O O K S . O R G / W I K I /J A V A %20P R O G R A M M I N G %2FAPI%2F J A V A . L A N G .O B J E C T %23 H T T P :// E N . W I K I B O O K S . O R G / W I K I /J A V A %20P R O G R A M M I N G %2FAPI%2F J A V A . L A N G .O B J E C T % 23 H A S H C O D E %28%29%20M E T H O D H T T P :// E N . W I K I B O O K S . O R G / W I K I /J A V A %20P R O G R A M M I N G %2FAPI%2F J A V A . L A N G .O B J E C T %23 H T T P :// E N . W I K I B O O K S . O R G / W I K I /J A V A %20P R O G R A M M I N G %2FAPI%2F J A V A . L A N G .O B J E C T %23
154
boolean ret = false; if ( this instanceof Apple && obj instanceof Apple ) { ret = this.appleEquals(obj); } else if ( this instanceof Orange && obj instanceof Orange ) { ret = this.orangeEquals(obj); } else { // --- Can not compare Orange to Apple --ret = false; } return ret;
Note:
only the objects that have the same hashCode will be compared. you are responsible to override the equal() and hashCode() methods. The default implementations in Object wont work. Only override the hashCode()8 method if you want to eliminate value duplicates. Do not override the hashCode()9 method if you know that the values of your objects are different, or if you only want to prevent adding the exactly same object. Beware that the hashCode()10 may be used in other collection implementaions, like in a Hashtable to nd an object fast. Overriding the default hashCode() method may affect performance there. the default hashCodes are unique for each object created, so if you decide not to override the hashCode() method, there is no point overriding the equal() method, as it wont be called.
SortedSet
The SortedSet interface extends the Set Interface. All elements in the SortedSet must implement the Comparable Interface, futher more all elements must be mutually comparable. Note that the ordering maintained by a sorted set must be consistent with equals if the sorted set is to correctly implement the Set interface. This is so because the Set interface is dened in terms of the equals operation, but a sorted set performs all element comparisons using its compareTo (or compare) method, so two elements that are deemed equal by this method are, from the standpoint of the sorted set, equal.
H T T P :// E N . W I K I B O O K S . O R G / W I K I /J A V A %20P R O G R A M M I N G %2FAPI%2F J A V A . L A N G .O B J E C T % 23 H A S H C O D E %28%29%20M E T H O D 9 H T T P :// E N . W I K I B O O K S . O R G / W I K I /J A V A %20P R O G R A M M I N G %2FAPI%2F J A V A . L A N G .O B J E C T % 23 H A S H C O D E %28%29%20M E T H O D 10 H T T P :// E N . W I K I B O O K S . O R G / W I K I /J A V A %20P R O G R A M M I N G %2FAPI%2F J A V A . L A N G .O B J E C T % 23 H A S H C O D E %28%29%20M E T H O D
155
Collection Classes
The SortedSet interface has additional methods due to the sorted nature of the Set. Those are: E first(); -- returns the rst element E last(); -- returns the last element SortedSet headSet(E toElement); -- returns from the rst, to the exclusive toElement SortedSet tailSet(E fromElement); -- returns from the inclusive fromElement to the end SortedSet subSet(E fromElement, E toElement); -- returns elements range from fromElement, inclusive, to toElement, exclusive. (If fromElement and toElement are equal, the returned sorted set is empty.)
30.4.2 List
The List has the following implemenations:
../tmp/14.jpg
Figure 14
156
java.util.Vector<E> : Syncronized, use in multiple thread access, otherwise use ArrayList java.util.Stack<E> : It extends class Vector with ve operations that allow a vector to be treated as a stack. It represents a last-in-rst-out (LIFO) stack of objects. java.util.ArrayList<E> : Non-syncronized, use in single thread environment, otherwise use Vector java.util.LinkedList<E> : Non-syncronized, update operation is faster than other lists, easy to use for stacks, queues, double-ended queues. javax.management.AtributeList<E> : Represents a list of values for attributes of an MBean. The methods used for the insertion of Attribute objects in the AttributeList overrides the corresponding methods in the superclass ArrayList. This is needed in order to insure that the objects contained in the AttributeList are only Attribute objects. javax.management.relation.RoleList<E> : A RoleList represents a list of roles (Role objects). It is used as parameter when creating a relation, and when trying to set several roles in a relation (via setRoles() method). It is returned as part of a RoleResult, to provide roles successfully retrieved. javax.management.relation.RoleUnresolvedList<E> : A RoleUnresolvedList represents a list of RoleUnresolved objects, representing roles not retrieved from a relation due to a problem encountered when trying to access (read or write to roles). The basic implemenation of the List interface is the ArrayList. The ArrayList is not syncronized, not thread safe. Vector is syncronized, and thread safe. Vector is slower, because of the extra overhead to make it thread safe. When only one thread is accessing the list, use the ArrayList. Whenever you insert or remove an element from the list, there are extra overhead to reindex the list. When you have a large list, and you have lots of insert and remove, consider using the LinkedList. The name LinkList implies a special data structure where the elements/nodes are connected by pointers. To remove an element from the link list the pointers need to be rearranged.
Head Node 1 Node 2 Node n ______ | Size | _________________ _______________ _____________ |______| | | point | | | point | | | | | First|-------->| Data | to next |------>| Data | to next|-- ... -->| Data | null | | elem | |______|_________| |______|________| |______|______| |______| | | Last |----------------------------------------------------------------|_elem_|
157
Collection Classes
______ ___________________...________ | Size | _________________ | _______________ _|____________ |_- 1__| | | point | | | | point | | | | | First|-------->| Data | to next |---| Data | to next| | Data | null | | elem | |______|_________| |______|________| |______|______| |______| | | Last |----------------------------------------------------------------|_elem_|
30.4.3 Queue
The Queue interface adds the following operations to the Collection interface:
E element()
E poll() E remove()
Retrieves, but does not remove, the head of this queue. This method differs from the peek method only in that it throws an exception if this queue is empty Inserts the specied element into this queue, if possible. Retrieves, but does not remove, the head of this queue, returning null if this queue is empty Retrieves and removes the head of this queue, or null if this queue is empty Retrieves and removes the head of this queue. This method differs from the poll method in that it throws an exception if this queue is empty.
158
Map Classes
java.util.PriorityQueue<E> : orders elements according to an order/priority specied at construction time, null element is not allowed. java.util.concorrent.ArrayBlockingQueue<E> : orders elements FIFO; syncronized, Figure 15 thread safe. java.util.concorrent.SyncronousQueue<E> : each put must wait for a take, and vice versa, does not have any internal capacity, not even a capacity of one, an element is only present when you try to take it; you cannot add an element (using any method) unless another thread is trying to remove it
159
Collection Classes
Figure 16
java.util.TreeMap<E>: guarantees that the map will be in ascending key order, sorted according to the natural order for the keys class, not-syncronized. java.util.HashMap<E> : is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls java.util.concurrent.ConcurrentHashMap : same Hashtable, plus retrieval operations (including get) generally do not block, so may overlap with update operations (including put and remove). java.util.Hashtable<E> : Syncronized, null can not be used as key java.util.WeakHashMap<E> : entry in a WeakHashMap will automatically be removed when its key is no longer in ordinary use. Nonsyncronized. java.util.LinkedHashMap<E> : This linked list denes the iteration ordering, which is normally the order in which keys were inserted into the map (insertion-order). Note that insertion order is not affected if a key is re-inserted into the map. java.util.IdentityHashMap : This class implements the Map interface with a hash table, using reference-equality in place of object-equality when comparing keys (and values). In other words, in an IdentityHashMap, two keys k1 and k2 are considered equal if and only if
160
(k1==k2). (In normal Map implementations (like HashMap) two keys k1 and k2 are considered equal if and only if (k1==null ? k2==null : k1.equals(k2)).) Not-syncronized. java.util.EnumMap : All of the keys in an enum map must come from a single enum type that is specied, explicitly or implicitly, when the map is created. Enum maps are represented internally as arrays. This representation is extremely compact and efcient. Not-syncronized.
java.util.ArrayList
Set
Map
java.util.LinkList java.util.concurrent.CopyOnWriteArrayList java.util.TreeSet java.util.HashSet java.util.LinkHashSet java.util.concurrent.CopyOnWriteArraySet java.util.TreeMap java.util.Hashtable java.util.HashMap java.util.concurrent.ConcurrentHashMap java.util.LinkedHashMap java.util.IdentityHashMap java.util.EnumMap
161
Collection Classes
Figure 17
The following UML class diagram shows the Map interfaces and their implementations.
Figure 18
162
External links
11 12
163
Collection Classes
164
At the above line the current method execution is interrupted and the created exception object is thrown back to the caller. The exception object should contain the information about the reason of the interruption. The caller of the method catches the exception by the catch keyword.
catch (ExceptionClass e) { // --- What to do with this interruption ??? --}
Sometimes just the name of the exception class is enough to know the reason of the interruption.
165
1. A thrown exception object, can be caught by the catch keyword with specifying the exception objects class or its super-class. 2. When there are a list of catch clauses, it is evaluated sequentially, applying the rst rule. If there is a catch, the following catch clauses are ignored. 3. If there is a catch clause in the list, which will never be executed, because its super-class are listed before it, the compiler will give an error message. 4. The compiler enforce that all Exception and its sub-class exceptions must be handled by the programmer, except the RuntimeException and its sub-classes. 5. If the try block would never throw an exception that is specied in the catch list, the compiler gives an error.
There are some special exceptions that used by the JVM, those are the sub-classes of java.lang.Error. We are not suppose the catch them. So we should use the following code to catch all application, and runtime exceptions.
catch (Exception e) { // --- I caught all application and runtime exceptions --log_it( e ); // --- I dont know how to handle this, so I throw it again --throw e; }
166
The NullPointerException is caught by the rst catch clause, the following catch clauses are ignored. The second catch clause will catch all RuntimeExceptions, except the NullPointerException, because that will be caught by the rst clause. All exceptions that are dened by the application, will be caught by the last catch clause, see below.
catch (NullPointerException e) { // --- I caught a Nulpointer ex. --log_it( e ); // --- I dont know how to handle this, so I throw it again --throw e; } catch (RuntimeException e) { // --- I caught runtime ex. but not NullPointer --log_it( e ); // --- I dont know how to handle this, so I throw it again --throw e; } catch (Exception e) { // --- I caught all application but not Runtime exceptions --log_it( e ); // --- I dont know how to handle this, so I throw it again --throw e; }
167
The above code wont compile, because the try block does not throw exception. The compiler can be fooled with the following code.
168
public void methodA() throws SomeException, AnotherException { //methodbody } public void methodB() throws CustomException { //Methodbody } public void methodC() { methodB(); methodA(); }
In the code sample, methodC is invalid. Because methodA and methodB pass (or throw) exceptions, methodC must be prepared to handle them. This can be handled in two ways: a try - catch block, which will handle the exception within the method and a throws clause which would in turn throw the exception to the caller to handle. The above example will cause a compilation error, as Java is very strict about exception handling. So the programmer forced to handle any possible error condition at some point. A method can do two things with an exception. Ask the calling method to handle it by the throws declaration. Or handle the exception inside the method by the try-catch block. To construct a throws declaration, add throws ExceptionName (additional exceptions can be added with commas). To construct a try - catch block, use the following syntax
... try { //Possibly exception-causing code } catch (TheException e) { //Handle the exception } finally { //Optional. Executes regardless of exceptions thrown }
169
The original code can be modied to work correctly in multiple ways. For example, the following:
public void methodC() throws CustomException, SomeException { try { methodB(); } catch (AnotherException e) { //handle it } methodA(); }
The AnotherException from methodB will be handled locally, while CustomException and SomeException will be thrown to the caller to handle it.
}
catch( Exception e ) {
// --- The "thrown" object is the same what is specified at the catch-block -}
}
catch( Exception e ) {
170
Runtime Exceptions
There can be more than one catch-block for a try-block. The catching blocks evaluated sequentially one by one. If a catch-block catch the exception, the others will not be evaluated. Example:
try { throw new NullPointerException( "This will be caught below" );
}
catch( Exception e ) {
Because NullPointerException is subclass of the Exception class. All NullPointerExceptions will be caught by the rst catch-block. Instead the above code should be rewritten as follows:
try { throw new NullPointerException( "This will be caught below" );
}
catch( NullPointerException e ) {
here ---
// --- Any other exception except the NullPointerException will be caught here -}
31.4.1 NullPointerException
NullPointerException is a RuntimeException. In Java, a special null can be assigned to an object reference. NullPointerException is thrown when an application attempts to use an object reference, having the null value. These include: Calling an instance method on the object referred by a null reference.
171
Accessing or modifying an instance eld of the object referred by a null reference. If the reference type is an array type, taking the length of a null reference. If the reference type is an array type, accessing or modifying the slots of a null reference. If the reference type is a subtype of Throwable, throwing a null reference.
Applications should throw instances of this class to indicate other illegal uses of the null object.
Object obj = null;
... obj.toString();
The above code shows one of the pitfall of Java, and the most common source of bugs. No object is created and the compiler does not detect it. NullPointerException is one of the most common exceptions thrown in Java. why do we need null ? : The reason we need it is because many times we need to create an object reference, before the object itself is created. Object references cannot exist without a value, so we assign the null value to it.
public Customer getCustomer()
{ Customer customer = null; try { ... customer = createCustomer(); ... } catch ( Exception e) { ... } return customer; }
In the above code we want to create the Customer inside the try-block, but we also want to return the object reference to the caller, so we need to create the object reference outside of the try-block, because of the scoping rule in Java. This is one of the pitfall of Java.
172
java.lang.Throwable : The Throwable class is the superclass of all errors and exceptions in the Java language. Only objects that are instances of this class (or one of its subclasses) are thrown by the Java Virtual Machine or can be thrown by the Java throw statement. A throwable contains a snapshot of the execution stack of its thread at the time it was created. It can also contain a message string that gives more information about the error. Finally, it can contain a cause: another throwable that caused this throwable to get thrown. The cause facility is new in release 1.4. It is also known as the chained exception facility, as the cause can, itself, have a cause, and so on, leading to a "chain" of exceptions, each caused by another java.lang.Error : An Error indicates serious problems that a reasonable application should not try to catch. Most such errors are abnormal conditions. java.lang.Exception : The class Exception and its subclasses are a form of Throwable that indicates conditions that a reasonable application might want to catch. Also this is the class that a programmer may want to extend when adding business logic exceptions. java.lang.RuntimeException : RuntimeException is the superclass of those exceptions that can be thrown during the normal operation of the Java Virtual Machine. A method is not required to declare in its throws clause any subclasses of RuntimeException that might be thrown during the execution of the method but not caught. java.lang.NullPointerException : Thrown when an application attempts to use null in a case where an object is required.
Figure 19
173
C ATEGORY:JAVA P ROGRAMMING5 This page describes some techniques for preventing NullPointerException. It does not describe general techniques for how you should program Java. It is of some use, to make you more aware of null values, and to be more careful about generating them yourself. Note that this list is not complete - there are no rules for preventing NullPointerException entirely in Java, because the standard libraries have to be used, and they can cause NullPointerExceptions. Also, it is possible to observe an uninitialised nal eld in Java, so you cant even treat a nal eld as being completely trusted during the objects creation. A good approach is to learn how to deal with NullPointerExceptions rst, and become competent with that. These suggestions will help you to cause less NullPointerExceptions, but they dont replace the need to know about NullPointerExceptions.
something3(s);
{ done=true; something3("yep"); }
1 2 3 4 5
H T T P :// E N . W I K I B O O K S . O R G / W I K I /J A V A %20P R O G R A M M I N G %2FK E Y W O R D S %2F T R Y H T T P :// E N . W I K I B O O K S . O R G / W I K I /J A V A %20P R O G R A M M I N G %2FK E Y W O R D S %2F C A T C H H T T P :// E N . W I K I B O O K S . O R G / W I K I /J A V A %20P R O G R A M M I N G %2FK E Y W O R D S %2F T H R O W S H T T P :// E N . W I K I B O O K S . O R G / W I K I /J A V A %20P R O G R A M M I N G %2FK E Y W O R D S %2F T H R O W H T T P :// E N . W I K I B O O K S . O R G / W I K I /C A T E G O R Y %3AJ A V A %20P R O G R A M M I N G
174
Minimize the use of the new Type[int] syntax for creating arrays of objects
You might also consider replacing null with "" in the rst example, but default values bring about bugs caused by default values being left in place. A NullPointerException is actually better, as it allows the runtime to tell you about the bug, rather than just continue with a default value.
31.8 Minimize the use of the new Type[int] syntax for creating arrays of objects
An array created using new Object[10] has 10 null pointers. Thats 10 more than we want, so use collections instead, or explicitly ll the array at initialisation with:
Object[] objects={"blah",5,new File("/usr/bin")};
or:
Object[] objects; objects=new Object[]{"blah",5,new File("/usr/bin")};
File.listFiles() can return null if "/etc" is not a directory. You can decide to trust some methods not to return null, if you like, but thats an assumption youre making. Some methods that dont specify that they might return null, actually do, instead of throwing an exception.
175
</strike> If the state variable is null, you get a NullPointerException in the second example, but not in the rst one. C ATEGORY:JAVA P ROGRAMMING6
6 7 8 9 10 11 12 13 14
H T T P :// E N . W I K I B O O K S . O R G / W I K I /C A T E G O R Y %3AJ A V A %20P R O G R A M M I N G H T T P :// E N . W I K I P E D I A . O R G / W I K I /J A V A %20 P L A T F O R M H T T P :// E N . W I K I P E D I A . O R G / W I K I /J A V A %20API H T T P :// E N . W I K I P E D I A . O R G / W I K I /J A V A %20 V I R T U A L %20 M A C H I N E H T T P :// E N . W I K I P E D I A . O R G / W I K I /GNU%20C O M P I L E R %20C O L L E C T I O N H T T P :// E N . W I K I P E D I A . O R G / W I K I /C O M P A R I S O N %20 O F %20J A V A %20 T O %20C P L U S P L U S H T T P :// E N . W I K I P E D I A . O R G / W I K I /JINI H T T P :// E N . W I K I P E D I A . O R G / W I K I /E C L I P S E %20%28 C O M P U T I N G %29
176
32 Links
32.1 External References
JAVA C ERTIFICATION M OCK E XAMS1 500+ questions with exam simulator (this is the older 1.4 version of the exam) JAVA L ANGUAGE S PECIFICATION , 3 RD E DITION2 . T HINKING IN JAVA3 JAVA 5 SDK D OCUMENTATION4 JAVA 5 SDK D OCUMENTATION IN CHM F ORMAT5 JAVA 5 API D OCUMENTATION6 T HE JAVA T UTORIAL7 Sun Developer Network N EW TO JAVA C ENTER8 A SIMPLE JAVA T UTORIAL 9 T WO S EMESTERS OF C OLLEGE -L EVEL JAVA L ECTURES --F REE10 JAVA L ESSONS - I NTERACTIVE JAVA PROGRAMMING TUTORIALS BASED ON EXAMPLES11 JAVA T UTORIALS FOR K IDS AND A DULTS12
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
H T T P :// W W W . C E R T I F I C A T I O N 4 C A R E E R . C O M H T T P :// J A V A . S U N . C O M / D O C S / B O O K S / J L S / T H I R D _ E D I T I O N / H T M L / J 3TOC. H T M L H T T P :// W W W . M I N D V I E W . N E T /B O O K S /TIJ/ H T T P :// J A V A . S U N . C O M / J 2 S E /1.5.0/ D O C S / I N D E X . H T M L H T T P :// W W W . Z E U S E D I T . C O M / F O R U M / V I E W T O P I C . P H P ? T =10 H T T P :// J A V A . S U N . C O M / J 2 S E /1.5.0/ D O C S / A P I / I N D E X . H T M L H T T P :// J A V A . S U N . C O M / D O C S / B O O K S / T U T O R I A L / I N D E X . H T M L H T T P :// J A V A . S U N . C O M / D E V E L O P E R / O N L I N E T R A I N I N G / N E W 2 J A V A / I N D E X . H T M L H T T P :// W W W . A L N A J A 7. N E T /P R O G R A M M E R /393/ITCS-393. H T M H T T P :// C U R M U D G E O N 99. G O O G L E P A G E S . C O M / H T T P :// J A V A L E S S O N S . C O M H T T P :// W W W . K I D W A R E S O F T W A R E . C O M H T T P :// W W W . C E R T I F I C A T I O N 4 C A R E E R . C O M H T T P :// W W W . S W I N G W I K I . O R G H T T P :// W W W . A K K I D I . C O M H T T P :// W W W . F R E E B O O K C E N T R E . N E T /J A V A T E C H / J A V A C A T E G O R Y . H T M L
177
Links
F REE JAVA AND J2EE E B OOKS17 JAVA BOOKS AVAILABLE FOR FREE DOWNLOADS18 ROEDY G REEN S JAVA & I NTERNET G LOSSARY19 A comprehensive reference thats also an excellent starting point for beginners C2: JAVA L ANGUAGE20 N ET B EANS IDE21 E CLIPSE IDE22 Z EUS FOR W INDOWS IDE23 O FFICIAL JAVA H OME S ITE24 O RIGINAL JAVA W HITEPAPER25 C OMPLETE JAVA P ROGRAMMING T UTORIALS26 JAVAPASSION , JAVA COURSE27 - The Javapassion Site, Java Course, driven by Sang Shin from Sun BEANSHELL28 Interpreted version T HE JAVA L ANGUAGE S PECIFICATION , T HIRD E DITION29 "This book attempts a complete specication of the syntax and semantics of the language." T HE JAVA V IRTUAL M ACHINE S PECIFICATION , S ECOND E DITION30 and AMENDMENTS31 A PURE JAVA DESKTOP32 JAVAPEDIA PROJECT33 Bruce Eckel Thinking in Java Third edition -- HTTP :// WWW. MINDVIEW. NET /B OOKS /TIJ/34 (Bruce has an C/C++ free book available on-line too) JAVAG AME D EVELOPMENT35 Daily news and articles on Java Game Development JAVA C ERTIFICATIONS S ITE (SCJP,SCWCD,SCBCD,JAVA 5.0,SCEA36 JAVA P ROGRAMMING FAQ S AND T UTORIALS37 M ORE RESOURCES38 JAVA LESSONS39 O NLINE JAVA T UTORIAL40
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
H T T P :// W W W . B E S T E B O O K S W O R L D . C O M / D E F A U L T . A S P ? C A T =55 H T T P :// W W W . T E C H B O O K S F O R F R E E . C O M / J A V A . S H T M L H T T P :// W W W . M I N D P R O D . C O M / J G L O S S / J G L O S S . H T M L H T T P :// C 2. C O M / C G I / W I K I ?J A V A L A N G U A G E H T T P :// W W W . N E T B E A N S . O R G H T T P :// W W W . E C L I P S E . O R G H T T P :// W W W . Z E U S E D I T . C O M / J A V A . H T M L H T T P :// J A V A . S U N . C O M H T T P :// J A V A . S U N . C O M / D O C S / W H I T E / L A N G E N V / H T T P :// W W W . R O S E I N D I A . N E T / J A V A / H T T P :// W W W . J A V A P A S S I O N . C O M / J A V A I N T R O / H T T P :// W W W . B E A N S H E L L . O R G H T T P :// J A V A . S U N . C O M / D O C S / B O O K S / J L S / T H I R D _ E D I T I O N / H T M L / J 3TOC. H T M L H T T P :// J A V A . S U N . C O M / D O C S / B O O K S / V M S P E C /2 N D - E D I T I O N / H T M L /VMS P E C TOC. D O C . H T M L H T T P :// J A V A . S U N . C O M / D O C S / B O O K S / V M S P E C /2 N D - E D I T I O N / J V M S - C L A R I F Y . H T M L H T T P :// W W W . J D I S T R O . C O M / H T T P :// W I K I . J A V A . N E T / B I N / V I E W /J A V A P E D I A / H T T P :// W W W . M I N D V I E W . N E T /B O O K S /TIJ/ H T T P :// J A V A G A M E D E V E L O P M E N T . N E T H T T P :// W W W . J A V A B E A T . N E T H T T P :// W W W . A P L . J H U . E D U /~{} H A L L / J A V A /FAQ S - A N D -T U T O R I A L S . H T M L H T T P :// F I N D S H E L L . C O M H T T P :// W W W . L A N D O F C O D E . C O M / J A V A / H T T P :// C O M P U T E R . F R E E O N L I N E B O O K S T O R E . O R G /S H O W B O O K . P H P ? S U B C A T E G O R Y I D =17
178
External links
F ULL JAVA T UTORIAL41 - A collection of free premium programming tutorials JAVA C ERTIFICATION P RACTICE T ESTS AND A RTICLES42 KODE JAVA - L EARN JAVA P ROGRAMMING BY E XAMPLES43 G AMES P ROGRAMMING W IKI44 - Java tutorials and lessons based on game programming W IKI JAVA45 - Examples and tutorials in Java D OWNLOAD F REE JAVA EBOOKS FROM 83 EBOOKS COLLECTION46 - Free Java Ebooks to download from ebookslab.info D OWNLOAD F REE S UN C ERTIFIED D EVELOPER FOR JAVA W EB S ERVICES47 - Free Java Ebooks to download from ebooks.mzwriter.net C ODE C ONVENTIONS FOR THE JAVA P ROGRAMMING L ANGUAGE48 - At SUN Newsgroups: news:comp.lang.java comp.lang.java ( G OOGLE S WEB INTERFACE49 ) L INKS50
41 42 43 44 45 46 47 48 49 50
H T T P :// W W W . M E S H P L E X . O R G / W I K I /J A V A /I N T R O D U C T I O N _ T O _J A V A H T T P :// W W W . U C E R T I F Y . C O M / V E N D O R S /S U N . H T M L H T T P :// W W W . K O D E J A V A . O R G / H T T P :// G P W I K I . O R G / H T T P :// W W W . W I K I J A V A . O R G / H T T P :// W W W . E B O O K S L A B . I N F O / D O W N L O A D - F R E E - J A V A - E B O O K S H T T P :// J A V A . S U N . C O M / D O C S / C O D E C O N V / H T M L /C O D E C O N V TOC. D O C . H T M L H T T P :// G R O U P S . G O O G L E . C O M / G R O U P S ? G R O U P = C O M P . L A N G . J A V A H T T P :// E N . W I K I B O O K S . O R G / W I K I /C A T E G O R Y %3AJ A V A %20P R O G R A M M I N G
H T T P :// E B O O K S . M Z W R I T E R . N E T / E - B O O K S / S H A R E _ E B O O K -310-220- S U N - C E R T I F I E D - D E V E L O P E R - F O R - J A V A - W E B - S
179
Links
180
33 License
181
License
182
D EUTSCH J.SE3
1 2 3
183
184
35 Authors
Edits 1 24 2 1 1 2 1 1 69 7 2 1 1 4 1 1 1 3 2 5 3
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
User A D R ILEY1 A DRIGNOLA2 A LAINR 3453 A LBMONT4 A LEXANDER . ORLOV5 A NTIDRUGUE6 A PHONIK7 A RSENALFAN8 A RUNREGINALD9 A SHMAILIT10 A Z 156811 B ENO 100012 C ECLAUSON13 C OLFULUS14 C OLINDAVEN15 C SPURRIER16 DALLAS 127817 DAN P OLANSKY18 DARKLAMA19 DARKXXXXILLUSION20 DAVID C ARY21
H T T P :// E N . W I K I B O O K S . O R G / W / I N D E X . P H P ? T I T L E =U S E R :A D R I L E Y H T T P :// E N . W I K I B O O K S . O R G / W / I N D E X . P H P ? T I T L E =U S E R :A D R I G N O L A H T T P :// E N . W I K I B O O K S . O R G / W / I N D E X . P H P ? T I T L E =U S E R :A L A I N R 345 H T T P :// E N . W I K I B O O K S . O R G / W / I N D E X . P H P ? T I T L E =U S E R :A L B M O N T H T T P :// E N . W I K I B O O K S . O R G / W / I N D E X . P H P ? T I T L E =U S E R :A L E X A N D E R . O R L O V H T T P :// E N . W I K I B O O K S . O R G / W / I N D E X . P H P ? T I T L E =U S E R :A N T I D R U G U E H T T P :// E N . W I K I B O O K S . O R G / W / I N D E X . P H P ? T I T L E =U S E R :A P H O N I K H T T P :// E N . W I K I B O O K S . O R G / W / I N D E X . P H P ? T I T L E =U S E R :A R S E N A L F A N H T T P :// E N . W I K I B O O K S . O R G / W / I N D E X . P H P ? T I T L E =U S E R :A R U N R E G I N A L D H T T P :// E N . W I K I B O O K S . O R G / W / I N D E X . P H P ? T I T L E =U S E R :A S H M A I L I T H T T P :// E N . W I K I B O O K S . O R G / W / I N D E X . P H P ? T I T L E =U S E R :A Z 1568 H T T P :// E N . W I K I B O O K S . O R G / W / I N D E X . P H P ? T I T L E =U S E R :B E N O 1000 H T T P :// E N . W I K I B O O K S . O R G / W / I N D E X . P H P ? T I T L E =U S E R :C E C L A U S O N H T T P :// E N . W I K I B O O K S . O R G / W / I N D E X . P H P ? T I T L E =U S E R :C O L F U L U S H T T P :// E N . W I K I B O O K S . O R G / W / I N D E X . P H P ? T I T L E =U S E R :C O L I N D A V E N H T T P :// E N . W I K I B O O K S . O R G / W / I N D E X . P H P ? T I T L E =U S E R :C S P U R R I E R H T T P :// E N . W I K I B O O K S . O R G / W / I N D E X . P H P ? T I T L E =U S E R :D A L L A S 1278 H T T P :// E N . W I K I B O O K S . O R G / W / I N D E X . P H P ? T I T L E =U S E R :D A N _P O L A N S K Y H T T P :// E N . W I K I B O O K S . O R G / W / I N D E X . P H P ? T I T L E =U S E R :D A R K L A M A H T T P :// E N . W I K I B O O K S . O R G / W / I N D E X . P H P ? T I T L E =U S E R :D A R K X X X X I L L U S I O N H T T P :// E N . W I K I B O O K S . O R G / W / I N D E X . P H P ? T I T L E =U S E R :D A V I D C A R Y
185
Authors
1 1 5 3 79 1 1 646 3 3 3 3 1 1 2 4 2 2 1 1 5 1 1 1 1
D EVOURER 0922 D ICKDICKDICK23 D IRK H NNIGER24 D IRK GENTLY25 D JB26 D MONEGO27 D RAWDE 8328 E RVINN29 E XABYTE30 E XPLANATOR31 F ELIPEOCHOA 091832 F ISHPI33 F KEREKI34 F LATIPAC35 F REDMARANHAO36 F TIERCEL37 G O LL OX P38 G ROKUS39 G RUNNY40 G UANACO41 G UANGPU . HUANG42 HMP ERSON 143 H AGINDAZ44 H ERMIONE 198045 H ROULF46
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
H T T P :// E N . W I K I B O O K S . O R G / W / I N D E X . P H P ? T I T L E =U S E R :D E V O U R E R 09 H T T P :// E N . W I K I B O O K S . O R G / W / I N D E X . P H P ? T I T L E =U S E R :D I C K D I C K D I C K H T T P :// E N . W I K I B O O K S . O R G / W / I N D E X . P H P ? T I T L E =U S E R :D I R K _H%C3%BC N N I G E R H T T P :// E N . W I K I B O O K S . O R G / W / I N D E X . P H P ? T I T L E =U S E R :D I R K _ G E N T L Y H T T P :// E N . W I K I B O O K S . O R G / W / I N D E X . P H P ? T I T L E =U S E R :D J B H T T P :// E N . W I K I B O O K S . O R G / W / I N D E X . P H P ? T I T L E =U S E R :D M O N E G O H T T P :// E N . W I K I B O O K S . O R G / W / I N D E X . P H P ? T I T L E =U S E R :D R A W D E 83 H T T P :// E N . W I K I B O O K S . O R G / W / I N D E X . P H P ? T I T L E =U S E R :E R V I N N H T T P :// E N . W I K I B O O K S . O R G / W / I N D E X . P H P ? T I T L E =U S E R :E X A B Y T E H T T P :// E N . W I K I B O O K S . O R G / W / I N D E X . P H P ? T I T L E =U S E R :E X P L A N A T O R H T T P :// E N . W I K I B O O K S . O R G / W / I N D E X . P H P ? T I T L E =U S E R :F E L I P E O C H O A 0918 H T T P :// E N . W I K I B O O K S . O R G / W / I N D E X . P H P ? T I T L E =U S E R :F I S H P I H T T P :// E N . W I K I B O O K S . O R G / W / I N D E X . P H P ? T I T L E =U S E R :F K E R E K I H T T P :// E N . W I K I B O O K S . O R G / W / I N D E X . P H P ? T I T L E =U S E R :F L A T I P A C H T T P :// E N . W I K I B O O K S . O R G / W / I N D E X . P H P ? T I T L E =U S E R :F R E D M A R A N H A O H T T P :// E N . W I K I B O O K S . O R G / W / I N D E X . P H P ? T I T L E =U S E R :F T I E R C E L H T T P :// E N . W I K I B O O K S . O R G / W / I N D E X . P H P ? T I T L E =U S E R :G O LL O X P H T T P :// E N . W I K I B O O K S . O R G / W / I N D E X . P H P ? T I T L E =U S E R :G R O K U S H T T P :// E N . W I K I B O O K S . O R G / W / I N D E X . P H P ? T I T L E =U S E R :G R U N N Y H T T P :// E N . W I K I B O O K S . O R G / W / I N D E X . P H P ? T I T L E =U S E R :G U A N A C O H T T P :// E N . W I K I B O O K S . O R G / W / I N D E X . P H P ? T I T L E =U S E R :G U A N G P U . H U A N G H T T P :// E N . W I K I B O O K S . O R G / W / I N D E X . P H P ? T I T L E =U S E R :HMP E R S O N 1 H T T P :// E N . W I K I B O O K S . O R G / W / I N D E X . P H P ? T I T L E =U S E R :H A G I N D A Z H T T P :// E N . W I K I B O O K S . O R G / W / I N D E X . P H P ? T I T L E =U S E R :H E R M I O N E 1980 H T T P :// E N . W I K I B O O K S . O R G / W / I N D E X . P H P ? T I T L E =U S E R :H R O %C3%B0 U L F
186
External links
2 1 1 33 1 1 7 2 1 1 1 1 1 6 2 11 1 3 1 42 1 1 2 4 1
IM AC W IN 9547 I TSBORIN48 J36 MILES49 J GUK50 J IMMYATIC51 J K 3352 J OMEGAT53 J ONATHAN W EBLEY54 J PKOTTA55 K EJIA56 K ENJ 041857 K RIAK58 L CAWTE59 M ALFIST60 M ATRIX F ROG61 M ATTYLAWS62 M AX B OWSHER63 M ETA B OHEMIAN64 M HAYES65 M IKM66 M S 2 GER67 M STENTA68 O MZIG 8969 PANIC 2 K 470 P ENGO71
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
H T T P :// E N . W I K I B O O K S . O R G / W / I N D E X . P H P ? T I T L E =U S E R :IM A C W I N 95 H T T P :// E N . W I K I B O O K S . O R G / W / I N D E X . P H P ? T I T L E =U S E R :I T S B O R I N H T T P :// E N . W I K I B O O K S . O R G / W / I N D E X . P H P ? T I T L E =U S E R :J36 M I L E S H T T P :// E N . W I K I B O O K S . O R G / W / I N D E X . P H P ? T I T L E =U S E R :J G U K H T T P :// E N . W I K I B O O K S . O R G / W / I N D E X . P H P ? T I T L E =U S E R :J I M M Y A T I C H T T P :// E N . W I K I B O O K S . O R G / W / I N D E X . P H P ? T I T L E =U S E R :J K 33 H T T P :// E N . W I K I B O O K S . O R G / W / I N D E X . P H P ? T I T L E =U S E R :J O M E G A T H T T P :// E N . W I K I B O O K S . O R G / W / I N D E X . P H P ? T I T L E =U S E R :J O N A T H A N _W E B L E Y H T T P :// E N . W I K I B O O K S . O R G / W / I N D E X . P H P ? T I T L E =U S E R :J P K O T T A H T T P :// E N . W I K I B O O K S . O R G / W / I N D E X . P H P ? T I T L E =U S E R :K E J I A H T T P :// E N . W I K I B O O K S . O R G / W / I N D E X . P H P ? T I T L E =U S E R :K E N J 0418 H T T P :// E N . W I K I B O O K S . O R G / W / I N D E X . P H P ? T I T L E =U S E R :K R I A K H T T P :// E N . W I K I B O O K S . O R G / W / I N D E X . P H P ? T I T L E =U S E R :L C A W T E H T T P :// E N . W I K I B O O K S . O R G / W / I N D E X . P H P ? T I T L E =U S E R :M A L F I S T H T T P :// E N . W I K I B O O K S . O R G / W / I N D E X . P H P ? T I T L E =U S E R :M A T R I X F R O G H T T P :// E N . W I K I B O O K S . O R G / W / I N D E X . P H P ? T I T L E =U S E R :M A T T Y L A W S H T T P :// E N . W I K I B O O K S . O R G / W / I N D E X . P H P ? T I T L E =U S E R :M A X B O W S H E R H T T P :// E N . W I K I B O O K S . O R G / W / I N D E X . P H P ? T I T L E =U S E R :M E T A B O H E M I A N H T T P :// E N . W I K I B O O K S . O R G / W / I N D E X . P H P ? T I T L E =U S E R :M H A Y E S H T T P :// E N . W I K I B O O K S . O R G / W / I N D E X . P H P ? T I T L E =U S E R :M I K M H T T P :// E N . W I K I B O O K S . O R G / W / I N D E X . P H P ? T I T L E =U S E R :M S 2 G E R H T T P :// E N . W I K I B O O K S . O R G / W / I N D E X . P H P ? T I T L E =U S E R :M S T E N T A H T T P :// E N . W I K I B O O K S . O R G / W / I N D E X . P H P ? T I T L E =U S E R :O M Z I G 89 H T T P :// E N . W I K I B O O K S . O R G / W / I N D E X . P H P ? T I T L E =U S E R :P A N I C 2 K 4 H T T P :// E N . W I K I B O O K S . O R G / W / I N D E X . P H P ? T I T L E =U S E R :P E N G O
187
Authors
2 12 3 1 7 1 3 10 3 5 1 1 65 8 16 1 4 3 7 1 2 1 1 2 2
P ITEL72 P RODOC73 Q UITE U NUSUAL74 R ALPHCOOK75 R APPO76 R AVICHANDAR 8477 R ECENT RUNES78 R ICKY CLARKSON79 SBJ OHNNY80 S AMWILSON81 S EANJA82 S HAHIDSIDD83 S IGMA 784 S PONGEBOB 8885 S POON !86 S TEPHANVANINGEN87 S UNDAR 22 IN88 S UNNYCHAN89 S UPERFLY J ON90 S WIFT91 TANMINIVAN92 TAROSE . TREVOR93 T HE DAVE ROSS94 T HEPHILWELLS95 UNV96
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
H T T P :// E N . W I K I B O O K S . O R G / W / I N D E X . P H P ? T I T L E =U S E R :P I T E L H T T P :// E N . W I K I B O O K S . O R G / W / I N D E X . P H P ? T I T L E =U S E R :P R O D O C H T T P :// E N . W I K I B O O K S . O R G / W / I N D E X . P H P ? T I T L E =U S E R :Q U I T E U N U S U A L H T T P :// E N . W I K I B O O K S . O R G / W / I N D E X . P H P ? T I T L E =U S E R :R A L P H C O O K H T T P :// E N . W I K I B O O K S . O R G / W / I N D E X . P H P ? T I T L E =U S E R :R A P P O H T T P :// E N . W I K I B O O K S . O R G / W / I N D E X . P H P ? T I T L E =U S E R :R A V I C H A N D A R 84 H T T P :// E N . W I K I B O O K S . O R G / W / I N D E X . P H P ? T I T L E =U S E R :R E C E N T _R U N E S H T T P :// E N . W I K I B O O K S . O R G / W / I N D E X . P H P ? T I T L E =U S E R :R I C K Y _ C L A R K S O N H T T P :// E N . W I K I B O O K S . O R G / W / I N D E X . P H P ? T I T L E =U S E R :SBJ O H N N Y H T T P :// E N . W I K I B O O K S . O R G / W / I N D E X . P H P ? T I T L E =U S E R :S A M W I L S O N H T T P :// E N . W I K I B O O K S . O R G / W / I N D E X . P H P ? T I T L E =U S E R :S E A N J A H T T P :// E N . W I K I B O O K S . O R G / W / I N D E X . P H P ? T I T L E =U S E R :S H A H I D S I D D H T T P :// E N . W I K I B O O K S . O R G / W / I N D E X . P H P ? T I T L E =U S E R :S I G M A _7 H T T P :// E N . W I K I B O O K S . O R G / W / I N D E X . P H P ? T I T L E =U S E R :S P O N G E B O B 88 H T T P :// E N . W I K I B O O K S . O R G / W / I N D E X . P H P ? T I T L E =U S E R :S P O O N %21 H T T P :// E N . W I K I B O O K S . O R G / W / I N D E X . P H P ? T I T L E =U S E R :S T E P H A N V A N I N G E N H T T P :// E N . W I K I B O O K S . O R G / W / I N D E X . P H P ? T I T L E =U S E R :S U N D A R 22 I N H T T P :// E N . W I K I B O O K S . O R G / W / I N D E X . P H P ? T I T L E =U S E R :S U N N Y C H A N H T T P :// E N . W I K I B O O K S . O R G / W / I N D E X . P H P ? T I T L E =U S E R :S U P E R F L Y _J O N H T T P :// E N . W I K I B O O K S . O R G / W / I N D E X . P H P ? T I T L E =U S E R :S W I F T H T T P :// E N . W I K I B O O K S . O R G / W / I N D E X . P H P ? T I T L E =U S E R :T A N M I N I V A N H T T P :// E N . W I K I B O O K S . O R G / W / I N D E X . P H P ? T I T L E =U S E R :T A R O S E . T R E V O R H T T P :// E N . W I K I B O O K S . O R G / W / I N D E X . P H P ? T I T L E =U S E R :T H E D A V E R O S S H T T P :// E N . W I K I B O O K S . O R G / W / I N D E X . P H P ? T I T L E =U S E R :T H E P H I L W E L L S H T T P :// E N . W I K I B O O K S . O R G / W / I N D E X . P H P ? T I T L E =U S E R :UNV
188
External links
1 1 1 6 2 1 1 1 2 1 7 9 1
V INAY H97 W EBAWARE98 W HITEKNIGHT99 W IKI W IZARD100 W IKIALT101 W ILLEM S OUWER102 W ISE E YES103 W UR - DENE104 W UTZOFANT105 YMS106 Y UUKI M AYUKI107 Z ERO O NE108
109
97 98 99 100 101 102 103 104 105 106 107 108 109
H T T P :// E N . W I K I B O O K S . O R G / W / I N D E X . P H P ? T I T L E =U S E R :V I N A Y _ H H T T P :// E N . W I K I B O O K S . O R G / W / I N D E X . P H P ? T I T L E =U S E R :W E B A W A R E H T T P :// E N . W I K I B O O K S . O R G / W / I N D E X . P H P ? T I T L E =U S E R :W H I T E K N I G H T H T T P :// E N . W I K I B O O K S . O R G / W / I N D E X . P H P ? T I T L E =U S E R :W I K I W I Z A R D H T T P :// E N . W I K I B O O K S . O R G / W / I N D E X . P H P ? T I T L E =U S E R :W I K I A L T H T T P :// E N . W I K I B O O K S . O R G / W / I N D E X . P H P ? T I T L E =U S E R :W I L L E M _S O U W E R H T T P :// E N . W I K I B O O K S . O R G / W / I N D E X . P H P ? T I T L E =U S E R :W I S E E Y E S H T T P :// E N . W I K I B O O K S . O R G / W / I N D E X . P H P ? T I T L E =U S E R :W U R - D E N E H T T P :// E N . W I K I B O O K S . O R G / W / I N D E X . P H P ? T I T L E =U S E R :W U T Z O F A N T H T T P :// E N . W I K I B O O K S . O R G / W / I N D E X . P H P ? T I T L E =U S E R :YMS H T T P :// E N . W I K I B O O K S . O R G / W / I N D E X . P H P ? T I T L E =U S E R :Y U U K I _M A Y U K I H T T P :// E N . W I K I B O O K S . O R G / W / I N D E X . P H P ? T I T L E =U S E R :Z E R O O N E H T T P :// E N . W I K I B O O K S . O R G / W / I N D E X . P H P ? T I T L E =U S E R :%E7%A0%B2%E7%81%AB_%E4%B8%87% E7%89%A9%E3%81%AE%E9%9C%8A%E9%95%B7
189
Authors
190
List of Figures
GFDL: Gnu Free Documentation License. http://www.gnu.org/licenses/fdl.html cc-by-sa-3.0: Creative Commons Attribution http://creativecommons.org/licenses/by-sa/3.0/ cc-by-sa-2.5: Creative Commons Attribution http://creativecommons.org/licenses/by-sa/2.5/ cc-by-sa-2.0: Creative Commons Attribution http://creativecommons.org/licenses/by-sa/2.0/ cc-by-sa-1.0: Creative Commons Attribution http://creativecommons.org/licenses/by-sa/1.0/ cc-by-2.0: Creative Commons http://creativecommons.org/licenses/by/2.0/ cc-by-2.0: Creative Commons http://creativecommons.org/licenses/by/2.0/deed.en cc-by-2.5: Creative Commons http://creativecommons.org/licenses/by/2.5/deed.en cc-by-3.0: Creative Commons http://creativecommons.org/licenses/by/3.0/deed.en ShareAlike ShareAlike ShareAlike ShareAlike 3.0 2.5 2.0 1.0 2.0 2.0 2.5 3.0 License. License. License. License. License. License. License. License.
GPL: GNU General Public License. http://www.gnu.org/licenses/gpl-2.0.txt PD: This image is in the public domain. ATTR: The copyright holder of this le allows anyone to use it for any purpose, provided that the copyright holder is properly attributed. Redistribution, derivative work, commercial use, and all other use is permitted. EURO: This is the common (reverse) face of a euro coin. The copyright on the design of the common face of the euro coins belongs to the European Commission. Authorised is reproduction in a format without relief (drawings, paintings, lms) provided they are not detrimental to the image of the euro. LFK: Lizenz Freie Kunst. http://artlibre.org/licence/lal/de CFR: Copyright free use. EPL: Eclipse Public License. http://www.eclipse.org/org/documents/epl-v10.php
191
List of Figures
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
GFDL GFDL
A RUN R EGINALD114 A RUN R EGINALD115 Original version created by B :U SER :E RVINN116 , SVG version created by MYSELF117 Original version created by B :U SER :E RVINN118 , SVG version created by MYSELF119
110 111 112 113 114 115 116 117 118 119
H T T P :// E N . W I K I B O O K S . O R G / W I K I /U S E R %3AP E T E R %20C A M P B E L L H T T P :// E N . W I K I B O O K S . O R G / W I K I /U S E R %3AA R U N R E G I N A L D H T T P :// E N . W I K I B O O K S . O R G / W I K I /U S E R %3AA R U N R E G I N A L D H T T P :// E N . W I K I B O O K S . O R G / W I K I /U S E R %3AA R U N R E G I N A L D H T T P :// E N . W I K I B O O K S . O R G / W I K I /U S E R %3AA R U N R E G I N A L D H T T P :// E N . W I K I B O O K S . O R G / W I K I /U S E R %3AA R U N R E G I N A L D H T T P :// E N . W I K I B O O K S . O R G / W I K I /U S E R %3AE R V I N N H T T P :// E N . W I K I B O O K S . O R G / W I K I /U S E R %3AM I K M H T T P :// E N . W I K I B O O K S . O R G / W I K I /U S E R %3AE R V I N N H T T P :// E N . W I K I B O O K S . O R G / W I K I /U S E R %3AM I K M
192