Beginning java 8 fundamentals

810 281 0
Beginning java 8 fundamentals

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

www.it-ebooks.info For your convenience Apress has placed some of the front matter material after the index Please use the Bookmarks and Contents at a Glance links to access them www.it-ebooks.info Contents at a Glance Foreword�������������������������������������������������������������������������������������������������������������������������� xxv About the Author������������������������������������������������������������������������������������������������������������ xxvii About the Technical Reviewer����������������������������������������������������������������������������������������� xxix Acknowledgments����������������������������������������������������������������������������������������������������������� xxxi Introduction������������������������������������������������������������������������������������������������������������������� xxxiii ■■Chapter 1: Programming Concepts�����������������������������������������������������������������������������������1 ■■Chapter 2: Writing Java Programs����������������������������������������������������������������������������������31 ■■Chapter 3: Data Types������������������������������������������������������������������������������������������������������61 ■■Chapter 4: Operators�������������������������������������������������������������������������������������������������������99 ■■Chapter 5: Statements���������������������������������������������������������������������������������������������������139 ■■Chapter 6: Classes and Objects�������������������������������������������������������������������������������������165 ■■Chapter 7: The Object and Objects Classes�������������������������������������������������������������������281 ■■Chapter 8: Wrapper Classes������������������������������������������������������������������������������������������317 ■■Chapter 9: Exception Handling��������������������������������������������������������������������������������������335 ■■Chapter 10: Assertions��������������������������������������������������������������������������������������������������379 ■■Chapter 11: Strings�������������������������������������������������������������������������������������������������������387 ■■Chapter 12: Dates and Times�����������������������������������������������������������������������������������������411 ■■Chapter 13: Formatting Data�����������������������������������������������������������������������������������������485 ■■Chapter 14: Regular Expressions����������������������������������������������������������������������������������519 ■■Chapter 15: Arrays��������������������������������������������������������������������������������������������������������543 v www.it-ebooks.info ■ Contents at a Glance ■■Chapter 16: Inheritance�������������������������������������������������������������������������������������������������583 ■■Chapter 17: Interfaces���������������������������������������������������������������������������������������������������643 ■■Chapter 18: Enum Types������������������������������������������������������������������������������������������������705 ■■Appendix A: Character Encodings���������������������������������������������������������������������������������727 ■■Appendix B: Documentation Comments������������������������������������������������������������������������739 ■■Appendix C: Compact Profiles���������������������������������������������������������������������������������������759 Index���������������������������������������������������������������������������������������������������������������������������������775 vi www.it-ebooks.info Introduction How This Book Came About My first encounter with the Java programming language was during a one-week Java training session in 1997 I did not get a chance to use Java in a project until 1999 I read two Java books and took a Java Programmer certification examination I did very well on the test, scoring 95 percent The three questions that I missed on the test made me realize that the books that I had read did not adequately cover details of all the topics necessary about Java I made up my mind to write a book on the Java programming language So, I formulated a plan to cover most of the topics that a Java developer needs to use the Java programming language effectively in a project, as well as to get a certification I initially planned to cover all essential topics in Java in 700 to 800 pages As I progressed, I realized that a book covering most of the Java topics in detail could not be written in 700 to 800 hundred pages One chapter alone that covered data types, operators, and statements spanned 90 pages I was then faced with the question, “Should I shorten the content of the book or include all the details that I think a Java developer needs?” I opted for including all the details in the book, rather than shortening its content to keep the number of pages low It has never been my intent to make lots of money from this book I was never in a hurry to finish this book because that rush could have compromised the quality and the coverage of its contents In short, I wrote this book to help the Java community understand and use the Java programming language effectively, without having to read many books on the same subject I wrote this book with the plan that it would be a comprehensive onestop reference for everyone who wants to learn and grasp the intricacies of the Java programming language One of my high school teachers used to tell us that if one wanted to understand a building, one must first understand the bricks, steel, and mortar that make up the building The same logic applies to most of the things that we want to understand in our lives It certainly applies to an understanding of the Java programming language If you want to master the Java programming language, you must start by understanding its basic building blocks I have used this approach throughout this book, endeavoring to build each topic by describing the basics first In the book, you will rarely find a topic described without first learning its background Wherever possible, I have tried to correlate the programming practices with activities in our daily life Most of the books about the Java programming language available in the market either not include any pictures at all or have only a few I believe in the adage, “A picture is worth a thousand words.” To a reader, a picture makes a topic easier to understand and remember I have included plenty of illustrations in the book to aid readers in understanding and visualizing the contents Developers who have little or no programming experience have difficulty in putting things together to make it a complete program Keeping them in mind, the book contains over 240 complete Java programs that are ready to be compiled and run I spent countless hours doing research for writing this book My main source of research was the Java Language Specification, white papers and articles on Java topics, and Java Specification Requests (JSRs) I also spent quite a bit of time reading the Java source code to learn more about some of the Java topics Sometimes, it took a few months researching a topic before I could write the first sentence on the topic Finally, it was always fun to play with Java programs, sometimes for hours, to add them to the book xxxiii www.it-ebooks.info ■ Introduction Structure of the Book This book contains 18 chapters and three appendixes The chapters contain fundamental topics of Java such as syntax, data types, operators, classes, objects, etc The chapters are arranged in an order that aids learning the Java programming language faster The first chapter, “Programming Concepts,” explains basic concepts related to programming in general, without going into too much technical details; it introduces Java and its features The second chapter, “Writing Java Programs,” introduces the first program using Java; this chapter is especially written for those learning Java for the first time Subsequent chapters introduce Java topics in an increasing order of complexity The new features of Java are included wherever they fit in the chapter The new Date-Time API, which is one of the biggest addition in Java 8, has been discussed in great detail in over 80 pages in Chapter 12 After finishing this book, to take your Java knowledge to the next level, two companion books are available by the author: Beginning Java Language Features (ISBN 978-1-4302-6658-7) and Beginning Java APIs, Extensions, and Libraries (ISBN 978-1-4302-6661-7) Audience This book is designed to be useful for anyone who wants to learn the Java programming language If you are a beginner, with little or no programming background, you need to read from the first chapter to the last, in order The book contains topics of various degrees of complexity As a beginner, if you find yourself overwhelmed while reading a section in a chapter, you can skip to the next section or the next chapter, and revisit it later when you gain more experience If you are a Java developer with an intermediate or advanced level of experience, you can jump to a chapter or to a section in a chapter directly If a section uses an unfamiliar topic, you need to visit that topic before continuing the current one If you are reading this book to get a certification in the Java programming language, you need to read almost all of the chapters, paying attention to all the detailed descriptions and rules Most of the certification programs test your fundamental knowledge of the language, not the advanced knowledge You need to read only those topics that are part of your certification test Compiling and running over 240 complete Java programs will help you prepare for your certification If you are a student who is attending a class in the Java programming language, you need to read the first six chapters of this book thoroughly These chapters cover the basics of the Java programming languages in detail You cannot well in a Java class unless you first master the basics After covering the basics, you need to read only those chapters that are covered in your class syllabus I am sure, you, as a Java student, not need to read the entire book page-by-page How to Use This Book This book is the beginning, not the end, for you to gain the knowledge of the Java programming language If you are reading this book, it means you are heading in the right direction to learn the Java programming language that will enable you to excel in your academic and professional career However, there is always a higher goal for you to achieve and you must constantly work harder to achieve it The following quotations from some great thinkers may help you understand the importance of working hard and constantly looking for knowledge with both your eyes and mind open The learning and knowledge that we have, is, at the most, but little compared with that of which we are ignorant —Plato True knowledge exists in knowing that you know nothing And in knowing that you know nothing, that makes you the smartest of all —Socrates xxxiv www.it-ebooks.info ■ Introduction Readers are advised to use the API documentation for the Java programming language, as much as possible, while using this book The Java API documentation is the place where you will find a complete list of documentation for everything available in the Java class library You can download (or view) the Java API documentation from the official web site of Oracle Corporation at www.oracle.com While you read this book, you need to practice writing Java programs yourself You can also practice by tweaking the programs provided in the book It does not help much in your learning process if you just read this book and not practice by writing your own programs Remember that “practice makes perfect,” which is also true in learning how to program in Java Source Code and Errata Source code and errata for this book may be downloaded from www.apress.com/source-code Questions and Comments Please direct all your questions and comments for the author to ksharan@jdojo.com xxxv www.it-ebooks.info Chapter Programming Concepts In this chapter, you will learn • The general concept of programming • Different components of programming • Major programming paradigms • The object-oriented paradigm and how it is used in Java What Is Programming? The term “programming” is used in many contexts We will discuss its meaning in the context of human-to-computer interaction In the simplest terms, programming is the way of writing a sequence of instructions to tell a computer to perform a specific task The sequence of instructions for a computer is known as a program A set of well-defined notations is used to write a program The set of notations used to write a program is called a programming language The person who writes a program is called a programmer A programmer uses a programming language to write a program How does a person tell a computer to perform a task? Can a person tell a computer to perform any task or does a computer have a predefined set of tasks that it can perform? Before we look at human-to-computer communication, let’s look at human-to-human communication How does a human communicate with another human? You would say that human-to-human communication is accomplished using a spoken language, for example, English, German, Hindi, etc However, spoken language is not the only means of communication between humans We also communicate using written languages or using gestures without uttering any words Some people can even communicate sitting miles away from each other without using any words or gestures; they can communicate at thought level To have a successful communication, it is not enough just to use a medium of communication like a spoken or written language The main requirement for a successful communication between two parties is the ability of both parties to understand what is communicated from the other party For example, suppose there are two people One person knows how to speak English and the other one knows how to speak German Can they communicate with each other? The answer is no, because they cannot understand each other’s language What happens if we add an English-German translator between them? We would agree that they would be able to communicate with the help of a translator even though they not understand each other directly Computers understand instructions only in binary format, which is a sequence of 0s and 1s The sequence of 0s and 1s, which all computers understand, is called machine language or machine code A computer has a fixed set of basic instructions that it understands Each computer has its own set of instructions For example, 0010 may be an instruction to add two numbers on one computer and 0101 is an instruction to add two numbers on another computer Therefore, programs written in machine language are machine-dependent Sometimes machine code is referred to as native code as it is native to the machine for which it is written Programs written in machine language are very difficult, if not impossible, to write, read, understand, and modify Suppose you want to write a program that www.it-ebooks.info Chapter ■ Programming Concepts adds two numbers, 15 and 12 The program to add two numbers in machine language will look similar to the one shown below You not need to understand the sample code written in this section It is only for the purpose of discussion and illustration   0010010010 10010100000100110 0001000100 01010010001001010   The above instructions are to add two numbers How difficult will it be to write a program in machine language to perform a complex task? Based on the above code, you may now realize that it is very difficult to write, read, and understand a program written in a machine language But aren’t computers supposed to make our jobs easier, not more difficult? We needed to represent the instructions for computers in some notations that were easier to write, read, and understand, so computer scientists came up with another language called an assembly language An assembly language provides different notations to write instructions It is little easier to write, read, and understand than its predecessor, machine language An assembly language uses mnemonics to represent instructions as opposed to the binary (0s and 1s) used in machine language A program written in an assembly language to add two numbers looks similar to the following:   li $t1, 15 add $t0, $t1, 12   If you compare the two programs written in the two different languages to perform the same task, you can see that assembly language is easier to write, read, and understand than machine code There is one-to-one correspondence between an instruction in machine language and assembly language for a given computer architecture Recall that a computer understands instructions only in machine language The instructions that are written in an assembly language must be translated into machine language before the computer can execute them A program that translates the instructions written in an assembly language into machine language is called an assembler Figure 1-1 shows the relationship between assembly code, an assembler, and machine code Figure 1-1.  The relationship between assembly code, assembler, and machine code Machine language and assembly language are also known as low-level languages They are called low-level languages because a programmer must understand the low-level details of the computer to write a program using those languages For example, if you were writing programs in machine and assembly languages, you would need to know what memory location you are writing to or reading from, which register to use to store a specific value, etc Soon programmers realized a need for a higher-level programming language that could hide the low-level details of computers from them The need gave rise to the development of high-level programming languages like COBOL, Pascal, FORTRAN, C, C++, Java, C#, etc The high-level programming languages use English-like words, mathematical notation, and punctuation to write programs A program written in a high-level programming language is also called source code They are closer to the written languages that humans are familiar with The instructions to add two numbers can be written in a high-level programming language, for example Java looks similar to the following:   int x = 15 + 27;   www.it-ebooks.info Chapter ■ Programming Concepts You may notice that the programs written in a high-level language are easier and more intuitive to write, read, understand, and modify than the programs written in machine and assembly languages You might have realized that computers not understand programs written in high-level languages, as they understand only sequences of 0s and 1s So there’s a need for a way to translate a program written in a high-level language to machine language The translation is accomplished by a compiler, an interpreter, or a combination of both A compiler is a program that translates programs written in a high-level programming language into machine language Compiling a program is an overloaded phrase Typically, it means translating a program written in a high-level language into machine language Sometimes it is used to mean translating a program written in a high-level programming language into a lower-level programming language, which is not necessarily the machine language The code that is generated by a compiler is called compiled code The compiled program is executed by the computer Another way to execute a program written in high-level programming language is to use an interpreter An interpreter does not translate the whole program into machine language at once Rather, it reads one instruction written in a high-level programming language at a time, translates it into machine language, and executes it You can view an interpreter as a simulator Sometimes a combination of a compiler and an interpreter may be used to compile and run a program written in a high-level language For example, a program written in Java is compiled into an intermediate language called bytecode An interpreter, specifically called a Java Virtual Machine (JVM) for the Java platform, is used to interpret the bytecode and execute it An interpreted program runs slower than a compiled program Most of the JVMs today use just-in-time compilers (JIT), which compile the entire Java program into machine language as needed Sometimes another kind of compiler, which is called an ahead-of-time (AOT) compiler, is used to compile a program in an intermediate language (e.g Java bytecode) to machine language Figure 1-2 shows the relationship between the source code, a compiler, and the machine code Figure 1-2.  The relationship between source code, a compiler, and machine code Components of a Programming Language A programming language is a system of notations that are used to write instructions for computers It can be described using three components: • Syntax • Semantics • Pragmatics The syntax part deals with forming valid programming constructs using available notations The semantics part deals with the meaning of the programming constructs The pragmatics part deals with the use of the programming language in practice Like a written language (e.g English), a programming language has a vocabulary and grammar The vocabulary of a programming language consists of a set of words, symbols, and punctuation marks The grammar of a programming language defines rules on how to use the vocabulary of the language to form valid programming constructs You can think of a valid programming construct in a programming language like a sentence in a written language A sentence in a written language is formed using the vocabulary and grammar of the language Similarly, a programming construct is formed using the vocabulary and the grammar of the programming language The vocabulary and the rules to use that vocabulary to form valid programming constructs are known as the syntax of the programming language www.it-ebooks.info ■ Contents ■■Chapter 8: Wrapper Classes������������������������������������������������������������������������������������������317 Wrapper Classes�����������������������������������������������������������������������������������������������������������������������317 Numeric Wrapper Classes��������������������������������������������������������������������������������������������������������������������������������� 320 The Character Wrapper Class���������������������������������������������������������������������������������������������������������������������������� 322 The Boolean Wrapper Class������������������������������������������������������������������������������������������������������������������������������� 323 Unsigned Numeric Operations���������������������������������������������������������������������������������������������������324 Autoboxing and Unboxing���������������������������������������������������������������������������������������������������������326 Beware of Null Values���������������������������������������������������������������������������������������������������������������328 Overloaded Methods and Autoboxing/Unboxing������������������������������������������������������������������������329 Comparison Operators and AutoBoxing/Unboxing��������������������������������������������������������������������331 Collections and Autoboxing/Unboxing���������������������������������������������������������������������������������������333 Summary�����������������������������������������������������������������������������������������������������������������������������������334 ■■Chapter 9: Exception Handling��������������������������������������������������������������������������������������335 What Is an Exception?���������������������������������������������������������������������������������������������������������������335 An Exception Is an Object����������������������������������������������������������������������������������������������������������337 Using a try-catch Block�������������������������������������������������������������������������������������������������������������338 Transfer of Control���������������������������������������������������������������������������������������������������������������������341 Exception Class Hierarchy���������������������������������������������������������������������������������������������������������341 Arranging Multiple catch Blocks�����������������������������������������������������������������������������������������������343 Checked and Unchecked Exceptions����������������������������������������������������������������������������������������346 Checked Exception - Catch or Declare��������������������������������������������������������������������������������������349 Checked Exceptions and Initializers������������������������������������������������������������������������������������������355 Throwing an Exception��������������������������������������������������������������������������������������������������������������357 Creating an Exception Class������������������������������������������������������������������������������������������������������357 The finally Block������������������������������������������������������������������������������������������������������������������������361 Rethrowing an Exception����������������������������������������������������������������������������������������������������������365 Analysis of Rethrown Exceptions����������������������������������������������������������������������������������������������368 Throwing too Many Exceptions�������������������������������������������������������������������������������������������������368 xiv www.it-ebooks.info ■ Contents Accessing the Stack of a Thread�����������������������������������������������������������������������������������������������369 The try-with-resources Block����������������������������������������������������������������������������������������������������372 A Multi-Catch Block�������������������������������������������������������������������������������������������������������������������376 Summary�����������������������������������������������������������������������������������������������������������������������������������377 ■■Chapter 10: Assertions��������������������������������������������������������������������������������������������������379 What Is an Assertion?����������������������������������������������������������������������������������������������������������������379 Testing Assertions���������������������������������������������������������������������������������������������������������������������381 Enabling/Disabling Assertions���������������������������������������������������������������������������������������������������382 Using Assertions������������������������������������������������������������������������������������������������������������������������384 Checking for Assertion Status���������������������������������������������������������������������������������������������������385 Summary�����������������������������������������������������������������������������������������������������������������������������������386 ■■Chapter 11: Strings�������������������������������������������������������������������������������������������������������387 What is a String?�����������������������������������������������������������������������������������������������������������������������387 String Literals����������������������������������������������������������������������������������������������������������������������������387 Escape Sequence Characters in String Literals������������������������������������������������������������������������388 Unicode Escapes in String Literals��������������������������������������������������������������������������������������������388 What is a CharSequence?���������������������������������������������������������������������������������������������������������389 Creating String Objects�������������������������������������������������������������������������������������������������������������389 Length of a String����������������������������������������������������������������������������������������������������������������������390 String Literals Are String Objects����������������������������������������������������������������������������������������������390 String Objects Are Immutable���������������������������������������������������������������������������������������������������391 Comparing Two Strings�������������������������������������������������������������������������������������������������������������392 String Pool���������������������������������������������������������������������������������������������������������������������������������393 String Operations����������������������������������������������������������������������������������������������������������������������395 Getting the Character at an Index���������������������������������������������������������������������������������������������������������������������� 395 Testing Strings for Equality�������������������������������������������������������������������������������������������������������������������������������� 396 Testing a String to be Empty������������������������������������������������������������������������������������������������������������������������������ 397 Changing the Case��������������������������������������������������������������������������������������������������������������������������������������������� 397 xv www.it-ebooks.info ■ Contents Searching for a String���������������������������������������������������������������������������������������������������������������������������������������� 398 Representing Values as Strings������������������������������������������������������������������������������������������������������������������������� 398 Getting a Substring�������������������������������������������������������������������������������������������������������������������������������������������� 398 Trimming a String���������������������������������������������������������������������������������������������������������������������������������������������� 398 Replacing Part of a String���������������������������������������������������������������������������������������������������������������������������������� 399 Matching Start and End of a String������������������������������������������������������������������������������������������������������������������� 399 Splitting and Joining Strings�����������������������������������������������������������������������������������������������������400 Strings in a switch Statement���������������������������������������������������������������������������������������������������401 Testing a String for Palindrome�������������������������������������������������������������������������������������������������403 StringBuilder and StringBuffer��������������������������������������������������������������������������������������������������404 String Concatenation Operator (+)��������������������������������������������������������������������������������������������408 Language-Sensitive String Comparison������������������������������������������������������������������������������������408 Summary�����������������������������������������������������������������������������������������������������������������������������������409 ■■Chapter 12: Dates and Times�����������������������������������������������������������������������������������������411 The Date-Time API���������������������������������������������������������������������������������������������������������������������411 Design Principles�����������������������������������������������������������������������������������������������������������������������412 A Quick Example�����������������������������������������������������������������������������������������������������������������������412 Evolution of Timekeeping����������������������������������������������������������������������������������������������������������414 Time Zones and Daylight Saving Time��������������������������������������������������������������������������������������416 Calendar Systems���������������������������������������������������������������������������������������������������������������������417 The Julian Calendar������������������������������������������������������������������������������������������������������������������������������������������� 418 The Gregorian Calendar������������������������������������������������������������������������������������������������������������������������������������� 418 ISO-8601 Standards for Datetime���������������������������������������������������������������������������������������������419 Exploring the New Date-Time API���������������������������������������������������������������������������������������������421 The ofXXX( ) Methods����������������������������������������������������������������������������������������������������������������������������������������� 421 The from( ) Methods������������������������������������������������������������������������������������������������������������������������������������������� 422 The withXXX( ) Methods������������������������������������������������������������������������������������������������������������������������������������� 422 The getXXX( ) Methods��������������������������������������������������������������������������������������������������������������������������������������� 422 xvi www.it-ebooks.info ■ Contents The toXXX( ) Methods����������������������������������������������������������������������������������������������������������������������������������������� 422 The atXXX( ) Methods����������������������������������������������������������������������������������������������������������������������������������������� 423 The plusXXX( ) and minusXXX( ) Methods����������������������������������������������������������������������������������������������������������� 423 The multipliedBy( ), dividedBy( ), and negated( ) Methods���������������������������������������������������������������������������������� 424 Instants and Durations��������������������������������������������������������������������������������������������������������������424 Human-Scale Time��������������������������������������������������������������������������������������������������������������������427 The ZoneOffset Class ���������������������������������������������������������������������������������������������������������������������������������������� 427 The ZoneId Class����������������������������������������������������������������������������������������������������������������������������������������������� 429 Useful Datetime-Related Enums ����������������������������������������������������������������������������������������������������������������������� 431 Local Date, Time, and Datetime������������������������������������������������������������������������������������������������������������������������� 436 Offset Time and Datetime���������������������������������������������������������������������������������������������������������������������������������� 439 Zoned Datetime������������������������������������������������������������������������������������������������������������������������������������������������� 440 Same Instant, Different Times���������������������������������������������������������������������������������������������������443 Clocks����������������������������������������������������������������������������������������������������������������������������������������444 Periods��������������������������������������������������������������������������������������������������������������������������������������445 Period Between Two Dates and Times��������������������������������������������������������������������������������������448 Partials��������������������������������������������������������������������������������������������������������������������������������������449 Adjusting Dates�������������������������������������������������������������������������������������������������������������������������452 Querying Datetime Objects�������������������������������������������������������������������������������������������������������457 Non-ISO Calendar Systems�������������������������������������������������������������������������������������������������������462 Formatting Dates and Times�����������������������������������������������������������������������������������������������������463 Using Predefined Formatters����������������������������������������������������������������������������������������������������������������������������� 463 Using the format( ) Method of Datetime Classes����������������������������������������������������������������������������������������������� 465 Using User-Defined Patterns����������������������������������������������������������������������������������������������������������������������������� 466 Using Locale Specific Formats�������������������������������������������������������������������������������������������������������������������������� 471 Using the DateTimeFormatterBuilder Class������������������������������������������������������������������������������������������������������� 473 Parsing Dates and Times�����������������������������������������������������������������������������������������������������������474 xvii www.it-ebooks.info ■ Contents Legacy Datetime Classes����������������������������������������������������������������������������������������������������������477 The Date Class��������������������������������������������������������������������������������������������������������������������������������������������������� 477 The Calendar Class�������������������������������������������������������������������������������������������������������������������������������������������� 478 The add( ) Method���������������������������������������������������������������������������������������������������������������������������������������������� 479 The roll( ) Method����������������������������������������������������������������������������������������������������������������������������������������������� 479 Interoperability with Legacy Datetime Classes�������������������������������������������������������������������������481 Summary�����������������������������������������������������������������������������������������������������������������������������������484 ■■Chapter 13: Formatting Data�����������������������������������������������������������������������������������������485 Formatting Dates�����������������������������������������������������������������������������������������������������������������������485 Formatting Numbers�����������������������������������������������������������������������������������������������������������������492 Printf-style Formatting��������������������������������������������������������������������������������������������������������������495 The Big Picture�������������������������������������������������������������������������������������������������������������������������������������������������� 495 The Details��������������������������������������������������������������������������������������������������������������������������������������������������������� 498 Referencing an Argument inside a Format Specifier����������������������������������������������������������������������������������������� 500 Using Flags in a Format Specifier���������������������������������������������������������������������������������������������������������������������� 504 Conversion Characters�������������������������������������������������������������������������������������������������������������������������������������� 505 Summary�����������������������������������������������������������������������������������������������������������������������������������518 ■■Chapter 14: Regular Expressions����������������������������������������������������������������������������������519 What Is a Regular Expression?��������������������������������������������������������������������������������������������������519 Metacharacters�������������������������������������������������������������������������������������������������������������������������522 Character Classes���������������������������������������������������������������������������������������������������������������������523 Predefined Character Classes��������������������������������������������������������������������������������������������������������������������������� 523 More Powers to Regular Expressions����������������������������������������������������������������������������������������524 Compiling Regular Expressions������������������������������������������������������������������������������������������������������������������������� 524 Creating a Matcher�������������������������������������������������������������������������������������������������������������������������������������������� 526 Matching the Pattern����������������������������������������������������������������������������������������������������������������������������������������� 526 Beware of Backslashes�������������������������������������������������������������������������������������������������������������529 Quantifiers in Regular Expressions�������������������������������������������������������������������������������������������529 Matching Boundaries����������������������������������������������������������������������������������������������������������������530 xviii www.it-ebooks.info ■ Contents Groups and Back Referencing���������������������������������������������������������������������������������������������������531 Using Named Groups�����������������������������������������������������������������������������������������������������������������535 Resetting the Matcher���������������������������������������������������������������������������������������������������������������538 Final Words on E-mail Validations���������������������������������������������������������������������������������������������538 Find-and-Replace Using Regular Expressions��������������������������������������������������������������������������538 Summary�����������������������������������������������������������������������������������������������������������������������������������542 ■■Chapter 15: Arrays��������������������������������������������������������������������������������������������������������543 What Is an Array?����������������������������������������������������������������������������������������������������������������������543 Arrays Are Objects���������������������������������������������������������������������������������������������������������������������544 Accessing Array Elements���������������������������������������������������������������������������������������������������������546 Length of an Array���������������������������������������������������������������������������������������������������������������������546 Initializing Array Elements���������������������������������������������������������������������������������������������������������547 Beware of Reference Type Arrays���������������������������������������������������������������������������������������������549 Explicit Array Initialization���������������������������������������������������������������������������������������������������������551 Limitations of Using Arrays�������������������������������������������������������������������������������������������������������552 Variable-Length Arrays��������������������������������������������������������������������������������������������������������������554 Passing an Array as a Parameter����������������������������������������������������������������������������������������������558 Array Parameter Reference������������������������������������������������������������������������������������������������������������������������������� 562 Elements of the Array Parameter����������������������������������������������������������������������������������������������������������������������� 563 The Object Referred by the Array Parameter Elements������������������������������������������������������������������������������������� 564 Command-Line Arguments��������������������������������������������������������������������������������������������������������566 Multi-Dimensional Arrays����������������������������������������������������������������������������������������������������������570 Accessing Elements of a Multi-Dimensional Array�������������������������������������������������������������������������������������������� 573 Initializing Multi-Dimensional Arrays����������������������������������������������������������������������������������������������������������������� 574 Enhanced for Loop for Arrays����������������������������������������������������������������������������������������������������574 Array Declaration Syntax�����������������������������������������������������������������������������������������������������������575 Runtime Array Bounds Checks��������������������������������������������������������������������������������������������������576 What Is the Class of an Array Object�����������������������������������������������������������������������������������������577 xix www.it-ebooks.info ■ Contents Array Assignment Compatibility������������������������������������������������������������������������������������������������579 Converting an ArrayList/Vector to an Array�������������������������������������������������������������������������������581 Summary�����������������������������������������������������������������������������������������������������������������������������������582 ■■Chapter 16: Inheritance�������������������������������������������������������������������������������������������������583 What is Inheritance?�����������������������������������������������������������������������������������������������������������������583 Object Class is the Default Superclass��������������������������������������������������������������������������������������586 Inheritance and Hierarchical Relationship��������������������������������������������������������������������������������587 What Is Inherited by a Subclass?����������������������������������������������������������������������������������������������588 Upcasting and Downcasting������������������������������������������������������������������������������������������������������589 The instanceof Operator������������������������������������������������������������������������������������������������������������593 Binding��������������������������������������������������������������������������������������������������������������������������������������596 Early Binding����������������������������������������������������������������������������������������������������������������������������������������������������� 596 Late Binding������������������������������������������������������������������������������������������������������������������������������������������������������� 599 Method Overriding���������������������������������������������������������������������������������������������������������������������602 Method Overriding Rule #1�������������������������������������������������������������������������������������������������������������������������������� 604 Method Overriding Rule #2�������������������������������������������������������������������������������������������������������������������������������� 604 Method Overriding Rule #3�������������������������������������������������������������������������������������������������������������������������������� 604 Method Overriding Rule #4�������������������������������������������������������������������������������������������������������������������������������� 604 Method Overriding Rule #5�������������������������������������������������������������������������������������������������������������������������������� 605 Method Overriding Rule #6�������������������������������������������������������������������������������������������������������������������������������� 605 Accessing Overridden Method��������������������������������������������������������������������������������������������������608 Method Overloading������������������������������������������������������������������������������������������������������������������610 Inheritance and Constructors����������������������������������������������������������������������������������������������������615 Method Hiding���������������������������������������������������������������������������������������������������������������������������622 Field Hiding�������������������������������������������������������������������������������������������������������������������������������624 Disabling Inheritance ���������������������������������������������������������������������������������������������������������������628 Abstract Classes and Methods��������������������������������������������������������������������������������������������������629 Method Overriding and Generic Method Signatures�����������������������������������������������������������������636 Typo Danger in Method Overriding��������������������������������������������������������������������������������������������638 xx www.it-ebooks.info ■ Contents Is-a, has-a, and part-of Relationships���������������������������������������������������������������������������������������639 No Multiple Inheritance of Classes��������������������������������������������������������������������������������������������641 Summary�����������������������������������������������������������������������������������������������������������������������������������642 ■■Chapter 17: Interfaces���������������������������������������������������������������������������������������������������643 What Is an Interface?����������������������������������������������������������������������������������������������������������������643 Proposed Solution #1���������������������������������������������������������������������������������������������������������������������������������������� 645 Proposed Solution #2���������������������������������������������������������������������������������������������������������������������������������������� 647 Proposed Solution #3���������������������������������������������������������������������������������������������������������������������������������������� 647 An Ideal Solution������������������������������������������������������������������������������������������������������������������������������������������������ 648 Declaring an Interface���������������������������������������������������������������������������������������������������������������652 Declaring Interface Members����������������������������������������������������������������������������������������������������653 Constant Fields Declarations����������������������������������������������������������������������������������������������������������������������������� 653 Methods Declarations���������������������������������������������������������������������������������������������������������������������������������������� 655 Nested Type Declarations���������������������������������������������������������������������������������������������������������������������������������� 662 An Interface Defines a New Type�����������������������������������������������������������������������������������������������664 Implementing an Interface��������������������������������������������������������������������������������������������������������666 Implementing Interface Methods����������������������������������������������������������������������������������������������670 Implementing Multiple Interfaces���������������������������������������������������������������������������������������������673 Partially Implementing an Interface������������������������������������������������������������������������������������������676 The Supertype-Subtype Relationship����������������������������������������������������������������������������������������677 Interface Inheritance�����������������������������������������������������������������������������������������������������������������678 The Superinterface-Subinterface Relationship�������������������������������������������������������������������������684 Inheriting Conflicting Implementations�������������������������������������������������������������������������������������685 The Superclass Always Wins����������������������������������������������������������������������������������������������������������������������������� 685 The Most Specific Superinterface Wins������������������������������������������������������������������������������������������������������������� 687 The Class Must Override the Conflicting Method���������������������������������������������������������������������������������������������� 688 The instanceof Operator������������������������������������������������������������������������������������������������������������689 Marker Interfaces����������������������������������������������������������������������������������������������������������������������692 Functional Interfaces�����������������������������������������������������������������������������������������������������������������693 xxi www.it-ebooks.info ■ Contents Comparing Objects��������������������������������������������������������������������������������������������������������������������694 Using the Comparable Interface������������������������������������������������������������������������������������������������������������������������ 694 Using the Comparator Interface������������������������������������������������������������������������������������������������������������������������� 696 Polymorphism—One Object, Many Views���������������������������������������������������������������������������������701 Dynamic Binding and Interfaces�����������������������������������������������������������������������������������������������703 Summary�����������������������������������������������������������������������������������������������������������������������������������704 ■■Chapter 18: Enum Types������������������������������������������������������������������������������������������������705 What Is an Enum Type?�������������������������������������������������������������������������������������������������������������705 Superclass of an Enum Type�����������������������������������������������������������������������������������������������������709 Using Enum Types in switch Statements����������������������������������������������������������������������������������712 Associating Data and Methods to Enum Constants�������������������������������������������������������������������713 Associating a Body to an Enum Constant����������������������������������������������������������������������������������715 Comparing Two Enum Constants�����������������������������������������������������������������������������������������������719 Nested Enum Types�������������������������������������������������������������������������������������������������������������������720 Implementing an Interface to an Enum Type�����������������������������������������������������������������������������722 Reverse Lookup for Enum Constants����������������������������������������������������������������������������������������723 Range of Enum Constants���������������������������������������������������������������������������������������������������������724 Summary�����������������������������������������������������������������������������������������������������������������������������������725 ■■Appendix A: Character Encodings���������������������������������������������������������������������������������727 ASCII������������������������������������������������������������������������������������������������������������������������������������������728 8-bit Character Sets������������������������������������������������������������������������������������������������������������������733 Universal Multiple-Octet Coded Character Set (UCS)����������������������������������������������������������������733 UCS-2���������������������������������������������������������������������������������������������������������������������������������������������������������������� 734 UCS-4���������������������������������������������������������������������������������������������������������������������������������������������������������������� 734 UTF-16 (UCS Transformation Format 16)����������������������������������������������������������������������������������������������������������� 734 UTF-8 (UCS Transformation Format 8)��������������������������������������������������������������������������������������������������������������� 735 Java and Character Encodings��������������������������������������������������������������������������������������������������735 xxii www.it-ebooks.info ■ Contents ■■Appendix B: Documentation Comments������������������������������������������������������������������������739 Writing Documentation Comments�������������������������������������������������������������������������������������������740 List of Block and Inline Tags������������������������������������������������������������������������������������������������������742 @author ������������������������������������������������������������������������������������������������������������������������������ 742 @deprecated ��������������������������������������������������������������������������������������������������������������������� 743 @exception ������������������������������������������������������������������������������������������������������� 743 @param ���������������������������������������������������������������������������������������������������� 743 @return �������������������������������������������������������������������������������������������������������������������������������������� 744 @see �������������������������������������������������������������������������������������������������������������������������������������������� 744 @serial ������������������������������������������������������������������������������������������������ 745 @serialData ����������������������������������������������������������������������������������������������������������������������� 746 @serialField �������������������������������������������������������������������������� 746 @since ��������������������������������������������������������������������������������������������������������������������������������������� 747 @throws ������������������������������������������������������������������������������������������������������������ 747 @version ���������������������������������������������������������������������������������������������������������������������������������� 748 {@code }������������������������������������������������������������������������������������������������������������������������������������������������� 748 {@docRoot}�������������������������������������������������������������������������������������������������������������������������������������������������������� 748 {@inheritDoc}���������������������������������������������������������������������������������������������������������������������������������������������������� 748 {@link }����������������������������������������������������������������������������������������������������� 750 {@linkplain }���������������������������������������������������������������������������������������������� 750 {@literal }������������������������������������������������������������������������������������������������������������������������������������������������ 750 {@value }����������������������������������������������������������������������������������������������������������������������� 750 Documenting Packages�������������������������������������������������������������������������������������������������������������751 com/jdojo/utility/package-info.java file������������������������������������������������������������������������������������������������������������� 751 com/jdojo/utility/package.html file�������������������������������������������������������������������������������������������������������������������� 752 Overview Documentation����������������������������������������������������������������������������������������������������������752 Including Unprocessed Files in Documentation������������������������������������������������������������������������752 Skipping Source Files Processing���������������������������������������������������������������������������������������������752 An Example of Documentation Comments��������������������������������������������������������������������������������753 Running the javadoc Tool����������������������������������������������������������������������������������������������������������755 xxiii www.it-ebooks.info ■ Contents Generated Documentation Files������������������������������������������������������������������������������������������������757 Viewing Generated HTML Documentation���������������������������������������������������������������������������������758 Summary�����������������������������������������������������������������������������������������������������������������������������������758 ■■Appendix C: Compact Profiles���������������������������������������������������������������������������������������759 Enhancement in the javac Command����������������������������������������������������������������������������������������762 Enhancement in Java API Documentation ��������������������������������������������������������������������������������765 Checking for Profile Dependencies�������������������������������������������������������������������������������������������765 Creating Custom JREs Using the EJDK�������������������������������������������������������������������������������������768 Installing EJDK��������������������������������������������������������������������������������������������������������������������������������������������������� 768 Running the jrecreate Command����������������������������������������������������������������������������������������������������������������������� 769 Deploying the Custom JRE�������������������������������������������������������������������������������������������������������������������������������� 773 Running the Custom JRE����������������������������������������������������������������������������������������������������������������������������������� 773 Index���������������������������������������������������������������������������������������������������������������������������������775 xxiv www.it-ebooks.info Foreword Java is a very versatile programming language It began over 20 years ago in the depths of Sun Microsystems, which has since been taken over by Oracle The original version of Java—including the compiler, runtime, source code, and documentation—could fit onto a single 720KB floppy disk Nowadays, the closest thing to a floppy disk one can find is one of those micro SD cards you plug into your phone, and you’ll be lucky if the whole of the Java world could fit on it Instead of just the single desktop version of the Java platform, today you’ll find separate versions for micro devices and the enterprise, and even multiple desktop profiles You’ll find specialized libraries for security, databases, 3D graphics, TV, messaging, expressions, e-mail, and so many other things This large library set is what makes the Java platform so great You don’t need to keep reinventing the wheel More than likely, somebody else has already done it for you Most of the custom code done these days is for the business logic behind a project, not the management of data structures nor the marshaling and unmarshalling of data sent across the wire This large library set is also what makes learning the Java platform so hard There is just so much out there! You must focus on a small part of it to get started before you can tackle Java as a whole This book takes a focused approach to learning the fundamentals of the Java platform Author Kishori Sharan has weeded through all there is to the core Java development environment and focuses on those parts you need to know to get yourself started with object-oriented development using the Java programming language There is certainly much more out there than can fit in one introductory text Until you’re comfortable with the basics, just don’t worry about the rest You’ll learn about them soon enough, when you need to For now, read on, and you’ll be glad you picked up this text —John Zukowski Java Author and Senior Software Engineer, TripAdvisor.com @JavaJohnZ xxv www.it-ebooks.info About the Author Kishori Sharan is a senior software consultant at Doozer, Inc He holds a Master of Science in Computer Information Systems from Troy State University in Montgomery, Alabama He is a Sun Certified Java programmer and Sybase Certified PowerBuilder Developer Professional He specializes in developing enterprise application using Java SE, Java EE, PowerBuilder, and Oracle database He has been working in the software industry for over 16 years He has helped several clients to migrate legacy applications to the Web He loves writing technical books in his free time He maintains his web site at www.jdojo.com where he posts blogs on Java and JavaFX xxvii www.it-ebooks.info About the Technical Reviewer John Zukowski is currently a software engineer with TripAdvisor, the world’s largest travel site (www.tripadvisor.com) He has been playing with Java technologies for 20 years now and is the author of 10 Java-related books His books cover Java 6, Java Swing, Java Collections, and JBuilder from Apress, Java AWT from O’Reilly, and introductory Java from Sybex He lives outside Boston, Massachusetts and has a Master’s degree in software engineering from The Johns Hopkins University You can follow him on Twitter at http://twitter.com/javajohnz xxix www.it-ebooks.info Acknowledgments My heartfelt thanks are due to my father-in-law, Mr Jim Baker, for displaying extraordinary patience in reading the initial draft of the book I am very grateful to him for spending so much of his valuable time teaching me quite a bit of English grammar that helped me produce better material I would like to thank my friend Richard Castillo for his hard work in reading my initial draft of the book and weeding out several mistakes Richard was instrumental in running all examples and pointing out errors My wife, Ellen, has always been patient when I spent long hours at my computer desk working on this book She would happily bring me snacks, fruit, and a glass of water every 30 minutes or so to sustain me during that period I want to thank her for all her support in writing this book She also deserves my sincere thanks for letting me sometimes seclude myself on weekends so I could focus on this book I would like to thank my family members and friends for their encouragement and support for writing this book: my elder brothers, Janki Sharan and Dr Sita Sharan; my sister and brother-in-law, Ratna and Abhay; my nephews Babalu, Dabalu, Gaurav, Saurav, and Chitranjan; my friends Shivashankar Ravindranath, Kannan Somasekar, Mahbub Choudhury, Biju Nair, Srinivas Kakkera, Anil Kumar Singh, Chris Coley, Willie Baptiste, Rahul Jain, Larry Brewster, Greg Langham, Ram Atmakuri, LaTondra Okeke, Rahul Nagpal, Ravi Datla, Prakash Chandra, and many more friends not mentioned here My sincere thanks are due to the wonderful team at Apress for their support during the publication of this book Thanks to Anamika Panchoo, the Senior Coordinating Editor, for providing excellent support and for being exceptionally patient with me when I asked her so many questions in the beginning, Thanks to Matthew Moodie and John Zukovski for their technical insights and feedback during the editing process Last but not least, my sincere thanks to Steve Anglin, the Lead Editor at Apress, for taking the initiative for the publication of this book xxxi www.it-ebooks.info ... encounter with the Java programming language was during a one-week Java training session in 1997 I did not get a chance to use Java in a project until 1999 I read two Java books and took a Java Programmer... over 80 pages in Chapter 12 After finishing this book, to take your Java knowledge to the next level, two companion books are available by the author: Beginning Java Language Features (ISBN 9 78- 1-4302-66 58- 7)... (ISBN 9 78- 1-4302-66 58- 7) and Beginning Java APIs, Extensions, and Libraries (ISBN 9 78- 1-4302-6661-7) Audience This book is designed to be useful for anyone who wants to learn the Java programming

Ngày đăng: 12/03/2019, 11:48

Từ khóa liên quan

Mục lục

  • Contents at a Glance

  • Contents

  • Foreword

  • About the Author

  • About the Technical Reviewer

  • Introduction

  • Chapter 1: Programming Concepts

    • What Is Programming?

    • Components of a Programming Language

    • Programming Paradigms

      • Imperative Paradigm

      • Procedural Paradigm

      • Declarative Paradigm

      • Functional Paradigm

      • Logic Paradigm

      • Object-Oriented Paradigm

      • What Is Java?

      • The Object-Oriented Paradigm and Java

        • Abstraction

          • Abstraction for Hiding Complexities

          • Procedural Abstraction

          • Data Abstraction

          • Encapsulation and Information Hiding

          • Inheritance

Tài liệu cùng người dùng

Tài liệu liên quan