Learn Java for Android Development: Java 8 and Android 5 Edition
By Jeff Friesen
()
About this ebook
Android development is hot, and many programmers are interested in joining the fun. However, because this technology is based on Java, you should first obtain a solid grasp of the Java language and its APIs in order to improve your chances of succeeding as an effective Android app developer. This book helps you do that.
Each of the book’s 16 chapters provides an exercise section that gives you the opportunity to reinforce your understanding of the chapter’s material. Answers to the book’s more than 700 exercises are provided in an appendix. A second appendix provides a significant game-oriented Java application, which you can convert into an Android app.
Once you complete this one-of-a-kind book written by Jeff Friesen, an expert Java developer and JavaWorld.com columnist, you should be ready to begin your indie or professional Android app development journey.
Read more from Jeff Friesen
United States of LEGO®: A Brick Tour of America Rating: 4 out of 5 stars4/5Bricksy: Unauthorized Underground Brick Street Art Rating: 4 out of 5 stars4/5Learn Java for Android Development: Migrating Java SE Programming Skills to Mobile Development Rating: 0 out of 5 stars0 ratingsJava XML and JSON: Document Processing for Java SE Rating: 0 out of 5 stars0 ratings
Related to Learn Java for Android Development
Related ebooks
Java EE 7 Recipes: A Problem-Solution Approach Rating: 0 out of 5 stars0 ratingsModern Programming Made Easy: Using Java, Scala, Groovy, and JavaScript Rating: 0 out of 5 stars0 ratingsThe Business of iOS App Development: For iPhone, iPad and iPod touch Rating: 0 out of 5 stars0 ratingsLearn Java for Web Development: Modern Java Web Development Rating: 0 out of 5 stars0 ratingsPractical ASP.NET Web API Rating: 0 out of 5 stars0 ratingsMy First In Java Rating: 0 out of 5 stars0 ratingsBuilding React Apps with Server-Side Rendering: Use React, Redux, and Next to Build Full Server-Side Rendering Applications Rating: 0 out of 5 stars0 ratingsPro TypeScript: Application-Scale JavaScript Development Rating: 4 out of 5 stars4/5Beginning Backbone.js Rating: 3 out of 5 stars3/5C# Deconstructed: Discover how C# works on the .NET Framework Rating: 0 out of 5 stars0 ratings.NET DevOps for Azure: A Developer's Guide to DevOps Architecture the Right Way Rating: 0 out of 5 stars0 ratingsBeginning Android C++ Game Development Rating: 0 out of 5 stars0 ratingsJava Design Patterns: A Hands-On Experience with Real-World Examples Rating: 4 out of 5 stars4/5Pro ASP.NET 4.5 in C# Rating: 0 out of 5 stars0 ratingsAutomated Theorem Proving in Software Engineering Rating: 0 out of 5 stars0 ratingsASP.NET 3.5 CMS Development Rating: 0 out of 5 stars0 ratingsHandbook of Human Centric Visualization Rating: 0 out of 5 stars0 ratingsModern C++ Programming Rating: 0 out of 5 stars0 ratingsLearn C Programming from Scratch: A step-by-step methodology with problem solving approach (English Edition) Rating: 0 out of 5 stars0 ratings.NET IL Assembler Rating: 0 out of 5 stars0 ratingsBeginning DotNetNuke Skinning and Design Rating: 0 out of 5 stars0 ratingsDeveloping Applications with Azure Active Directory: Principles of Authentication and Authorization for Architects and Developers Rating: 0 out of 5 stars0 ratingsPython, PyGame, and Raspberry Pi Game Development Rating: 0 out of 5 stars0 ratingsCSS Mastery: Styling Web Pages Like a Pro Rating: 0 out of 5 stars0 ratingsC++ Cookbook: How to write great code with the latest C++ releases (English Edition) Rating: 0 out of 5 stars0 ratingsLearning AWS Lumberyard Game Development Rating: 0 out of 5 stars0 ratingsOpenCV Android Programming By Example Rating: 0 out of 5 stars0 ratingsTensor Analysis and Elementary Differential Geometry for Physicists and Engineers Rating: 0 out of 5 stars0 ratings
Programming For You
SQL QuickStart Guide: The Simplified Beginner's Guide to Managing, Analyzing, and Manipulating Data With SQL Rating: 4 out of 5 stars4/5Coding All-in-One For Dummies Rating: 4 out of 5 stars4/5Excel 101: A Beginner's & Intermediate's Guide for Mastering the Quintessence of Microsoft Excel (2010-2019 & 365) in no time! Rating: 0 out of 5 stars0 ratingsLearn to Code. Get a Job. The Ultimate Guide to Learning and Getting Hired as a Developer. Rating: 5 out of 5 stars5/5Excel : The Ultimate Comprehensive Step-By-Step Guide to the Basics of Excel Programming: 1 Rating: 5 out of 5 stars5/5Python Programming : How to Code Python Fast In Just 24 Hours With 7 Simple Steps Rating: 4 out of 5 stars4/5Linux: Learn in 24 Hours Rating: 5 out of 5 stars5/5Python: For Beginners A Crash Course Guide To Learn Python in 1 Week Rating: 4 out of 5 stars4/5Grokking Algorithms: An illustrated guide for programmers and other curious people Rating: 4 out of 5 stars4/5Spies, Lies, and Algorithms: The History and Future of American Intelligence Rating: 4 out of 5 stars4/5HTML in 30 Pages Rating: 5 out of 5 stars5/5Learn PowerShell in a Month of Lunches, Fourth Edition: Covers Windows, Linux, and macOS Rating: 5 out of 5 stars5/5C# Programming from Zero to Proficiency (Beginner): C# from Zero to Proficiency, #2 Rating: 0 out of 5 stars0 ratingsTiny Python Projects: Learn coding and testing with puzzles and games Rating: 4 out of 5 stars4/5HTML & CSS: Learn the Fundaments in 7 Days Rating: 4 out of 5 stars4/5SQL All-in-One For Dummies Rating: 3 out of 5 stars3/5JavaScript All-in-One For Dummies Rating: 5 out of 5 stars5/5iPhone For Dummies Rating: 0 out of 5 stars0 ratingsPython QuickStart Guide: The Simplified Beginner's Guide to Python Programming Using Hands-On Projects and Real-World Applications Rating: 0 out of 5 stars0 ratingsC# 7.0 All-in-One For Dummies Rating: 0 out of 5 stars0 ratingsSQL: For Beginners: Your Guide To Easily Learn SQL Programming in 7 Days Rating: 5 out of 5 stars5/5PYTHON: Practical Python Programming For Beginners & Experts With Hands-on Project Rating: 5 out of 5 stars5/5
Reviews for Learn Java for Android Development
0 ratings0 reviews
Book preview
Learn Java for Android Development - Jeff Friesen
Jeff FriesenLearn Java for Android Development10.1007/978-1-4302-6455-2© Apress 2014
Jeff Friesen
Learn Java for Android Development
A978-1-4302-6455-2_BookFrontmatter_Figa_HTML.pngJeff Friesen
ISBN 978-1-4302-6454-5e-ISBN 978-1-4302-6455-2
© Apress 2014
Learn Java for Android Development
President and Publisher: Paul Manning
Lead Editor: Steve Anglin
Development Editor: Gary Schwartz, Tom Welsh
Technical Reviewer: Chad Darby
Editorial Board: Steve Anglin, Mark Beckner, Ewan Buckingham, Gary Cornell, Louise Corrigan, James T. DeWolf, Jonathan Gennick, Jonathan Hassell, Robert Hutchinson, Michelle Lowman, James Markham, Matthew Moodie, Jeff Olson, Jeffrey Pepper, Douglas Pundick, Ben Renow-Clarke, Dominic Shakeshaft, Gwenan Spearing, Matt Wade, Steve Weiss
Coordinating Editor: Anamika Panchoo, Jill Balzano
Production Editor: Steve Weiss
Copy Editor: Mary Behr
Compositor: SPi Global
Indexer: SPi Global
Artist: SPi Global
Cover Designer: Anna Ishchenko
Distributed to the book trade worldwide by Springer Science+Business Media New York, 233 Spring Street, 6th Floor, New York, NY 10013. Phone 1-800-SPRINGER, fax (201) 348-4505, e-mail [email protected], or visit www.springeronline.com . Apress Media, LLC is a California LLC and the sole member (owner) is Springer Science + Business Media Finance Inc (SSBM Finance Inc). SSBM Finance Inc is a Delaware corporation.
For information on translations, please e-mail [email protected], or visit www.apress.com .
Apress and friends of ED books may be purchased in bulk for academic, corporate, or promotional use. eBook versions and licenses are also available for most titles. For more information, reference our Special Bulk Sales–eBook Licensing web page at www.apress.com/bulk-sales .
Any source code or other supplementary materials referenced by the author in this text is available to readers at www.apress.com . For detailed information about how to locate your book’s source code, go to www.apress.com/source-code/ .
This work is subject to copyright. All rights are reserved by the Publisher, whether the whole or part of the material is concerned, specifically the rights of translation, reprinting, reuse of illustrations, recitation, broadcasting, reproduction on microfilms or in any other physical way, and transmission or information storage and retrieval, electronic adaptation, computer software, or by similar or dissimilar methodology now known or hereafter developed. Exempted from this legal reservation are brief excerpts in connection with reviews or scholarly analysis or material supplied specifically for the purpose of being entered and executed on a computer system, for exclusive use by the purchaser of the work. Duplication of this publication or parts thereof is permitted only under the provisions of the Copyright Law of the Publisher's location, in its current version, and permission for use must always be obtained from Springer. Permissions for use may be obtained through RightsLink at the Copyright Clearance Center. Violations are liable to prosecution under the respective Copyright Law. Trademarked names, logos, and images may appear in this book. Rather than use a trademark symbol with every occurrence of a trademarked name, logo, or image we use the names, logos, and images only in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark. The images of the Android Robot (01 / Android Robot) are reproduced from work created and shared by Google and used according to terms described in the Creative Commons 3.0 Attribution License. Android and all Android and Google-based marks are trademarks or registered trademarks of Google, Inc., in the U.S. and other countries. Apress Media, L.L.C. is not affiliated with Google, Inc., and this book was written without endorsement from Google, Inc. The use in this publication of trade names, trademarks, service marks, and similar terms, even if they are not identified as such, is not to be taken as an expression of opinion as to whether or not they are subject to proprietary rights. While the advice and information in this book are believed to be true and accurate at the date of publication, neither the authors nor the editors nor the publisher can accept any legal responsibility for any errors or omissions that may be made. The publisher makes no warranty, express or implied, with respect to the material contained herein.
To you, dear reader!
I hope this book helps you achieve great success.
About the Author
A978-1-4302-6455-2_BookFrontmatter_Fig1_HTML.jpgJeff Friesen is a freelance tutor, author, and software developer with an emphasis on Java, Android, and HTML5. In addition to writing this book and its two predecessors, Jeff has written numerous articles on Java and other technologies for JavaWorld ( www.javaworld.com ), informIT ( www.informit.com ), java.net, SitePoint ( www.sitepoint.com ), and others. Jeff can be contacted via his web site at tutortutor.ca.
About the Technical Reviewer
A978-1-4302-6455-2_BookFrontmatter_Fig2_HTML.jpgChád Darby is an author, instructor, and speaker in the Java development world. As a recognized authority on Java applications and architectures, he has presented technical sessions at software development conferences worldwide (U.S., U.K., India, Russia, and Australia). In his 15 years as a professional software architect, he’s had the opportunity to work for Blue Cross/Blue Shield, Merck, Boeing, Red Hat, and a handful of startup companies.
Chád is a contributing author to several Java books, including Professional Java E-Commerce (Wrox Press), Beginning Java Networking (Wrox Press), and XML and Web Services Unleashed (Sams Publishing). Chád has Java certifications from Sun Microsystems and IBM. He holds a B.S. in Computer Science from Carnegie Mellon University.
Visit Chád's blog at www.luv2code.com to view his free video tutorials on Java. You can also follow him on Twitter at @darbyluvs2code.
Introduction
Smartphones and tablets are all the rage these days. Their popularity is largely due to their ability to run apps. Although the iPhone and iPad, with their growing collection of Objective-C based apps, had a head start, Android-based smartphones and tablets, with their growing collection of Java-based apps, have proven to be a strong competitor.
Not only are many iPhone/iPad app developers making money by selling their apps, but many Android app developers are also making money by selling similar apps. According to tech web sites such as The Register ( www.theregister.co.uk ), some Android app developers are making lots of money ( www.theregister.co.uk/2010/03/02/android_app_profit ).
In today’s challenging economic climate, you might like to try your hand at developing Android apps and make some money. If you have good ideas, perseverance, and some artistic talent (or perhaps know some talented individuals), you are already part of the way toward achieving this goal.
Tip
A good reason to consider Android app development over iPhone/iPad app development is the lower startup costs that you’ll incur with Android. For example, you don’t need to purchase a Mac on which to develop Android apps (a Mac is required for developing iPhone/iPad apps); your existing Windows, Linux, or Unix machine will do nicely.
Most importantly, you’ll need to possess a solid understanding of the Java language and foundational application programming interfaces (APIs) before jumping into Android. After all, Android apps are written in Java and interact with many of the standard Java APIs (such as threading and input/output APIs).
I wrote Learn Java for Android Development to give you a solid Java foundation that you can later extend with knowledge of Android architecture, API, and tool specifics. This book will give you a strong grasp of the Java language and the many important APIs that are fundamental to Android apps and other Java applications. It will also introduce you to key development tools.
Book Organization
The first edition of this book was organized into 10 chapters and 1 appendix. The second edition was organized into 14 chapters and 3 appendixes. This third edition is organized into 16 chapters and 2 appendixes with a bonus appendix on Android app development. Each chapter in each edition offers a set of exercises that you should complete to get the most benefit from its content. Their solutions are presented in Appendix A.
Chapter 1 introduces you to Java by first focusing on Java’s dual nature (language and platform). It then briefly introduces you to Oracle’s Java SE, Java EE, and Java ME editions of the Java platform. You next learn how to download and install the Java SE Development Kit (JDK), and you learn some Java basics by developing and playing with three simple Java applications. After receiving a brief introduction to the Eclipse IDE, you receive a brief introduction to Android.
Chapter 2 starts you on an in-depth journey of the Java language by focusing on language fundamentals. You first learn about simple application structure and then learn about comments, identifiers (and reserved words), types, variables, expressions (and literals), and statements.
Chapter 3 continues your journey by focusing on classes and objects. You learn how to declare a class and organize applications around multiple classes. You then learn how to construct objects from classes, declare fields in classes and access these fields, declare methods in classes and call them, initialize classes and objects, and remove objects when they’re no longer needed. You also learn more about arrays, which were first introduced in Chapter 2.
Chapter 4 adds to Chapter 3’s pool of object-based knowledge by introducing you to the language features that take you from object-based applications to object-oriented applications. Specifically, you learn about features related to inheritance, polymorphism, and interfaces. While exploring inheritance, you learn about Java’s ultimate superclass. Also, while exploring interfaces, you discover why they were included in the Java language; interfaces are not merely a workaround for Java’s lack of support for multiple implementation inheritance, but serve a higher purpose.
Chapter 5 introduces you to four categories of advanced language features: nested types, packages, static imports, and exceptions.
Chapter 6 introduces you to four additional advanced language feature categories: assertions, annotations, generics, and enums.
Chapter 7 begins a trend that focuses more on APIs than language features. This chapter first introduces you to Java’s Math and StrictMath math-oriented types. It then explores Number and its various subtypes (such as Integer, Double, and BigDecimal). Next you explore the string-oriented types (String, StringBuffer, and StringBuilder) followed by the System type. Finally, you explore the Thread class and related types for creating multithreaded applications.
Chapter 8 continues to explore Java’s basic APIs by focusing on the Random class for generating random numbers; the References API, Reflection, the StringTokenizer class for breaking a string into smaller components; and the Timer and TimerTask classes for occasionally or repeatedly executing tasks.
Chapter 9 focuses exclusively on Java’s Collections Framework, which provides you with a solution for organizing objects in lists, sets, queues, and maps. You also learn about collection-oriented utility classes and review Java’s legacy utility types.
Chapter 10 focuses exclusively on Java’s Concurrency Utilities. After receiving an introduction to this framework, you explore executors, synchronizers (such as countdown latches), concurrent collections, the Locking Framework, and atomic variables (where you discover compare-and-swap).
Chapter 11 is all about classic input/output (I/O), largely from a file perspective. In this chapter, you explore classic I/O in terms of the File class, RandomAccessFile class, various stream classes, and various writer/reader classes. My discussion of stream I/O includes coverage of Java’s object serialization and deserialization mechanisms.
Chapter 12 continues to explore classic I/O by focusing on networks. You learn about the Socket, ServerSocket, DatagramSocket, and MulticastSocket classes along with related types. You also learn about the URL class for achieving networked I/O at a higher level and learn about the related URI class. After learning about the low-level NetworkInterface and InterfaceAddress classes, you explore cookie management, in terms of the CookieHandler and CookieManager classes, and the CookiePolicy and CookieStore interfaces.
Chapter 13 introduces you to New I/O. You learn about buffers, channels, selectors, regular expressions, charsets, and the Formatter and Scanner types in this chapter.
Chapter 14 focuses on databases. You first learn about the Java DB and SQLite database products, and then explore JDBC for communicating with databases created via these products.
Chapter 15 emphasizes Java’s support for XML. I first provide a tutorial on this topic where you learn about the XML declaration, elements and attributes, character references and CDATA sections, namespaces, comments and processing instructions, well-formed documents, and valid documents (in terms of Document Type Definition and XML Schema). I then show you how to parse XML documents via the SAX API, parse and create XML documents via the DOM API, parse XML documents via the XMLPULL V1 API (supported by Android as an alternative to Java’s StAX API), use the XPath API to concisely select nodes via location path expressions, and transform XML documents via XSLT.
Chapter 16 completes the chapter portion of this book by covering odds and ends. You first learn about useful Java 7 language features that I’ve successfully used in Android apps. Next, you explore classloaders, the Console class, design patterns (with emphasis on the Strategy pattern), double brace initialization, fluent interfaces, immutability, internationalization (in terms of locales; resource bundles; break iterators; collators; dates, time zones, and calendars; and formatters), the Logging API, the Preferences API, the Runtime and Process classes, the Java Native Interface, and the ZIP and JAR APIs.
Appendix A presents solutions to all of the exercises in Chapters 1 through 16.
Appendix B introduces you to application development in the context of Four of a Kind, a console-based card game.
Appendix C provides an introduction to Android app development. It gives you a chance to see how various Java language features and APIs are used in an Android context.
Unlike the other elements, Appendix C is not included in this book—it’s included with the book’s source code. Appendix C doesn't officially belong in Learn Java for Android Development because this book’s focus is to prepare you for getting into Android app development by teaching you the fundamentals of the Java language, and Appendix C goes beyond that focus by giving you a tutorial on Android app development. Besides, the presence of this appendix would cause the book to exceed the 1,200-page print-on-demand limit.
Note
You can download this book’s source code by pointing your web browser to www.apress.com/9781430264545 and clicking the Source Code tab followed by the Download Now link.
What Comes Next?
After you complete this book, I recommend that you check out Apress’s other Android-oriented books, such as Beginning Android 4 by Grant Allen (Apress, 2012), and learn more about developing Android apps. In that book, you learn Android basics and how to create innovative and salable applications for Android 4 mobile devices.
Thanks for purchasing this third (and my final) edition of Learn Java for Android Development. I hope you find it a helpful preparation for, and I wish you lots of success in achieving, a satisfying and lucrative career as an Android app developer.
Jeff Friesen, January 2014
Acknowledgments
I would like to thank Steve Anglin for contacting me to write this book, Jill Balzano and Anamika Panchoo for guiding me through the various aspects of this project, Tom Welsh and Gary Schwartz for helping me with the development of my chapters, and Chad Darby for his diligence in catching various flaws that would otherwise have made it into this book.
Contents
Chapter 1: Getting Started with Java 1
What Is Java? 2
Java Is a Language 2
Java Is a Platform 4
Java SE, Java EE, and Java ME 6
Installing the JDK and Exploring Example Applications 7
Hello, World! 9
DumpArgs 11
EchoText 13
Installing and Exploring the Eclipse IDE 15
Java Meets Android 20
What Is Android? 20
History of Android 21
Android Architecture 24
Android Says Hello 28
Summary 30
Chapter 2: Learning Language Fundamentals 31
Learning Application Structure 31
Learning Comments 33
Single-Line Comments 33
Multiline Comments 33
Javadoc Comments 34
Learning Identifiers 37
Learning Types 38
Primitive Types 38
User-Defined Types 41
Array Types 41
Learning Variables 42
Learning Expressions 43
Simple Expressions 43
Compound Expressions 49
Learning Statements 70
Assignment Statements 71
Decision Statements 71
Loop Statements 76
Break and Labeled Break Statements 81
Continue and Labeled Continue Statements 83
Summary 86
Chapter 3: Discovering Classes and Objects 89
Declaring Classes 89
Classes and Applications 91
Constructing Objects 92
Default Constructor 93
Explicit Constructors 93
Objects and Applications 97
Encapsulating State and Behaviors 98
Representing State via Fields 99
Representing Behaviors via Methods 107
Hiding Information 119
Initializing Classes and Objects 124
Class Initializers 124
Instance Initializers 126
Initialization Order 128
Collecting Garbage 131
Revisiting Arrays 134
Summary 139
Chapter 4: Discovering Inheritance, Polymorphism, and Interfaces 141
Building Class Hierarchies 141
Extending Classes 142
The Ultimate Superclass 148
Composition 157
The Trouble with Implementation Inheritance 158
Changing Form 162
Upcasting and Late Binding 163
Abstract Classes and Abstract Methods 167
Downcasting and Runtime Type Identification 169
Covariant Return Types 172
Formalizing Class Interfaces 174
Declaring Interfaces 174
Implementing Interfaces 176
Extending Interfaces 180
Why Use Interfaces? 181
Summary 187
Chapter 5: Mastering Advanced Language Features, Part 1 189
Mastering Nested Types 189
Static Member Classes 189
Nonstatic Member Classes 193
Anonymous Classes 197
Local Classes 200
Inner Classes and Memory Leaks 202
Interfaces within Classes and Classes within Interfaces 203
Mastering Packages 205
What Are Packages? 206
The Package Statement 207
The Import Statement 207
Searching for Packages and Types 209
Playing with Packages 210
Packages and JAR Files 215
Mastering Static Imports 215
Mastering Exceptions 217
What Are Exceptions? 218
Representing Exceptions in Source Code 218
Throwing Exceptions 223
Handling Exceptions 226
Performing Cleanup 229
Summary 234
Chapter 6: Mastering Advanced Language Features, Part 2 235
Mastering Assertions 235
Declaring Assertions 236
Using Assertions 237
Avoiding Assertions 243
Enabling and Disabling Assertions 244
Mastering Annotations 245
Discovering Annotations 245
Declaring Annotation Types and Annotating Source Code 248
Processing Annotations 253
Mastering Generics 255
Collections and the Need for Type Safety 255
Generic Types 258
Generic Methods 267
Arrays and Generics 271
Mastering Enums 273
The Trouble with Traditional Enumerated Types 273
The Enum Alternative 275
The Enum Class 280
Summary 284
Chapter 7: Exploring the Basic APIs, Part 1 287
Exploring Math 287
StrictMath and strictfp 294
Exploring Number and Its Children 295
BigDecimal 295
BigInteger 301
Primitive Type Wrapper Classes 305
Exploring String, StringBuffer, and StringBuilder 314
String 314
StringBuffer and StringBuilder 318
Exploring System 322
Exploring Threads 324
Runnable and Thread 325
Synchronization 335
Thread-Local Variables 352
Summary 357
Chapter 8: Exploring the Basic APIs, Part 2 359
Exploring Random 359
Exploring References 362
Basic Terminology 362
Reference and ReferenceQueue 363
SoftReference 365
WeakReference 365
PhantomReference 366
Exploring Reflection 368
The Class Entry Point 368
Constructor, Field, and Method 378
Package 383
Array 388
Exploring StringTokenizer 388
Exploring Timer and TimerTask 391
Timer in Depth 392
TimerTask in Depth 395
Summary 399
Chapter 9: Exploring the Collections Framework 401
Exploring Collections Framework Fundamentals 401
Comparable vs. Comparator 402
Iterable and Collection 404
Exploring Lists 411
ArrayList 415
LinkedList 416
Exploring Sets 419
TreeSet 419
HashSet 420
EnumSet 425
Exploring Sorted Sets 428
Exploring Navigable Sets 435
Exploring Queues 438
PriorityQueue 440
Exploring Deques 443
ArrayDeque 447
Exploring Maps 448
TreeMap 452
HashMap 453
IdentityHashMap 463
WeakHashMap 465
EnumMap 467
Exploring Sorted Maps 468
Exploring Navigable Maps 471
Exploring the Arrays and Collections Utility APIs 475
Exploring the Legacy Collection APIs 479
Summary 486
Chapter 10: Exploring the Concurrency Utilities 487
Introducing the Concurrency Utilities 487
Exploring Executors 488
Exploring Synchronizers 497
Countdown Latches 497
Cyclic Barriers 500
Exchangers 505
Semaphores 509
Exploring the Concurrent Collections 515
Demonstrating BlockingQueue and ArrayBlockingQueue 516
Learning More About ConcurrentHashMap 518
Exploring the Locking Framework 518
Lock 519
ReentrantLock 521
Condition 524
ReadWriteLock 529
ReentrantReadWriteLock 529
Exploring Atomic Variables 533
Improving Performance with the Concurrency Utilities 535
Summary 538
Chapter 11: Performing Classic I/O 539
Working with the File API 539
Constructing File Instances 540
Learning About Stored Abstract Pathnames 542
Learning About a Pathname’s File or Directory 545
Obtaining Disk Space Information 546
Listing Directories 548
Creating and Manipulating Files and Directories 550
Setting and Getting Permissions 552
Exploring Miscellaneous Capabilities 554
Working with the RandomAccessFile API 556
Working with Streams 567
Stream Classes Overview 568
OutputStream and InputStream 569
ByteArrayOutputStream and ByteArrayInputStream 572
FileOutputStream and FileInputStream 573
PipedOutputStream and PipedInputStream 576
FilterOutputStream and FilterInputStream 579
BufferedOutputStream and BufferedInputStream 587
DataOutputStream and DataInputStream 588
Object Serialization and Deserialization 590
PrintStream 604
Standard I/O Revisited 606
Working with Writers and Readers 607
Writer and Reader Classes Overview 608
Writer and Reader 610
OutputStreamWriter and InputStreamReader 611
FileWriter and FileReader 612
Summary 620
Chapter 12: Accessing Networks 621
Accessing Networks via Sockets 622
Socket Addresses 624
Socket Options 625
Socket and ServerSocket 626
DatagramSocket and MulticastSocket 632
Accessing Networks via URLs 639
URL and URLConnection 639
URLEncoder and URLDecoder 643
URI 645
Accessing Network Interfaces and Interface Addresses 652
Managing Cookies 657
Summary 662
Chapter 13: Migrating to New I/O 665
Working with Buffers 666
Buffer and Its Children 666
Buffers in Depth 670
Working with Channels 681
Channel and Its Children 681
Channels in Depth 686
Working with Selectors 723
Selector Fundamentals 724
Selector Demonstration 728
Working with Regular Expressions 732
Pattern, PatternSyntaxException, and Matcher 732
Character Classes 737
Capturing Groups 738
Boundary Matchers and Zero-Length Matches 739
Quantifiers 740
Practical Regular Expressions 743
Working with Charsets 743
A Brief Review of the Fundamentals 743
Working with Charsets 744
Charsets and the String Class 750
Working with Formatter and Scanner 751
Working with Formatter 752
Working with Scanner 756
Summary 761
Chapter 14: Accessing Databases 763
Introducing Java DB 764
Java DB Installation and Configuration 766
Java DB Demos 767
Java DB Command-Line Tools 769
Introducing SQLite 772
Accessing Databases via JDBC 774
Data Sources, Drivers, and Connections 774
Exceptions 777
Statements 781
Metadata 794
Summary 801
Chapter 15: Parsing, Creating, and Transforming XML Documents 803
What Is XML? 803
XML Declaration 805
Elements and Attributes 806
Character References and CDATA Sections 808
Namespaces 809
Comment and Processing Instructions 813
Well-Formed Documents 814
Valid Documents 814
Parsing XML Documents with SAX 824
Exploring the SAX API 825
Demonstrating the SAX API 831
Creating a Custom Entity Resolver 840
Parsing and Creating XML Documents with DOM 843
A Tree of Nodes 843
Exploring the DOM API 845
Parsing XML Documents with XMLPULL V1 855
Selecting XML Document Nodes with XPath 859
XPath Language Primer 859
XPath and DOM 863
Advanced XPath 868
Transforming XML Documents with XSLT 875
Exploring the XSLT API 875
Demonstrating the XSLT API 878
Summary 884
Chapter 16: Focusing on Odds and Ends 885
Focusing on Additional Language Features 885
Numeric Literal Enhancements 886
Switch-on-String 886
Diamond Operator 887
Multicatch 887
Automatic Resource Management 888
Focusing on Classloaders 891
Kinds of Classloaders 891
Class-Loading Mechanics 892
Playing with Classloaders 893
Classloader Difficulties 897
Classloaders and Resources 899
Focusing on Console 902
Focusing on Design Patterns 905
Understanding Strategy 906
Implementing Strategy 906
Focusing on Double Brace Initialization 909
Focusing on Fluent Interfaces 910
Focusing on Immutability 911
Focusing on Internationalization 914
Locales 915
Resource Bundles 916
Break Iterators 935
Collators 939
Dates, Time Zones, and Calendars 941
Formatters 948
Focusing on Logging 958
Logging API Overview 959
A Hierarchy of Loggers 960
Logging Messages 962
Filtering LogRecords 968
Handlers and Formatters 971
LogManager and Configuration 974
ErrorManager 977
Focusing on Preferences 981
Exploring Preferences 982
Focusing on Runtime and Process 986
Focusing on the Java Native Interface 990
Creating a Hybrid Library 990
Testing the Hybrid Library 994
Focusing on ZIP and JAR 995
Focusing on the ZIP API 995
Focusing on the JAR API 1003
Summary 1010
Appendix A: Solutions to Exercises 1015
Chapter 1: Getting Started with Java 1015
Chapter 2: Learning Language Fundamentals 1017
Chapter 3: Discovering Classes and Objects 1020
Chapter 4: Discovering Inheritance, Polymorphism, and Interfaces 1026
Chapter 5: Mastering Advanced Language Features, Part 1 1034
Chapter 6: Mastering Advanced Language Features, Part 2 1041
Chapter 7: Exploring the Basic APIs, Part 1 1046
Chapter 8: Exploring the Basic APIs, Part 2 1054
Chapter 9: Exploring the Collections Framework 1059
Chapter 10: Exploring the Concurrency Utilities 1065
Chapter 11: Performing Classic I/O 1073
Chapter 12: Accessing Networks 1083
Chapter 13: Migrating to New I/O 1088
Chapter 14: Accessing Databases 1096
Chapter 15: Parsing, Creating, and Transforming XML Documents 1100
Chapter 16: Focusing on Odds and Ends 1116
Appendix B: Four of a Kind 1127
Understanding Four of a Kind 1127
Modeling Four of a Kind in Pseudocode 1128
Converting Pseudocode to Java Code 1129
Compiling, Running, and Distributing FourOfAKind 1145
Index1149
Contents at a Glance
Chapter 1: Getting Started with Java 1
Chapter 2: Learning Language Fundamentals 31
Chapter 3: Discovering Classes and Objects 89
Chapter 4: Discovering Inheritance, Polymorphism, and Interfaces 141
Chapter 5: Mastering Advanced Language Features, Part 1 189
Chapter 6: Mastering Advanced Language Features, Part 2 235
Chapter 7: Exploring the Basic APIs, Part 1 287
Chapter 8: Exploring the Basic APIs, Part 2 359
Chapter 9: Exploring the Collections Framework 401
Chapter 10: Exploring the Concurrency Utilities 487
Chapter 11: Performing Classic I/O 539
Chapter 12: Accessing Networks 621
Chapter 13: Migrating to New I/O 665
Chapter 14: Accessing Databases 763
Chapter 15: Parsing, Creating, and Transforming XML Documents 803
Chapter 16: Focusing on Odds and Ends 885
Appendix A: Solutions to Exercises 1015
Appendix B: Four of a Kind 1127
Index1149
Jeff FriesenLearn Java for Android Development10.1007/978-1-4302-6455-2_1
© Jeff Friesen 2014
1. Getting Started with Java
Jeff Friesen¹
(1)
MB, Canada
Abstract
Android apps are written in Java and use various Java application program interfaces (APIs). Because you’ll want to write your own apps, but may be unfamiliar with the Java language and these APIs, this book teaches you about Java as a first step into Android app development. It provides you with Java language fundamentals and Java APIs that are useful when developing apps.
Android apps are written in Java and use various Java application program interfaces (APIs). Because you’ll want to write your own apps, but may be unfamiliar with the Java language and these APIs, this book teaches you about Java as a first step into Android app development. It provides you with Java language fundamentals and Java APIs that are useful when developing apps.
Note
This book illustrates Java concepts via non-Android Java applications. It’s easier for beginners to grasp these applications than corresponding Android apps. However, I also reveal a trivial Android app toward the end of this chapter for comparison purposes.
An API is an interface that application code uses to communicate with other code, which is typically stored in a software library. For more information on this term, check out Wikipedia’s Application programming interface
topic at http://en.wikipedia.org/wiki/Application_programming_interface .
This chapter sets the stage for teaching you the essential Java concepts that you need to understand before embarking on an Android app development career. I first answer the question: What is Java?
Next, I show you how to install the Java SE Development Kit (JDK) and introduce you to JDK tools for compiling and running Java applications.
After presenting a few simple example applications, I show you how to install and use the open source Eclipse IDE (integrated development environment) so that you can more easily (and more quickly) develop Java applications and (eventually) Android apps. I then provide you with a brief introduction to Android and show you how Java fits into the Android development paradigm.
What Is Java?
Java is a language and a platform originated by Sun Microsystems. In this section, I briefly describe this language and reveal what it means for Java to be a platform. To meet various needs, Sun organized Java into three main editions: Java SE, Java EE, and Java ME. This section briefly explores each of these editions.
Note
Java has an interesting history that dates back to December 1990. At that time, James Gosling, Patrick Naughton, and Mike Sheridan (all employees of Sun Microsystems) were given the task of figuring out the next major trend in computing. They concluded that one trend would involve the convergence of computing devices and intelligent consumer appliances. Thus was born the Green Project.
The fruits of Green were Star7, a handheld wireless device featuring a five-inch color LCD screen, a SPARC processor, a sophisticated graphics capability, a version of Unix, and Oak, a language developed by James Gosling for writing applications to run on Star7 that he named after an oak tree growing outside of his office window at Sun. To avoid a conflict with another language of the same name, Dr. Gosling changed this language’s name to Java.
Sun Microsystems subsequently evolved the Java language and platform until Oracle acquired Sun in early 2010. Check out http://oracle.com/technetwork/java/index.html for the latest Java news from Oracle.
Java Is a Language
Java is a language in which developers express source code (program text). Java’s syntax (rules for combining symbols into language features) is partly patterned after the C and C++ languages in order to shorten the learning curve for C/C++ developers.
The following list identifies a few similarities between Java and C/C++:
Java and C/C++ share the same single-line and multi-line comment styles. Comments let you document source code.
Many of Java’s reserved words are identical to their C/C++ counterparts (for, if, switch, and while are examples) and C++ counterparts (catch, class, public, and try are examples).
Java supports character, double precision floating-point, floating-point, integer, long integer, and short integer primitive types via the same char, double, float, int, long, and short reserved words.
Java supports many of the same operators, including arithmetic (+, -, *, /, and %) and conditional (?:) operators.
Java uses brace characters ({ and }) to delimit blocks of statements.
The following list identifies a few of the differences between Java and C/C++:
Java supports an additional comment style known as Javadoc.
Java provides reserved words not found in C/C++ (extends, strictfp, synchronized, and transient are examples).
Java doesn’t require machine-specific knowledge. It supports the byte integer type (see http://en.wikipedia.org/wiki/Integer_(computer_science)), doesn’t provide a signed version of the character type, and doesn’t provide unsigned versions of integer, long integer, and short integer. Furthermore, all of Java’s primitive types have guaranteed implementation sizes, which is an important part of achieving portability (discussed later). The same cannot be said of equivalent primitive types in C and C++.
Java provides operators not found in C/C++. These operators include instanceof and >>> (unsigned right shift).
Java provides labeled break and continue statements that you’ll not find in C/C++.
You’ll learn about single-line, multi-line, and Javadoc comments in Chapter 2. Also, you’ll learn about reserved words, primitive types, operators, blocks, and statements (including labeled break and labeled continue) in that chapter.
Java was designed to be a safer language than C/C++. It achieves safety in part by not letting you overload operators and by omitting C/C++ features such as pointers (storage locations containing addresses; see http://en.wikipedia.org/wiki/Pointer_(computer_programming) ).
Java also achieves safety by modifying certain C/C++ features. For example, loops must be controlled by Boolean expressions instead of integer expressions where 0 is false and a nonzero value is true. (There is a discussion of loops and expressions in Chapter 2.)
Suppose you must code a C/C++ while loop that repeats no more than 10 times. Being tired, you specify the following:
while (x)
x++;
Assume that x is an integer-based variable initialized to 0 (I discuss variables in Chapter 2). This loop repeatedly executes x++ to add 1 to x’s value. This loop doesn’t stop when x reaches 10; you have introduced a bug.
This problem is less likely to occur in Java because it complains when it sees while (x). This complaint requires you to recheck your expression, and you will then most likely specify while (x != 10). Not only is safety improved (you cannot specify just x), but meaning is also clarified: while (x != 10) is more meaningful than while (x).
These and other fundamental language features support classes, objects, inheritance, polymorphism, and interfaces. Java also provides advanced features related to nested types, packages, static imports, exceptions, assertions, annotations, generics, enums, and more. Subsequent chapters explore most of these language features.
Java Is a Platform
Java is a platform consisting of a virtual machine and an execution environment. The virtual machine is a software-based processor that presents an instruction set, and it is commonly referred to as the Java Virtual Machine (JVM). The execution environment consists of libraries for running programs and interacting with the underlying operating system (also known as the native platform).
The execution environment includes a huge library of prebuilt classfiles that perform common tasks, such as math operations (trigonometry, for example) and network communications. This library is commonly referred to as the standard class library.
A special Java program known as the Java compiler translates source code into object code consisting of instructions that are executed by the JVM and associated data. These instructions are known as bytecode. Figure 1-1 shows this translation process.
A978-1-4302-6455-2_1_Fig1_HTML.jpgFigure 1-1.
The Java compiler translates Java source code into Java object code consisting of bytecode and associated data
The compiler stores a program’s bytecode and data in files having the .class extension. These files are known as classfiles because they typically store the compiled equivalent of classes, a language feature discussed in Chapter 3. Figure 1-2 shows the organization of a classfile.
A978-1-4302-6455-2_1_Fig2_HTML.jpgFigure 1-2.
A classfile is organized into a magic number, version number, constant pool, and seven other sections
Don’t worry about having to know this classfile architecture. I present it to satisfy the curiosities of those who are interested in learning more about how classfiles are organized.
A Java program executes via a tool that loads and starts the JVM and passes the program’s main classfile to the machine. The JVM uses its classloader component to load the classfile into memory.
After the classfile has been loaded, the JVM’s bytecode verifier component makes sure that the classfile’s bytecode is valid and doesn’t compromise security. The verifier terminates the JVM when it finds a problem with the bytecode.
Assuming that all is well with the classfile’s bytecode, the JVM’s interpreter component interprets the bytecode one instruction at a time. Interpretation consists of identifying bytecode instructions and executing equivalent native instructions.
Note
Native instructions (also known as native code) are the instructions understood by the native platform’s physical processor.
When the interpreter learns that a sequence of bytecode instructions is executed repeatedly, it informs the JVM’s just-in-time (JIT) compiler to compile these instructions into native code.
JIT compilation is performed only once for a given sequence of bytecode instructions. Because the native instructions execute instead of the associated bytecode instruction sequence, the program executes much faster.
During execution, the interpreter might encounter a request to execute another classfile’s bytecode. When that happens, it asks the classloader to load the classfile and the bytecode verifier to verify the bytecode before executing that bytecode.
Also during execution, bytecode instructions might request that the JVM open a file, display something on the screen, or perform another task that requires cooperation with the native platform. The JVM responds by transferring the request to the platform via its Java Native Interface (JNI ) bridge to the native platform. Figure 1-3 shows these JVM tasks.
A978-1-4302-6455-2_1_Fig3_HTML.jpgFigure 1-3.
The JVM provides all of the necessary components for loading, verifying, and executing a classfile
The platform side of Java promotes portability by providing an abstraction over the underlying platform. As a result, the same bytecode runs unchanged on Windows, Linux, Mac OS X, and other platforms.
Note
Java was introduced with the slogan write once, run anywhere.
Although Java goes to great lengths to enforce portability (such as defining an integer always to be 32 binary digits [bits] and a long integer always to be 64 bits (see http://en.wikipedia.org/wiki/Bit to learn about binary digits), it doesn’t always succeed. For example, despite being mostly platform independent, certain parts of Java (such as the scheduling of threads, discussed in Chapter 7) vary from underlying platform to underlying platform.
The platform side of Java also promotes security by doing its best to provide a secure environment (such as the bytecode verifier) in which code executes. The goal is to prevent malicious code from corrupting the underlying platform (and possibly stealing sensitive information).
Note
Many security issues that have plagued Java have prompted Oracle to release various security updates. For example, blogger Brian Krebs reported on a recent update (at time of this writing) that fixes 51 security issues in his Critical Java Update Plugs 51 Security Holes
blog post ( http://krebsonsecurity.com/2013/10/java-update-plugs-51-security-holes/ ). Although troubling, Oracle is keeping on top of this ongoing problem (whose impact on Android is minimal).
Java SE, Java EE, and Java ME
Developers use different editions of the Java platform to create Java programs that run on desktop computers, web browsers, web servers, mobile information devices (such as feature phones), and embedded devices (such as television set-top boxes).
Java Platform, Standard Edition(Java SE): The Java platform for developing applications, which are stand-alone programs that run on desktops. Java SE is also used to develop applets, which are programs that run in web browsers.
Java Platform, Enterprise Edition(Java EE): The Java platform for developing enterprise-oriented applications and servlets, which are server programs that conform to Java EE’s Servlet API. Java EE is built on top of Java SE.
Java Platform, Micro Edition(Java ME): The Java platform for developing MIDlets, which are programs that run on mobile information devices, and Xlets, which are programs that run on embedded devices.
This book largely focuses on Java SE and applications.
Note
Oracle is also championing Java Embedded, a collection of technologies that brings Java to all kinds of devices (such as smartcards and vehicle navigation systems). Java SE Embedded and Java ME Embedded are the two major subsets of Java Embedded.
Installing the JDK and Exploring Example Applications
The Java Runtime Environment (JRE) implements the Java SE platform and makes it possible to run Java programs. The public JRE can be downloaded from Oracle’s Java SE Downloads page at www.oracle.com/technetwork/java/javase/downloads/index.html .
However, the public JRE doesn’t make it possible to develop Java (and Android) applications. You need to download and install the Java SE Development Kit (JDK), which contains development tools (including the Java compiler) and a private JRE.
Note
JDK 1.0 was the first JDK to be released (in May 1995). Until JDK 6 arrived, JDK stood for Java Development Kit (SE wasn’t part of the title). Over the years, numerous JDKs have been released, with JDK 7 being current at time of this writing.
Each JDK’s version number identifies a version of Java. For example, JDK 1.0 identifies Java 1.0, and JDK 5 identifies Java 5.0. JDK 5 was the first JDK also to provide an internal version number: 1.5.0.
The Java SE Downloads page also provides access to the current JDK, which is JDK 7 Update 45 at time of this writing. Click the appropriate Download button to download the current JDK’s installer application for your platform. Then run this application to install the JDK.
The JDK installer places the JDK in a home directory. (It can also install the public JRE in another directory.) On my Windows 7 platform, the home directory is C:\Program Files\Java\jdk1.7.0_06. (I currently use JDK 7 Update 6—I’m slow to upgrade.)
Tip
After installing the JDK, you should add the bin subdirectory to your platform’s PATH environment variable (see http://java.com/en/download/help/path.xml ) so that you can execute JDK tools from any directory. Also, you might want to create a projects subdirectory of the JDK’s home directory to organize your Java projects and create a separate subdirectory within projects for each of these projects.
The home directory contains various files (such as README.html, which provides information about the JDK, and src.zip, which provides the standard class library source code) and subdirectories, including the following three important subdirectories:
bin: This subdirectory contains assorted JDK tools. You’ll use only a few of these tools in this book, mainly javac (Java compiler) and java (Java application launcher). However, you’ll also work with jar (Java ARchive [JAR] creator, updater, and extractor—a JAR file is a ZIP file with special features), javadoc (Java documentation generator), and serialver (serial version inspector).
jre: This subdirectory contains the JDK’s private copy of the JRE, which lets you run Java programs without having to download and install the public JRE.
lib: This subdirectory contains library files that are used by JDK tools. For example, tools.jar contains the Java compiler’s classfiles. The compiler was written in Java.
Note
javac isn’t the Java compiler. It’s a tool that loads and starts the JVM, identifies the compiler’s main classfile (located in tools.jar) to the JVM, and passes the name of the source file being compiled to the compiler’s main classfile.
You execute JDK tools at the command line, passing command-line arguments to a tool. For a quick refresher on the command line and command-line arguments topics, check out Wikipedia’s Command-line interface
entry ( http://en.wikipedia.org/wiki/Command-line_interface ).
The following command line shows you how to use javac to compile a source file named App.java:
javac App.java
The .java file extension is mandatory. The compiler complains when you omit this extension.
Tip
You can compile multiple source files by specifying an asterisk in place of the filename, as follows: javac *.java
Assuming success, an App.class file is created. If this file describes an application, which minimally consists of a single class containing a method named main, you can run the application as follows:
java App
You must not specify the .class file extension. The java tool complains when .class is specified.
In addition to downloading and installing the JDK, you’ll need to access the JDK documentation, especially to explore the Java APIs. There are two sets of documentation that you can explore.
Oracle’s JDK 7 documentation (http://docs.oracle.com/javase/7/docs/api/index.html)
Google’s Java Android API documentation (https://developer.android.com/reference/packages.html)
Oracle’s JDK 7 documentation presents many APIs that are not supported by Android. Furthermore, it doesn’t cover APIs that are specific to Android. This book focuses only on core Oracle Java APIs that are also covered in Google’s documentation.
Hello, World!
It’s customary to start exploring a new language and its tools by writing, compiling, and running a simple application that outputs the Hello, World!
message. This practice dates back to Brian Kernighan’s and Dennis Ritchie’s seminal book, The C Programming Language.
Listing 1-1 presents the source code to a HelloWorld application that outputs this message.
Listing 1-1. Saying Hello in a Java Language Context
public class HelloWorld
{
public static void main(String[] args)
{
System.out.println(Hello, World!
);
}
}
This short seven-line application has a lot to say about the Java language. I’ll briefly explain each feature, leaving comprehensive discussions of these features to later chapters.
This source code declares a class, which you can think of as a container for describing an application. The first line, public class HelloWorld, introduces the name of the class (HelloWorld), which is preceded by reserved words (names that have meaning to the Java compiler and which you cannot use to name other things in your programs) public and class. These reserved words respectively tell the compiler that HelloWorld must be stored in a file named HelloWorld and that a class is being declared.
The rest of the class declaration appears between a pair of brace characters ({}), which are familiar to C and C++ developers. Between these characters is the declaration of a single method, which you can think of as a named sequence of code. This method is named main to signify that it's the entry point into the application, and it is the analog of the main() function in C and C++.
The main() method includes a header that identifies this method and a block of code located between an open brace character ({) and a close brace character (}). Besides naming this method, the header provides the following information:
public: This reserved word makes main() visible to the startup code that calls this method. If public wasn’t present, the compiler would output an error message stating that it couldn’t find a main() method.
static: This reserved word causes this method to associate with the class instead of associating with any objects (discussed in Chapter 3) created from this class. Because the startup code that calls main() doesn’t create an object from the class to call this method, it requires that the method be declared static. Although the compiler will not report an error when static is missing, it will not be possible to run HelloWorld, which will not be an application when the proper main() method doesn’t exist.
void: This reserved word indicates that the method doesn’t return a value. If you change void to a type’s reserved word (such as int) and then insert code that returns a value of this type (such as return 0;), the compiler will not report an error. However, you won’t be able to run HelloWorld because the proper main() method wouldn’t exist. (I discuss types in Chapter 2.)
(String[] args): This parameter list consists of a single parameter named args, which is of type String[]. Startup code passes a sequence of command-line arguments to args, which makes these arguments available to the code that executes within main(). You’ll learn about parameters and arguments in Chapter 3.
main() is called with an array of strings (character sequences delimited by double quote " characters) that identify the application’s command-line arguments. These strings are stored in String-based array variable args. (I discuss method calling, arrays, and variables in Chapters 2 and 3.) Although the array variable is named args, there’s nothing special about this name. You could choose another name for this variable.
main() presents a single line of code, System.out.println (Hello, World!
);, which is responsible for outputting Hello, World! in the command window from where HelloWorld is run. From left to right, this method call accomplishes the following tasks:
System identifies a standard class of system utilities.
out identifies an object variable located in System whose methods let you output values of various types optionally followed by a newline (also known as line feed) character to the standard output stream. (In reality, a platform-dependent line terminator sequence is output. On Windows platforms, this sequence consists of a carriage return character [integer value 13] followed by a line feed character [integer value 10]. On Linux platforms, this sequence consists of a line feed character. On Mac OS X systems, this sequence consists of a carriage return character. It's convenient to refer to this sequence as a newline.)
println identifies a method that prints its Hello, World!
argument (the starting and ending double quote characters are not written; these characters delimit but are not part of the string) followed by a newline to the standard output stream.
Note
The standard output stream is part of Standard I/O ( http://en.wikipedia.org/wiki/Standard_streams ), which also consists of standard input and standard error streams, and which originated with the Unix operating system. Standard I/O makes it possible to read text from different sources (keyboard or file) and write text to different destinations (screen or file).
Text is read from the standard input stream, which defaults to the keyboard but can be redirected to a file. Text is written to the standard output stream, which defaults to the screen but can be redirected to a file. Error message text is written to the standard error stream, which defaults to the screen but can be redirected to a file that differs from the standard output file.
Assuming that you’re familiar with your platform’s command-line interface and are at the command line, make HelloWorld your current directory and copy Listing 1-1 to a file named HelloWorld.java. Then compile this source file via the following command line:
javac HelloWorld.java
Assuming that you’ve included the .java extension, which is required by javac, and that HelloWorld.java compiles, you should discover a file named HelloWorld.class in the current directory. Run this application via the following command line:
java HelloWorld
If all goes well, you should see the following line of output on the screen:
Hello, World!
You can redirect this output to a file by specifying the greater than angle bracket (>) followed by a filename. For example, the following command line stores the output in a file named hello.txt:
java HelloWorld >hello.txt
DumpArgs
In the previous example, I pointed out main()’s (String[] args) parameter list, which consists of a single parameter named args. This parameter stores an array (think sequence of values) of arguments passed to the application on the command line. Listing 1-2 presents the source code to a DumpArgs application that outputs each argument.
Listing 1-2. Dumping Command-Line Arguments Stored in main()’s args Array to the Standard Output Stream
public class DumpArgs
{
public static void main(String[] args)
{
System.out.println(Passed arguments:
);
for (int i = 0; i < args.length; i++)
System.out.println(args[i]);
}
}
Listing 1-2’s DumpArgs application consists of a class named DumpArgs that’s very similar to Listing 1-1’s HelloWorld class. The essential difference between these classes is the for loop (a construct for repeated execution and starting with reserved word for) that accesses each array item and dumps it to the standard output stream.
The for loop first initializes integer variable i to 0. This variable keeps track of how far the loop has progressed (the loop must end at some point), and it also identifies one of the entries in the args array. Next, i is compared with args.length, which records the number of entries in the array. The loop ends when i’s value equals the value of args.length. (I discuss .length in Chapter 2.)
Each loop iteration executes System.out.println(args[i]) ;. The string stored in the ith entry of the args array is accessed and then output to the standard output stream—the first entry is located at index (location) 0. The last entry is stored at index args.length - 1. Finally, i is incremented by 1 via i++, and i < args.length is reevaluated to determine whether the loop continues or ends.
Assuming that you’re familiar with your platform’s command-line interface and that you are at the command line, make DumpArgs your current directory and copy Listing 1-2 to a file named DumpArgs.java. Then compile this source file via the following command line:
javac DumpArgs.java
Assuming that that you’ve included the .java extension, which is required by javac, and that DumpArgs.java compiles, you should discover a file named DumpArgs.class in the current directory. Run this application via the following command line:
java DumpArgs
If all goes well, you should see the following line of output on the screen:
Passed arguments:
For more interesting output, you’ll need to pass command-line arguments to DumpArgs. For example, execute the following command line, which specifies Curly, Moe, and Larry as three arguments to pass to DumpArgs:
java DumpArgs Curly Moe Larry
This time, you should see the following expanded output on the screen:
Passed arguments:
Curly
Moe
Larry
You can redirect this output to a file. For example, the following command line stores the DumpArgs application’s output in a file named out.txt:
java DumpArgs Curly Moe Larry >out.txt
EchoText
The previous two examples introduced you to a few Java language features, and they also showed outputting text to the standard output stream, which defaults to the screen but can be redirected to a file. In the final example (see Listing 1-3), I introduce more language features and demonstrate inputting text from the standard input stream and outputting text to the standard error stream.
Listing 1-3. Echoing Text Read from Standard Input to Standard Output
public class EchoText
{
public static void main(String[] args)
{
boolean isRedirect = false;
if (args.length != 0)
isRedirect = true;
int ch;
try
{
while ((ch = System.in.read()) != ((isRedirect) ? -1 : '\n'))
System.out.print((char) ch);
}
catch (java.io.IOException ioe)
{
System.err.println(I/O error
);
}
System.out.println();
}
}
EchoText is a more complex application than HelloWorld or DumpArgs. Its main() method first declares a Boolean (true/false) variable named isRedirect that tells this application whether input originates from the keyboard (isRedirect is false) or a file (isRedirect is true). The application defaults to assuming that input originates from the keyboard.
There’s no easy way to determine if standard input has been redirected, and so the application requires that the user tell it if this is the case by specifying one or more command-line arguments. The if decision (a construct for making decisions and starting with reserved word if) evaluates args.length != 0, assigning true to isRedirect when this Boolean expression evaluates to true (at least one command-line argument has been specified).
main() now introduces the int variable ch to store the integer representation of each character read from standard input. (You’ll learn about int and integer in Chapter 2.) It then enters a sequence of code prefixed by the reserved word try and surrounded by brace characters. Code within this block may throw an exception (an object describing a problem) and the subsequent catch block will handle it (to address the problem). (I discuss exceptions in Chapter 5.)
The try block consists of a while loop (a construct for repeated execution and starting with the reserved word while) that reads and echoes characters. The loop first calls System.in.read() to read a character and assign its integer value to ch. The loop ends when this value equals -1 (no more input data is available from a file; standard input was redirected) or '\n' (the newline/line feed character has been read, which is the case when standard input wasn’t redirected.) '\n' is an example of a character literal, which is discussed in Chapter 2.
For any other value in ch, this value is converted to a character via (char), which is an example of Java’s cast operator (discussed in Chapter 2). The character is then output via System.out.print(), which doesn’t also terminate the current line by outputting a newline. The final System.out.println() ; call terminates the current line without outputting any content.
When standard input is redirected to a file and System.in.read() is unable to read text from the file (perhaps the file is stored on a removable storage device that has been removed before the read operation), System.in.read() fails by throwing a java.io.IOException object that describes this problem. The code within the catch block is then executed, which outputs an I/O error message to the standard error stream via System.err.println(I/O error
);.
Note
System.err provides the same families of println() and print() methods as System.out. You should only switch from System.out to System.err when you need to output an error message so that the error messages are displayed on the screen, even when standard output is redirected to a file.
Compile Listing 1-3 via the following command line:
javac EchoText.java
Now run the application via the following command line:
java EchoText
You should see a flashing cursor. Type the following text and press Enter:
This is a test.
You should see this text duplicated on the following line and the application should end.
Continue by redirecting the input source to a file, by specifying the less than angle bracket (<) followed by a filename:
java EchoText
Although it looks like there are two command-line arguments, there is only one: x. (Redirection symbols followed by filenames don’t count as command-line arguments.) You should observe the contents of EchoText.java listed on the screen.
Finally, execute the following command line:
java EchoText
This time, x isn’t specified, so input is assumed to originate from the keyboard. However, because the input is actually coming from the file EchoText.java, and because each line is terminated with a newline, only the first line from this file will be output.
Note
If I had shortened the while loop expression to while ((ch = System.in.read()) != -1) and didn’t redirect standard input to a file, the loop wouldn’t end because -1 would never be seen. To exit this loop, you would have to press the Ctrl and C keys simultaneously on a Windows platform or the equivalent keys on a non-Windows platform.
Installing and Exploring the Eclipse IDE
Working with the JDK’s tools at the command line is probably okay for small projects. However, this practice isn’t recommended for large projects, which are hard to manage without the help of an IDE.
An IDE consists of a project manager for managing a project’s files, a text editor for entering and editing source code, a debugger for locating bugs, and other features. Eclipse is a popular IDE that Google supports for developing Android apps.
Note
For convenience, I use JDK tools throughout this book, except for this section where I discuss and demonstrate the Eclipse IDE.
Eclipse IDE is an open source IDE for developing programs in Java and other languages (such as C, COBOL, PHP, Perl, and Python). Eclipse Standard is one distribution of this IDE that’s available for download; version 4.3.1 is the current version at time of this writing.
You should download and install Eclipse Standard to follow along with this section’s Eclipse-oriented example. Begin by pointing your browser to www.eclipse.org/downloads/ and completing the following tasks.
1.
Scroll down the page until you see an Eclipse Standard entry. (It may refer to 4.3.1 or a newer version.)
2.
Click one of the platform links (such as Windows 64 Bit) to the right of this entry.
3.
Select a download mirror from the subsequently displayed page, and proceed to download the distribution’s archive file.
I downloaded the eclipse-standard-kepler-SR1-win32-x86_64.zip archive file for my Windows 7 platform, unarchived this file, moved the resulting eclipse home directory to another location, and created a shortcut to that directory’s eclipse.exe file.
After installing Eclipse Classic, run this application. You should discover a splash screen identifying this IDE and a dialog box that lets you choose the location of a workspace for storing projects followed by a main window like the one shown in Figure 1-4.
A978-1-4302-6455-2_1_Fig4_HTML.jpgFigure 1-4.
Keep the default workspace or choose another workspace
Click the OK button, and you’re taken to Eclipse’s main window. See Figure 1-5.
A978-1-4302-6455-2_1_Fig5_HTML.jpgFigure 1-5.
The main window initially presents a Welcome tab
The main window initially presents a Welcome tab from which you can learn more about Eclipse. Click this tab’s X icon to close this tab; you can restore the Welcome tab by selecting Welcome from the menu bar’s Help menu.
The Eclipse user interface is based on a main window that consists of a menu bar, a tool bar, a workbench area, and a status bar. The workbench presents windows for organizing Eclipse projects, editing source files, viewing messages, and more.
To help you get comfortable with the Eclipse user interface, I’ll show you how to create a DumpArgs project containing a single DumpArgs.java source file with Listing 1-2’s source code. You’ll also learn how to compile and run this application.
Complete the following steps to create the DumpArgs project.
1.
Select New from the File menu and Java Project from the resulting pop-up menu.
2.
In the resulting New Java Project dialog box, enter DumpArgs into the Project name text field. Keep all of the other defaults, and click the Finish button.
After the second step (and after closing the Welcome tab), you’ll see a workbench similar to the one shown in Figure 1-6.
A978-1-4302-6455-2_1_Fig6_HTML.jpgFigure 1-6.
A DumpArgs entry appears in the workbench’s Package Explorer
On the left side of the workbench, you’ll see a window titled Package Explorer. This window identifies the workspace’s projects in terms of packages (discussed in Chapter 5). At the moment, only a single DumpArgs entry appears in this window.
Clicking the triangle icon to the left of DumpArgs expands this entry to reveal src and JRE System Library items. The src item stores the DumpArgs project’s source files, and the JRE System Library item identifies various JRE files that are